// Demonstrating the use of a while loop with a sentinel // condition. // Sasha Vassar Week 2, Lecture 4 /* Using a while loop allows us to repeat certain pieces of code. //1. Initialise loop control variable while (condition) { //2. Test the condition against the loop control variable //3. Update loop control variable (last statement of while loop } */ #include // Problem: I want to read in some scores until a negative number has been // entered, and I want to only add the even scores up. int main (void) { int score; int sum = 0; //1. Read in some scores //2. Stop reading when a negative number has been read) //3. Add the even scores up // - Check if the entered score is an even number, if it is add it to the sum //1. Set my loop control variable int endloop_flag = 0; while (endloop_flag == 0) { //2. Check the condition with that variable printf("Please enter a score to add to the sum: "); scanf("%d", &score); //Is this number that I have read in positive or negative? if (score >= 0) { //Is this score an even number? IF if (score % 2 == 0) { sum = sum + score; printf("The sum is now %d\n", sum); } } else { endloop_flag = 1; } } printf("The final sum of scores is %d\n", sum); return 0; }