Complementary task for topic: 2
M Nemeth · 2023-08-29 15:21:04.608221'
Loops: While: Scan and termination II.
Loops: While: Scan and termination II.
Task: Find the largest number entered by the user:
Write a C program that continuously prompts the user to enter a number until they enter a negative number. The program should find and display the largest number 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;
int largest = 0;
printf("Enter a number (-1 to stop): ");
scanf("%d", &number);
while (number >= 0) {
if (number > largest) {
largest = number;
}
printf("Enter a number (-1 to stop): ");
scanf("%d", &number);
}
printf("The largest number entered is %d.\n", largest);
return 0;
}
Explanation
In this example, the program initializes the number variable to store the user input and the largest variable to keep track of the largest number. 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 greater than or equal to 0. Inside the loop, it checks if the current number is larger than the current largest number. If it is, it updates the largest variable. After each iteration, it prompts the user to enter another number using printf() and scanf() to repeat the process. Once the user enters a negative number, the loop terminates, and it uses printf() to display the largest number.