In this article, we will write a C program to find the sum of three numbers.
The program takes three numbers from the user as input and prints their sum on the screen as output.
Sample Input:
Enter three numbers: 10 20 30
Output:
Sum of the three numbers is: 60
The following program shows how you can calculate the sum of three numbers in C programming:
// C program to add three numbers #include <stdio.h> int main() { int num1, num2, num3, res; printf("Enter three numbers: "); scanf("%d %d %d", & num1, & num2, & num3); // Calculate the sum res = num1 + num2 + num3; // Print the result printf("Sum of the three numbers is: %d", res); return 0; }
Output:
Enter three numbers: 10 20 30 Sum of the three numbers is: 60
Code Explanation:
- The program takes three numbers from the user and stores them in
num1
,num2
andnum3
variables respectively. - To store the sum of the three variables we have declared a variable
res
. - The sum of the three numbers is calculated using the addition operator(
+
) and stored in theres
variable. - Finally, the sum of the three numbers is printed on the screen using the printf() function.
Example 2: Find the Sum of Three Numbers using a Function
You can also define a function which takes three numbers as its arguments and returns their sum as a result.
See the implementation in the following program:
// C program to add three numbers using function #include <stdio.h> //Function declaration int add(int, int, int); int main() { int num1, num2, num3, res; printf("Enter three numbers: "); scanf("%d %d %d", & num1, & num2, & num3); // Call the add() function res = add(num1, num2, num3); // Print the result printf("Sum of the three numbers is: %d", res); return 0; } // User defined function for addition int add(int a, int b, int c) { int result; result = a + b + c; return result; }
Output:
Enter three numbers: 10 20 30 Sum of the three numbers is: 60
Code Explanation:
- The program takes three numbers from the user and stores them in
num1
,num2
andnum3
variables. - To get the sum of the three numbers, we have defined a function
add()
. Theadd()
function takes three numbers as its arguments, calculates their sum and returns it. - The sum returned by the
add()
method is stored in theres
variable. - Finally, the result is printed on the screen using the printf() function.
Thanks for reading.