C program to find sum of n numbers using function – To get the sum, the program contains a user defined sum function that receives a number as an argument, sum all numbers e.g. 1+2+3.. and returns the result.
e.g. if you want to get sum of numbers from 1 to 5 i.e. 1+2+3+4+5, then you need to enter number 5. the function will sum numbers from 1 to 5.
Test case:
Enter number 3
sum : 6
Program description:
Use a for loop in C program below and loop through the number from 1 to given number and sum all using statement sum += i. It can also be written as sum = sum +i;
C code to find sum of n numbers using function
/*
* C program to find sum of n numbers using function
*/
#include<stdio.h>
/*Write sum function that recieves the number
* as an argument up to which you want to sum.
* Return the total sum
*/
int sum(int num){
int i;
int sum =0;
//Loop through from 1 to num e.g.
//if number is 3 so index will start from
// 1 to 3 and sum will be as = 1+2+3 = 6
for(i=1; i<=num; ++i){
sum += i; // Also, this can be written as sum = sum +i;
}
return sum;
}
/*
* Test sum of n numbers
*/
int main(){
int num =0;
int result =0;
printf("Enter number ");
//Read the number up to which you want sum
scanf("%d", &num);
//call sum function that will return sum
result = sum(num);
printf("sum : %d ",result);
return 0;
}
Output:
Enter number 3
sum : 6