C program to add two integer numbers

In this example we will add two numbers stored in two individual variables. We will see this example in two different versions. In the first one, we will store the numbers in the variables by ourselves and in the second version we will ask a user to enter two numbers and then perform the addition.

Note:- To understand this example, you must have the knowledge of arithmetic operators in C, printf function, scanf function, return type of functions and format specifiers in C.

Example By assigning the value to the variables by ourselves

``````#include<stdio.h>
int main()
{
int num1 = 7;
num2 = 4;
int result;
result = num1 + num2;
printf("The sum is %d", result);
return 0;
}``````

Output:-

`The sum is 11 `

Explanation:-

• The first line is written to include the standard input output library ‘stdio’ in our program. This is required so as we could use the printf and scanf functions. These two functions are defined in the ‘stdio’ library.
• Inside the main function, we have declared two integer type variables num1 and num2 and initialized them with 7 and 4 respectively. We are going to perform addition on these two. We have also declared a third variable named result which will store the required addition.
• In line number seven, we have added the values stored in the two variables by the arithmetic operator ‘+’ and stored the result in the variable named result.
• Lastly we’ve print the result on the output screen.

Example By taking user input

``````#include<stdio.h>
int main()
{
int num1, num2, result;
printf("Enter first number");
scanf("%d", &num1);
printf("Enter second number");
scanf("%d", &num2);
result = num1 + num2;
printf("The sum is %d", result);
return 0;
}``````

Output:-

`Enter first number4`

`Enter first number5`

`The sum is 9 `

This example is the same as the example given above. The only difference in the later is that we have taken the numbers from the user using the scanf function.