Write a C program that takes two integers as input from the user and calculates their sum. The program should then display the result to the user.
Requirements:
- The program should prompt the user to enter two integers.
- It should read the integers from the user input.
- Calculate the sum of the two integers.
- Display the sum to the user.
Example:
Enter the first integer: 5
Enter the second integer: 7
The sum of 5 and 7 is: 12
Solution:
#include <stdio.h>
int main() {
int num1, num2, sum;
// Prompt the user to enter the first integer
printf("Enter the first integer: ");
scanf("%d", &num1);
// Prompt the user to enter the second integer
printf("Enter the second integer: ");
scanf("%d", &num2);
// Calculate the sum
sum = num1 + num2;
// Display the sum
printf("The sum of %d and %d is: %d\n", num1, num2, sum);
return 0;
}
1. #include <stdio.h>: This line includes the standard input-output library, which provides functions like printf() and scanf() for input and output operations.
2. int main() { ... }: This is the main function of the program where execution begins.
3. int num1, num2, sum;: Three integer variables are declared to store the two input numbers (num1 and num2) and their sum (sum).
4. printf("Enter the first integer: ");: This line prints a message prompting the user to enter the first integer.
5. scanf("%d", &num1);: This line reads an integer input from the user and stores it in the variable num1. The %d format specifier is used to read integers, and &num1 is the address of the variable num1.
6. Similarly, the next printf() and scanf() statements are used to prompt the user for the second integer (num2).
7. sum = num1 + num2;: This line calculates the sum of the two input integers and stores it in the variable sum.
8. printf("The sum of %d and %d is: %d\n", num1, num2, sum);: This line prints the sum of the two integers along with their values using the printf() function. %d is used as a placeholder for integers, and the values of num1, num2, and sum are substituted into the string.
9. return 0;: This line indicates that the program has executed successfully and returns 0 to the operating system.
Post a Comment