The program segment given below accepts numbers from the keyboard until we enter a zero or a negative number and calculates their sum excluding the last number.
printf("Enter positive numbers (0 or -ve number to stop):\n"); sum = 0; scanf ("%d", &num); while (num > 0) { sum += num; scanf ("%d", &num); } printf ("Sum = %d ", sum);
The variables num and sum (both of type int) are used to represent a number entered from keyboard and the sum of the numbers, respectively. Initially, variable sum is initialized to zero and the first number is read in variable num. A while loop is then set up in which we add a number to sum and accept next number. The body of the loop is executed as long as the entered number is positive. The output obtained by executing the program containing the above code is given below.
Enter positive numbers (0 or -ve number to stop): 10 15 20 50 0 Sum = 95
Note the use of a scanf statement to read a number before the while loop. Another scanf statement is required within the while loop to read subsequent numbers. Compare this while loop with that in the previous example (money payment) which requires only one scanf statement.
Example:
#include<stdio.h> void main() { int num,sum; clrscr(); printf("Enter positive numbers (0 or -ve number to stop):\n"); sum = 0; scanf ("%d", &num); while (num > 0) { sum += num; scanf ("%d", &num); } printf ("Sum = %d ", sum); getch(); }