Decode School

Decode School - The School for Problem Solvers

Welcome to my blog. Subscribe and get my latest blog post in your inbox.

C Program to calculate sum of N given numbers

Get input n and n inputs and calculate the sum of n inputs.

Sample Input 1:

4 6 5 3 2

Sample Output 1:

16(6+5+3+2)

Program or Solution

					    
							
#include<stdio.h>
int main()
{
	int n,i,num,sum=0;
	printf("Enter number of numbers to sum:");
	scanf("%d",&n);
	printf("Enter %d numbers to sum:"n);
	for(i=1;i<=n;i++)
	{
		scanf("%d",&num);
		sum=sum+num;
	}
	printf("The sum is:%d",sum);
	return 0;
}
					    
					

Program Explanation

Instruction(s) inside the for block{} are executed repeatedly till the second expression (i<=n) is true.

Here i is initialized to 1 and incremented by 1 for each iteration, instructions inside the for block are executed unless i becomes greater than n.

so value of num given by user will be added to sum at each iteration.

after adding all n numbers given by user to sum, sum will be printed using printf statement.