|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/jun02/break.c
/**
* This program will read integers from standard input and accumulate a sum of all
* positive non-negative values. The `sum = sum + n` statement will be skipped
* when n is <= 0 because the continue will move execution back to the
* test-expression of the while loop immediately.
*/
//this is the same program as continue.c but we are also making use of a break statement.
#include <stdio.h>
int main()
{
int sum = 0, n;
printf("-- Enter some numbers (one number per line) -- \n");
printf("-- When finished, type any non-number and hit enter to get the sum of all the numbers--\n");
/*
below, we have a while(1), which denotes an infinite loop
if you are writing a while(1), you need something inside the loop that can cause it to break
otherwise it will never stop.
here, if scanf returns something other than 1 (in this case, reads something other than an
integer), the while loop will break.
*/
while(1) { //an infinite loop that will only terminate if scanf returns 0.
if(scanf("%d", &n) != 1) break;
// Note how the test condition is reversed (!= vs ==) since we only want to exit the loop
// when the scanf fails to read one integer.
if(n <= 0) continue;
sum = sum + n;
}
printf("sum = %d\n", sum);
return 0;
}
|