This C program reads a sequence of positive integers as input by the user and print their sum. The program keeps on taking the input from user until user enters number ( 0 ) and program calculates the sum of all input numbers. Finally this C program prints the sum of all the numbers on screen and terminates.

This program is an excellent demonstration of using do-while loop of C Programming.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <stdio.h> #define SENTINEL 0 int main(void) { int sum = 0; /* The sum of numbers already read */ int current; /* The number just read */ do { printf("\nEnter an integer > "); scanf("%d", ¤t); if (current > SENTINEL) sum = sum + current; } while (current > SENTINEL); printf("\nThe sum is %d\n", sum); } |

Sample output of the C Program is:

1 2 3 4 5 6 7 8 9 10 |
Enter an integer > 3 Enter an integer > 4 Enter an integer > 6 Enter an integer > 7 Enter an integer > 8 Enter an integer > 45 Enter an integer > 56 Enter an integer > 0 The sum is 129 |