C Program to Add Sequence of Numbers

mycplus

mycplus

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.

#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", &current);
    if (current > SENTINEL)
      sum = sum + current;
  } 
  while (current > SENTINEL);
   
  printf("\nThe sum is %d\n", sum);
}

Output of the C Program is:

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
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post