Skip to main content

Sum Values

Suppose we wanted to write a program that will ask the user to enter numbers, using 0 to indicate that they have finish entering numbers. The program will then print out the sum of all the values.

Here is a sample run:

Please enter a number (0 to exit): 15
Please enter a number (0 to exit): 5
Please enter a number (0 to exit): -2
Please enter a number (0 to exit): 0
Total of all values entered was: 18

What are the steps?

Think about what you will need to do... of those things, what do you already know how to do? Expand for solution:

Click to see steps
  1. create a total to track sum
  2. prompt user for a number
  3. read in the number
  4. check if number is 0
  5. update the total
  6. repeat the prompt, read, update
  7. Once a zero is entered print total

Looking at the above, we actually know how to do most of this program. The only thing we need to add to this problem is a way to repeat the prompt/read and sum. This flow chart shows how the program can be constructed

We already know how to do some of this so we will put together the functions that we already know how to write:

#include <stdio.h>
//declare what functions we will have:
int getNumber();
int main(void)
{
int total=0;
int number = getNumber();
//ToDo:
//check number, update total, prompt and read again
return 0;
}
int getNumber()
{
int number;
printf("Please enter a number (0 to exit): ");
scanf("%d", &number);
return number;
}

In this example, we have a situation where we are reading in a number. We then repeatedly check that number, update a total, and read in a new number. We do this as long as the number entered is not 0. This is an example of a loop where we do not know how many times the loop will run. It is possible that the user enters 0 right away. It is also possible that the user enters many many numbers. Point is, the number of iterations is not something that we can easily count. In cases like this, the type of loop we would wish to use is called a while loop. A while loop has the following syntax:

while (<check to keep going with loop>){
//things we do each time go here. make sure
//there is something in here that will update
//the values used in the check or you will get
//stuck!
}

Putting all of this together, our program ends up looking like this:

#include <stdio.h>
//declare what functions we will have:
int getNumber();
int main(void)
{
int total=0;
int number = getNumber();
//while the number entered isn't 0
while (number != 0){
total += number; //update total
number = getNumber(); //prompt and read
}

//once the loop is done, print total:
printf("Total of all values entered was: %d\n",total);
return 0;
}
int getNumber()
{
int number;
printf("Please enter a number (0 to exit): ");
scanf("%d", &number);
return number;
}