Write a C program to input two numbers from user and calculate their sum. C program to add two numbers and display their sum as output. How to add two numbers in C programming.
Example
Input
Input first number: 20 Input second number: 10
Output
Sum = 30
Required knowledge
Fundamentals of C, Data types, Taking user input in CProgram to add two numbers
/**
* C program to find sum of two numbers
*/
#include <stdio.h>
int main()
{
int num1, num2, sum;
/*
* Read two numbers from user
*/
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number:");
scanf("%d", &num2);
/* Adding both number is simple and fundamental */
sum = num1 + num2;
/* Prints the sum of two numbers */
printf("Sum of %d and %d = %d", num1, num2, sum);
return 0;
}
Note We can also write the above program using single scanf() function.
/**
* C program to find sum of two numbers
*/
#include <stdio.h>
int main()
{
int num1, num2, sum;
/*
* Read two numbers from user
*/
printf("Enter any two numbers : ");
scanf("%d%d", &num1, &num2);
sum = num1 + num2;
/* Prints the sum of two numbers */
printf("Sum of %d and %d = %d\n", num1, num2, sum);
return 0;
}
Note: \n is a escape sequence character used to print new line (used to move to the next line).
Before you move on to the next exercise you may also want to check out - C program to find sum of two numbers using pointers.
Output
Enter any two numbers : 12 20 Sum of 12 and 20 = 32
Happy coding ;)
Recommended post
- Basic programming exercises index.
- C program to print Hello World.
- C program to perform all arithmetic operations.
- C program to find perimeter of a rectangle.
- C program to find area of rectangle.
- C program to find diameter, circumference and area of a circle.
- C program to convert meter into kilometer.