logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jun02/continue.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.
 */


#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"); 
	
	/*
		in this case, scanf will return a '1', if it is reading in an integer, hence why we have 
		the "scanf("%d", &n) == 1" statement. as long as you keep giving the program integers, the 
		loop will keep on going. 

		if scanf gets something other than an integer, scanf will return something
		other than 1, which makes the statement inside the while loop false, resulting in the while
		loop quitting
	*/

	while(scanf("%d", &n) == 1) { 
  		if(n <= 0) continue;
  		 /*
  		 	if your "if" statement is just 1 line long, you don't need curly braces around the statement
  		 	
  		 	here, if the user inputs a negative number then we do the continue statement, where we jump 
  		 	back to the top of the loop (to where we await user input) and not execute the code below. 
		
		 */
  		sum = sum + n; //adding our input to our running total
  		//an else statement is not necessary here, because if the "if" statement is true we will never reach this point

	}

	printf("sum = %d\n", sum); //printing the total sum

	return 0;

}