In this article, we will write a C program to add two numbers using function.
The program takes two numbers from the user as input and prints their sum on the screen as output.
Sample Input:
Enter two numbers: 10 20
Output:
Sum of the two numbers is: 30
To calculate the sum of two numbers, we have defined a function add()
which takes two numbers as arguments and returns their sum.
// C program to add two numbers using a function #include <stdio.h> // Function declaration int add(int, int); int main(){ int num1, num2, res; printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); // Call the add() function res = add(num1, num2); // Print the result printf("Sum of the two numbers is: %d", res); return 0; } // User defined function to add two numbers int add(int a, int b){ int sum; sum = a + b; return sum; }
Output:
Enter two numbers: 10 20 Sum of the two numbers is: 30
Code Explanation:
- The program takes two numbers as input from the user and stores them in the
num1
andnum2
variables respectively. - To get the sum of the two numbers, we have defined a function
add()
. Theadd()
function takes two arguments and returns their sum. - The sum returned by the
add()
function is stored in theres
variable. - Finally, the sum of the two numbers is printed on the screen using the print() function.
Thanks for reading.