#include<stdio.h> int sum(int a, int b); //function prototype declaration int main() { int c; c = sum(2, 5); //function call printf("The value of c is %d\n", c); return 0; } int sum (int a, int b){ int result; result = a+b; #include<stdio.h> // function for taking input from user int input() { int n; printf("Up to which number you want to find the sum: "); scanf("%d", &n); return n; } // function to find sum of two numbers int sum(int num) { int add = 0; for(int i=1; i<=num; i++) { add += i; } return add; } // function for displaying the result void display(int n, int sum) { printf("1+2+3+….+%d+%d = %d",n-1, n, sum); } int main() { int range, result; range = input(); result = sum(range); display(range, result); }
Using More Than One Function
Sum Function:- Write a C program to find the sum of n numbers using functions. Define three functions input(), sum(), and display(). Take input from the user in the input() function and return it to the main function. Find the sum of n numbers in the sum() function, return the sum value to the main function. Print result using display() function.
In this program, we defined a function sum() which takes one argument. Using for loop, the function sum() finds the sum of series 1+2+…+(n-1)+n; Later this value is returned back to the caller Sum function.
Inside the (Sum Function) main function, we asked the user to enter the range up to which you want to find the sum? The entered value from the user is passed to the function sum() as an argument. When compiler encounters result = sum(range); then control goes to function sum() with argument. After completion of the execution of the function, control came back to the main function with some value. The returned value from the function is stored in the variable result. Finally, the result has displayed on the screen.
⭐
Rating: 1 out of 5.