C Program to Add Two Numbers using Function

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 and num2 variables respectively.
  • To get the sum of the two numbers, we have defined a function add(). The add() function takes two arguments and returns their sum.
  • The sum returned by the add() function is stored in the res variable.
  • Finally, the sum of the two numbers is printed on the screen using the print() function.

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts