Complementary task for topic: 2
M Nemeth · 2023-08-29 15:21:04.608221'
Loops: While: Scan and termination I.
Loops: While: Scan and termination I.
Task: Calculate the sum of numbers entered by the user:
Write a C program that continuously prompts the user to enter a number until they enter 0. The program should calculate and display the sum of all the numbers entered using a while loop and scanf().
Hint: in the loop condition we can check if the termination happened or not.
Solution
#include
int main() {
int number; //Why can it be undefenied?
int sum = 0;
printf("Enter a number (0 to stop): ");
scanf("%d", &number); //because here it gets a value before usage
while (number != 0) {
sum += number;
printf("Enter a number (0 to stop): ");
scanf("%d", &number);
}
printf("The sum of the numbers entered is %d.\n", sum);
return 0;
}
return factorial;
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
if (number < 0) {
printf("Invalid input. Please enter a positive integer.\n");
return 0;
}
int factorial = computeFactorial(number);
printf("The factorial of %d is %d.\n", number, factorial);
return 0;
}
Explanation
In this example, the program initializes the number variable to store the user input and the sum variable to keep track of the sum. It uses printf() to prompt the user to enter a number and scanf() to scan the input and store it in the number variable. The program then enters a while loop that continues as long as the number entered by the user is not 0. Inside the loop, it adds the current number to the sum using the += operator. After calculating the sum, it again prompts the user to enter another number using printf() and scanf() to repeat the process. Once the user enters 0, the loop terminates, and it uses printf() to display the calculated sum.