C Program to calculate sum of two numbers
Write a program in C to enter two numbers from user and calculate their sum. C program to add two numbers and display their sum as output.
Example:
Enter first number: 10
Enter second number: 10
Output: Sum = 20
Required knowledge:
Fundamentals of C Data types, Taking user input in C
Fundamentals of C Data types, Taking user input in C
Program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| /** * C program to calculate sum of two numbers */ #include <stdio.h>
void
main() { int num1, num2, sum; /* * Read two numbers from user */ printf ( "Enter first number: \n" ); scanf ( "%d" , &num1); printf ( "Enter second number: \n" ); scanf ( "%d" , &num2); /* Adding both number*/ sum = num1 + num2; /* Prints the sum of two numbers */ printf ( "Sum of %d and %d = %d" ,num1, num2, sum); } |
Note: The above program can also written using single scanf() function as below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| /** * C program to find sum of two numbers */ #include <stdio.h>
void
main() { int num1, num2, sum; /* * Read two numbers from user */ printf ( "Enter any two numbers : \n" ); scanf ( "%d%d" , &num1, &num2); sum = num1 + num2; /* Prints the sum of two numbers */ printf ( "Sum of %d and %d = %d" ,num1, num2, sum); } |
Note: \n is a escape sequence character used to print new line or next line.
Output
Enter any two numbers :
20
20
Sum of 20 and 20 = 40
20
20
Sum of 20 and 20 = 40
Enjoy it......
Comments
Post a Comment
Dears! Yours Comment approved in 24 hours also your answer in 24 hours.......