
Write a program in C Language to print the sum of two numbers.
Here's a C program that calculates and prints the sum of two numbers:
Code:
#include
<stdio.h>
int
main() {
int num1, num2, sum;
printf("Enter the first number:
");
scanf("%d", &num1);
printf("Enter the second number:
");
scanf("%d", &num2);
sum = num1 + num2;
printf("The sum of %d and %d is
%d\n", num1, num2, sum);
return 0;
}
Explanation:
- The `#include <stdio.h>` line includes the standard input/output library, which provides the `printf()` and `scanf()` functions.
- The `int main()` function is the starting point of the program, where the execution begins.
- Three variables are declared: `num1`, `num2`, and `sum`. These variables hold the two input numbers and the sum, respectively.
- The `printf("Enter the first number: ");` statement is used to prompt the user to enter the first number.
- The `scanf("%d", &num1);` statement reads an integer input from the user and stores it in the `num1` variable.
- Similarly, the program prompts the user to enter the second number and reads it into the `num2` variable.
- The `sum` variable is assigned the sum of `num1` and `num2`.
- Finally, the program prints the sum using the `printf()` function, displaying a message with the input numbers and their sum.
- The `return 0;` statement indicates the successful termination of the `main()` function.
To run this program:
- 1. Save the program with a .c extension (e.g., sum.c).
- 2. Open a command prompt or terminal and navigate to the directory where the program is saved.
- 3. Compile the program using a C compiler (e.g., gcc).
- 4. Run the compiled program.
You will see the program asking for two numbers. After you input the numbers, it will display the sum. For example:
Enter the first number: 10
Enter the second number: 20
The sum of 10 and 20 is 30
Congratulations! You have successfully written a program in C to print the sum of two numbers.
To learn one-to-one C Programming, visit the Academy of Web Technologies and Information Management (AWTIM) or call 08961235337 for details.