In this program, user first enters the count of integers that he wants to add. Then we take N integers as input from user using scanf function inside a for loop and keep on adding it to a variable sum. Once user finished entering N integers we print sum of all N integers on screen. Here we are using addition arithmetic operator('+') to add numbers.
Check this tutorial for detailed explanation of Arithmetic operators.
C program to calculate sum of N numbers using for loop and without using array
#include <stdio.h> int main(){ int numberCount=0, number, counter, sum=0; printf("Enter the number of integers to add: "); scanf("%d",&numberCount); printf("Enter %d numbers\n",numberCount); for(counter = 0; counter < numberCount; counter++){ scanf("%d", &number); sum = sum + number; } printf("SUM = %d", sum); return 0; }Output
Enter the number of integers to add: 5 Enter 5 numbers 1 2 3 4 5 SUM = 15
C program to calculate sum of N numbers using array
In this program we first store all the numbers entered by user in an integer array. Then we traverse this array from index 0 to N-1 and add all numbers using a for loop and '+' operator. In line number 21, we can also uses shorthand assignment operators '+=' for addition. Check this tutorial for detailed explanation of Shorthand assignment operators.
#include <stdio.h> int main(){ /* Using array of size 500 to store input numbers */ int numberCount=0, numbers[500], counter, sum=0; printf("Enter the number of integers to add: "); scanf("%d",&numberCount); printf("Enter %d numbers\n", numberCount); for(counter = 0; counter < numberCount; counter++){ scanf("%d", &numbers[counter]); } for(counter = 0; counter < numberCount; counter++){ sum = sum + numbers[counter]; } printf("SUM = %d", sum); return 0; }Output
Enter the number of integers to add: 7 Enter 5 numbers 7 6 5 4 3 2 1 SUM = 28
C program to calculate sum of N numbers using recursion
We can use recursion to find sum of N numbers by breaking a problem into smaller problem. Function "getSum(int numberCount)" takes numberCount numbers as input and adds them recursively and returns the result to calling function.
#include <stdio.h> int getSum(int numberCount); int main(){ int numberCount=0, number, counter, sum=0; printf("Enter the number of integers to add: "); scanf("%d",&numberCount); printf("Enter %d numbers seperated by space \n", numberCount); sum = getSum(numberCount); printf("SUM = %d", sum); return 0; } int getSum(int numberCount){ int sum=0; /* exit condition */ if(0 == numberCount) return 0; scanf("%d", &sum); /* Recursively call getSum for numberCount-1 */ return sum + getSum(numberCount - 1); }Related Topics