Loading your workspace…
Loading your workspace…
Keep reading integers from the keyboard until the user enters 999, and add up only the positive ones.
#include <stdio.h>
#define SENTINEL 999
int main(void) {
int number, sum = 0;
printf("Enter numbers (enter %d to stop):\n", SENTINEL);
while (scanf("%d", &number) == 1) {
if (number == SENTINEL) {
break;
}
if (number > 0) {
sum += number;
}
}
printf("Sum of positive numbers: %d\n", sum);
return 0;
}
Input
5 -3 10 0 999Output
Enter numbers (enter 999 to stop):
Sum of positive numbers: 15Input
999Output
Enter numbers (enter 999 to stop):
Sum of positive numbers: 0The sentinel value 999 marks the end of the input, so the loop does not need to know how many numbers will be entered. The check comes before the addition so that 999 is never added.
Negative numbers and zero are excluded by the number > 0 test. The while condition also stops if the input is not an integer, which avoids an endless loop on bad input.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
5 -3 10 0 999
Expected output
Enter numbers (enter 999 to stop): Sum of positive numbers: 15
999
Expected output
Enter numbers (enter 999 to stop): Sum of positive numbers: 0
A special value that signals the end of input, here 999.
If the input is not a number, scanf returns something other than 1 and the loop ends instead of looping forever.
The break happens before the addition, so the sentinel is treated as a stop signal only.
The condition is number > 0, which excludes zero, as the lab asks for positive numbers only.
The program would stop early; a sentinel must be a value that never appears in the data.
Back to all RCU 21BCA1C1P lab programs.