|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/midtermSol/p2.c
/*
2.
Give me code (not a complete program) for a loop that will read integers from user input
and will accumulate a sum of all positive even numbers. Terminate that loop when a
non-integer is read and output the sum.
You must declare all variables used in the loop, initialize variables when necessary.
Hint: You will want to set up your loop so that it will run as long as scanf is still
reading integers. Read the C Lesson on the class website if you're not clear on this.
*/
#include <stdio.h>
int main(){
int sum = 0, n;
printf("Enter some numbers: ");
while(scanf("%d", &n) == 1){
if(n <= 0) continue;
if(n % 2 == 0)
sum = sum + n;
}
printf("sum of evens = %d\n", sum);
return 0;
}
|