Complementary task for topic: 1
M Nemeth · 2023-08-29 15:21:04.603220'
scanf: integer II.
scanf: integer II.
Task: Calculate the sum of two integers:
Write a C program that prompts the user to enter two integers using scanf() and calculates their sum. Display the sum using printf()!
Hint: scanf() works like printf(), but you need a & sign before the variable.
Later you will understand that is needed because the scanf needs a place to STORE the variable, not the value of the variable, & sign is an operator that gives us the memory address. This address is needed to be passed to scanf() so scanf can SAVE the read value there. (and so the value can change)
Solution
#include
int main() {
int num1, num2;
printf("Enter the first integer: ");
scanf("%d", &num1);
printf("Enter the second integer: ");
scanf("%d", &num2);
int sum = num1 + num2;
printf("The sum of %d and %d is %d.\n", num1, num2, sum);
return 0;
}
Explanation
In this example, the program uses printf() to prompt the user to enter the first and second integers. The scanf() function is used to scan the input from the user and store it in the num1 and num2 variables. The program calculates the sum of the two integers and stores it in the sum variable. Then, it uses printf() to display the sum in the specified format.