Introduction
Adding two numbers is one of the basic operations in programming. This guide will show you how to write a simple C program to add two numbers provided by the user and display the result.
Problem Statement
Create a C program that:
- Prompts the user to enter two numbers.
- Adds the two numbers.
- Displays the sum of the two numbers.
Example:
- Input:
5and3 - Output:
Sum: 8
Solution Steps
- Include the Standard Input-Output Library: Use
#include <stdio.h>to include the standard input-output library, which is necessary for usingprintfandscanffunctions. - Write the Main Function: Define the
mainfunction, which is the entry point of every C program. - Declare Variables: Declare variables to store the two numbers and the sum.
- Input the Numbers: Use
scanfto take input from the user for the two numbers. - Add the Numbers: Calculate the sum of the two numbers.
- Display the Sum: Use
printfto display the sum.
C Program
#include <stdio.h>
/**
* C Program to Add Two Numbers
* Author: https://www.javaguides.net/
*/
int main() {
// Step 1: Declare variables to hold the numbers and the sum
int num1, num2, sum;
// Step 2: Prompt the user to enter the first number
printf("Enter the first number: ");
scanf("%d", &num1);
// Step 3: Prompt the user to enter the second number
printf("Enter the second number: ");
scanf("%d", &num2);
// Step 4: Calculate the sum of the two numbers
sum = num1 + num2;
// Step 5: Display the result
printf("Sum: %d\n", sum);
return 0; // Step 6: Return 0 to indicate successful execution
}
Explanation
Step 1: Declare Variables
- Variables
num1,num2, andsumare declared as integers to hold the two input numbers and their sum, respectively.
Step 2: Input the First Number
- The program prompts the user to enter the first number using
printf. Thescanffunction then reads the input and stores it in the variablenum1.
Step 3: Input the Second Number
- Similarly, the program prompts the user to enter the second number, which is stored in the variable
num2.
Step 4: Calculate the Sum
- The sum of the two numbers is calculated by adding
num1andnum2, and the result is stored in thesumvariable.
Step 5: Display the Sum
- The calculated sum is displayed to the user using the
printffunction.
Step 6: Return 0
- The
return 0;statement indicates that the program executed successfully.
Output Example
Example:
Enter the first number: 5
Enter the second number: 3
Sum: 8
Conclusion
This C program demonstrates how to add two numbers provided by the user and display the result. It covers basic concepts such as taking user input, performing arithmetic operations, and outputting results, making it a useful example for beginners learning C programming.