I am having a bit of an issue with this problem. I am taking a Pascal programming class and this problem was in my logic book. I am required to have the user enter a series of (+) numbers and once he/she enters a (-) number, the program should find the sum of all the (+) numbers. I accomplished this, but now I am attempting part two of this problem, which requires me to utilize a nested loop to run the program x amount of times based on the user's input.
I do not know how to rerun the summation process based on a number the user enters. In other words, the program is required to
1) Ask the user how many times he/she would like to run the program
2) Begin the nested loop that prompts the user for a series of positive numbers
3) User enters numbers as loop asks for them
4) A negative number then signals the end of the series
5) After the repeat until loop, the program should then add all of the positive numbers together
steps 2-4 is one iteration of the program. I need this to run x amount of times, of course, based on user input.
The following code is what I have so far and honestly I am stumped:
program summation;
var num, sum, counter, userValue : integer;
begin
writeln('Run program how many times?');
readln(userValue);
for counter := 1 to userValue do
begin
sum := 0;
repeat
writeln('Enter a number: ');
readln(num);
if num >= 0 then
begin
sum := num + sum;
end;
until num < 0;
writeln('The sum is: ', sum);
readln();
end;
end.
Update [6/27] 3:40 Pacific Time
Output:
I attempted to upload an image of the output, but I require 10 rep points. Anyway, the program's output is as follows:
How many times would you like the program to run?
2
Enter a number:
1
Enter a number:
1
Enter a number:
-1 <-- negative number signals one iteration of the nested loop
Enter a number:
2
Enter a number:
-3 <-- negative number signals one iteration of the nested loop
The sum is: 6
The negative number signals the program to stop an iteration. However, I would like the program to repeat the summation of a sequence three times.
Update [6/27] 7:25PM Pacific Time
Currently my program executes correctly. By correctly I mean it (1) Asks the user how many times he/she would like to run it. (2) The nested loop begins and prompts user for a series of numbers. (3) Once a negative number is entered it signals the end of the series. (4) The program sums the positive numbers. (5) The program restarts by asking the user for another series of numbers. (6) Once again a negative number ends the series. (7) Error begins here: Once the program iterates (series of number prompts) according to the user defined number, it adds all of the sums from previous iterations to the final sum. This is not my goal. My goal is to have separate sums (one for each run) not all sums "summed" at the final iteration.
In summary (pun intended), your final corrected listing is:
program summation;
var num, sum, counter, userValue : integer;
begin
{ Prompt the user for how many times they wish to sum up a list of numbers }
writeln('Run program how many times?');
readln(userValue);
{ For each time the user wants to sum numbers, prompt them for the numbers }
for counter := 1 to userValue do
begin
sum := 0; { start with a sum of 0 for this list }
{ Repeatedly request a number from the user until they enter a negative to end }
repeat
{ Prompt for and get the number }
writeln('Enter a number: ');
readln(num);
if num >= 0 then
sum := num + sum; { add the number to the sum if it's not negative }
until num < 0; { finish with this sum if the number entered is negative }
{ Write out the last calculated sum }
writeln('The sum is: ', sum);
readln; { Let the user press enter to go around and request another sum }
end;
end.
In numPromptLoop change the name of the NUM parameter to SUM
Related
First time I am learning algorithms and trying to figure out with stratch. I am following tutorials on Stratch wiki. How can I convert this to algorithm?( with flow chart or normal steps). Especially the loop.( I uploaded as picture) Please click here to see picture
I Started:
Step:1 Start
Step2: İnt: delete all of numbers, iterator, amount,sum
Step3: How many numbers you want?
Step4:initialize sum=0,amount=0,iterator=1
Step5: Enter the elements values
Step6: found the sum by using loop in array and update sum value in which loop must be continue till (no of elements-1 ) times
Step7:avg=sum/no of elements
Step8: Print the values average
I don't think It's true. I mean I feel there are errors? Thank you for time.
Scratch
Here is the algorithm in variant 2 (see Java algorithm below) in Scratch. The output should be identical.
Java
Here is the algorithm in Java where I did comment the steps which should give you a step-by-step guide on how to do it in Scratch as well.
I have also implemented two variants of the algorithm to show you some considerations that a programmer often has to think of when implementing an algorithm which mainly is time (= time required for the algorithm to complete) and space (= memory used on your computer).
Please note: the following algorithms do not handle errors. E.g. if a user would enter a instead of a number the program would crash. It is easy to adjust the program to handle this but for simplicity I did not do that.
Variant 1: Storing all elements in array numbers
This variant stores all numbers in an array numbers and calculates the sum at the end using those numbers which is slower than variant 2 as the algorithm goes over all the numbers twice. The upside is that you will preserve all the numbers the user entered and you could use that later on if you need to but you will need storage to store those values.
public static void yourAlgorithm() {
// needed in Java to get input from user
var sc = new Scanner(System.in);
// print to screen (equivalent to "say"/ "ask")
System.out.print("How many numbers do you want? ");
// get amount of numbers as answer from user
var amount = sc.nextInt();
// create array to store all elements
var numbers = new int[amount];
// set iterator to 1
int iterator = 1;
// as long as the iterator is smaller or equal to the number of required numbers, keep asking for new numbers
// equivalent to "repeat amount" except that retries are possible if no number was entered
while (iterator <= amount) {
// ask for a number
System.out.printf("%d. number: ", iterator);
// insert the number at position iterator - 1 in the array
numbers[iterator - 1] = sc.nextInt();
// increase iterator by one
iterator++;
}
// calulate the sum after all the numbers have been entered by the user
int sum = 0;
// go over all numbers again! (this is why it is slower) and calculate the sum
for (int i = 0; i < amount; i++) {
sum += numbers[i];
}
// print average to screen
System.out.printf("Average: %s / %s = %s", sum, amount, (double)sum / (double)amount);
}
Variant 2: Calculating sum when entering new number
This algorithm does not store the numbers the user enters but immediately uses the input to calculate the sum, hence it is faster as only one loop is required and it needs less memory as the numbers do not need to be stored.
This would be the best solution (fastest, least space/ memory needed) in case you do not need all the numbers the user entered later on.
// needed in Java to get input from user
var sc = new Scanner(System.in);
// print to screen (equivalent to "say"/ "ask")
System.out.print("How many numbers do you want? ");
// get amount of numbers as answer from user
var amount = sc.nextInt();
// set iterator to 1
int iterator = 1;
int sum = 0;
// as long as the iterator is smaller or equal to the number of required numbers, keep asking for new numbers
// equivalent to "repeat amount" except that retries are possible if no number was entered (e.g. character was entered instead)
while (iterator <= amount) {
// ask for a number
System.out.printf("%d. number: ", iterator);
// get number from user
var newNumber = sc.nextInt();
// add the new number to the sum
sum += newNumber;
// increase iterator by one
iterator++;
}
// print average to screen
System.out.printf("Average: %s / %s = %s", sum, amount, (double)sum / (double)amount);
Variant 3: Combining both approaches
You could also combine both approaches, i. e. calculating the sum within the first loop and additionally storing the values in a numbers array so you could use that later on if you need to.
Expected output
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm supposed to write 5 pseudocodes for algorithms below and I'm kinda stuck. The things I've done are below the tasks, I know last 3 are meaningless. Would appreciate any help or tips. Thanks
• Printing the largest number from the input
Title: Print Largest Number From Input
//works with number inputs
max=0
number= getNumber()
read number
if number == NONE
print (“NO VALID DATA”)
while number != NONE
if number > max
max = number
• Printing the largest even integer value from the input
Title: Print Largest Even Integer Number From Input
//works with even integer inputs
max=0
integer number= getNumber()
read_integer number
if number == NONE
print “NO VALID DATA”
if number % 2 == 0
print(“NO VALID DATA”)
while number != NONE && number % 2 != 0
if number > max
max = number
• Printing the sum of all input integers
Title: Print Sum of All Input Integers
int Number= getNumber()
read_integer Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
print li[1] + li[2] + li[3] + ……. + li[n]
• Printing the arithmetic mean of all input numbers
Title: Print Arithmetic Mean of All Input Numbers
Number= getNumber()
read Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
print li[1] + li[2] + li[3] + ……. + li[n] / n
• Printing all values greater or equal to the arithmetic mean of all input numbers
Title: Print All Values Greater Than or Equal to the Aritmetic Mean of All Input Numbers
Number= getNumber()
read Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
arithmetic_mean = li[1] + li[2] + li[3] + ……. + li[n] / n
print(“”)
I'm guessing this is for class homework, so I wont provide full answers, but I'll try to help.
1. Print the largest number from the input
max = 0
// Assume that getNumber reads an input from the user and returns NONE if it is not a valid number
number = getNumber()
// If they never enter a number, give an error
if number == NONE:
print(“NO VALID DATA”)
exit() // exit the program
// Keep doing the following until number is set to NONE
while number != NONE:
if number > max:
max = number
number = getNumber()
print("The largest number is:")
print(max)
It seems like you basically have the right idea here. One thing to remember is that you have to getNumber() inside the loop. Otherwise, the value of number will never change because you only read the input once.
Note: this algorithm doesn't work if they only ever enter negative numbers. Setting max to negative infinity would fix that.
2. Print the largest even integer value from the input
This is exactly the same idea. The only change you have to make is ignoring every number that isn't even. You have the right idea for checking even-ness with the % operator.
Be careful where you make this check, though. If you check in the condition of the while loop, like you do in your code, then the loop will exit (and your program will stop) as soon as they enter an odd number. If you don't want that, then keep the loop running and just don't ever set max to be an odd number.
3. Print the sum of all input integers
It seems like your idea here is to save all the numbers they input to a list and then sum up the list at the end. That would work fine if you want to do that, but it's not necessary. Just like you kept track of a running max value, you could keep track of a running sum. Just add your the input to it each time. This is generally called the "accumulator pattern" if you want to look it up.
4. Print the arithmetic mean of all input numbers
Again, it looks like you are trying to store all the numbers in a list. Again, not necessary. Calculating the mean is just like calculating the sum except you need to divide by the number of inputs at the end. So, in addition to keeping track of the sum, you need to add an additional "accumulator" for n and just add 1 to it each time.
Also, it looks like you might be a little confused about what while does. while works just like if. It checks if a condition is true, and, if it is, it runs the code beneath it. The only difference is that while will keep running that code again and again until the condition is false. So the line while li.length == n doesn't make any sense. you haven't declared what n is before hand, so it can't make this comparison. I'm guessing you meant to do something like:
while number != NONE:
n = li.length
Here, you are assigning n to be the length of the list, instead of checking if the list length is equal to n or not.
5. Print all values greater or equal to the arithmetic mean of all input numbers
Here, we actually need to save all the inputs to a list, because we can't know what the mean is until we have seen all the numbers.
I would break this into three parts. First, just get all the input numbers and save them to a list. Then, calculate the mean of the list. Lastly, step through the list and print every value that's larger than the mean.
For part 1, just use the same pattern with a while loop that you have been since the first problem, but append number to a list instead of adding it to a sum.
For part 2, you need to calculate the sum of the list. In your code, you wrote li[1] + li[2] + li[3] + ……. + li[n]. The way you express this in code is probably with a for loop. I recommend looking up for loops for the language you are working in and seeing how they work. In some languages, you might be able to do something like this:
sum = 0
for number in list:
sum = sum + number
or, it might look like this:
sum = 0
for index in 0...list.length:
sum = sum + list[index]
For part 3, now that you have calculated the mean, you just need to loop through the numbers again and print the ones that are bigger than the mean.
for number in list:
if number > mean:
print(number)
I'm having some problems with my program in Pascal. I need to create a program which will calculate even and odd sums of a number's decomposition. For example, if my number is 10 the program should write that sum of even numbers is 30 (since 2,4,6,8,10 are the even numbers) and it should write that sum of odd numbers is 25 (since 1,3,5,7,9 are odd numbers). Here is what i tried
program odd_even;
var
a,sumeven,sumodd,even,odd : integer;
begin
writeln('Enter a number : ');
readln(a);
if a mod 2 = 0 then a=even;
if a mod 2 not=0 then a=odd;
for a:1 to a do begin
sumeven:=0;
sumeven:=sumeven+even
writeln('Sum of even numbers is : ',sumeven);
sumodd:=0;
sumodd:=sumodd+odd;
writeln('Sum of odd numbers is : ',sumodd),
end;
readln
end.
The compiler says that my if part is illegal but I don't understand how I can fix it, I also tried with else but it says the same thing. If someone could help me out I would be really thankful.
First of all, welcome to the world of programming!
There are several errors in your code:
The initialization of your result variables
sumEven:=0;
sumOdd:=0;
should be before your for loop
checking odd/even
if a mod 2 = 0 then a=even;
if a mod 2 not=0 then a=odd;
should be inside your loop and you should check not whether a (your input number) is odd/even but the value of your loop variable:
for i := 1 to a do
begin
if (i mod 2 <> 0) then sumOdd := sumOdd+1 else sumEven := sumEven+1 ;
end;
Printing the results should be of course after your loop.
Good luck!
Hi i am working on a random number generator which i faced a road block. I have done my program but i'm quite lost on how to do a loop for the C++ program to keep on looping. following below is the conditions for program:
The program prompts the user to enter a number.
This number determines the number of times the loop will repeat. The number ranges from 0 to 100. Validate this range.
The program uses a random number to generate a number from 0 to 9999 and then
checks if the generated number contains the digit 1, digit 2 or digit 3.
Please advise on how do i require to do a switch or while loop for point 3.
your inputs is greatly appreciated.
Easiest way to check would be to use the mod operation and division to extract every digit.
A loop would be something like
int randInt = randomFunction();
while(randInt > 0){
//Get Last Digit
int lastDigit = randInt % 10;
switch(lastDigit){
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
}
/*
Divide the number by 10 to remove the last digit.
Integers will automatically truncate remainders.
i.e int a = 21/10, a will = 2
*/
randInt /= 10;
}
I've been trying lately to write a program(a text based game) but I only know some commands and don't understand every command very well.
What I am trying to do is a hit chance. Lets say that I want the program to have
90% chance of choosing number 1 (which means hit) and
10% to choose number 0 (which means miss).
I saw the same question Here but I don't understand the commands because I've never used them (I'm talking about set.seed and sample). Could someone explain to me how do they work? Is there another way (easier to understand? I don't mind if it consumes more resource)
program Project1;
{$ASSERTIONS ON}
function getProb(aProbability: Integer): boolean;
begin
result := aProbability > (100 - random(100));
end;
procedure miss;
begin
writeln('miss');
end;
procedure hit;
begin
writeln('hit');
end;
var
i, success, probability, errorMarge: Integer;
const
combat: array[boolean] of procedure = (#miss, #hit);
begin
// show that getProb() is reliable
errorMarge := 4;
success := 0;
probability := 80;
for i in [0..99] do
Inc(success, Byte(getProb(probability)));
assert(success >= probability - errorMarge);
success := 0;
probability := 50;
for i in [0..99] do
Inc(success, Byte(getProb(probability)));
assert(success >= probability - errorMarge);
// example usage
combat[getProb(20)];
combat[getProb(80)];
combat[getProb(90)];
readln;
end.
Not knowing what "commands" you know, this is hard to answer w/o generalizing.
If you only need to choose between two values, then generate a random value in whatever range you know how to, and compute the dividing line based on your probability. So, for your example, if you can generate a value between 0 and 1, if it is <= 0.9, hit.
This can be extended to multiple values by adding the successive probabilities. So if you have 4 values to choose between, each with 25% probability, get you random value between 0 and 1: if it is less than 0.25, choose 0 else if less than 0.5, choose 1 else if less than 0.75 choose 2 otherwise choose 3.