// A series of demos on looping in C
// Marc Chee, February 2020
#include <stdio.h>
int main(void) {
// *****************************************************
// This first loop is a basic loop with a counter
// an integer outside the loop
int counter = 0;
while (counter < 5) { // this code has run counter number of times
printf("The first loop has completed %d times.\n", counter);
counter = counter + 1;
}
// When counter hits 10 and the loop's test fails
// the program will exit the loop
// *****************************************************
// This second loop shows the risk of asking the wrong
// question in the loop!
// This program will never end if this loop runs!
//while (1 < 2) {
// printf("Never going to give you up\n");
// printf("Never going to let you down . . .\n");
//}
// *****************************************************
// This loop will end only when a certain condition is
// met. When it detects that the input number is odd
// an integer outside the loop
int runLoop = 1;
// The loop will exit if it reads an odd number
while (runLoop) {
int inputNumber;
printf("Please type in a number: ");
scanf("%d", &inputNumber);
if (inputNumber % 2 == 0) {
printf("Number is even.\n");
} else {
printf("Number is odd.\n");
runLoop = 0;
}
}
// *****************************************************
// A loop within a loop. These should draw a grid of
// stars
// Run the drawing line code 5 times
int lines = 0;
while (lines < 5) { // loop has run lines times
// draw a row of 10 stars
int stars = 0;
while (stars < 10) { // loop has run stars times
printf("*");
stars = stars + 1;
}
printf("\n");
lines = lines + 1;
}
return 0;
}
Resource created Friday 25 September 2020, 02:22:46 PM.
file: loopDemo2.c