In this tutorial, you will learn how to write a C program to add two numbers. This is a very basic C program where user is asked to enter two integers and then program takes those inputs, stores them in two separate variables and displays the sum of these integers.
We will write two programs to find the sum of two integer numbers entered by user. In the first program, the user is asked to enter two integer numbers and then program displays the sum of these numbers. In the second C program we are doing the same thing using user defined function.
Example 1: Program to add two integer numbers
In the following example, there are two int variable num1
and num2
. These variables are there to store the user entered numbers. User input is captured by scanf() function. Once the entered values are stored in num1
and num2
, a simple arithmetic operation (num1+num2) is performed to find out the sum of num1
and num2
.
Once the sum of two numbers is calculated and stored in a new variable sum, the program prints the value of sum as an output using printf() function.
#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter two integers: ");
//Storing user input into variable num1 & num2
scanf("%d %d", &num1, &num2);
// Adding two input numbers
sum = num1 + num2;
printf("Sum of %d and %d is: %d", num1, num2, sum);
return 0;
}
Output: User enters the numbers 25 and 35 and program prints sum of these two numbers 60 as an output.
Example 2: Program to add two integers using function
In this program, we are finding the sum of two numbers using the user defined function sum()
and we are calling this function from the main function. To read about function, refer this guide: C Functions with example
#include <stdio.h>
/* User defined function sum that has two int
* parameters. The function adds these numbers and
* return the result of addition.
*/
int sum(int a, int b){
return a+b;
}
int main()
{
int num1, num2, num3;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
//Calling the function
num3 = sum(num1, num2);
printf("Sum of the entered numbers: %d", num3);
return 0;
}
Output:
Enter first number: 22 Enter second number: 7 Sum of the entered numbers: 29
Leave a Reply