-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhileloop-01.c
More file actions
45 lines (34 loc) · 1022 Bytes
/
whileloop-01.c
File metadata and controls
45 lines (34 loc) · 1022 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
* whileloop-01.c
*
* Repeatedly prompts the user for integers, accumulates a running sum,
* and terminates when the user enters 0.
* Includes input validation via scanf return-value checking.
*/
#include <stdio.h>
int main(void) {
int number;
int total = 0;
printf("Enter integers to be summed.\n ");
printf("Enter 0 to stop.\n\n ");
while (1) {
printf("Enter a number: ");
// Check that input is a valid integer
if (scanf("%d", &number) != 1) {
printf("Invalid input. Please enter a number.\n");
// Clear the bad input buffer - avoid infinite loop
while (getchar() != '\n');
continue;
}
// If user enters 0, break the loop
if (number == 0) {
break;
}
// Update the running sum
total += number;
printf("Total so far: %d\n\n", total);
}
// Display the final total when loop ends
printf("Final total: %d\n", total);
return 0;
}