It is very useful for us to have the ability to tell the computer to run code for a specific number of times or until a condition is violated.
For loops
This is called a bounded loop. This is because we can predict the number of times the loop will run. There is a sentinel value, usually $i$ or $n$ that is iterated and checked at the beginning of each iteration. If the condition is not fulfilled then the loop no longer runs.
David wants to list the all of the perfect squares for the numbers 1 to 10. He wrote the following code:
#include <stdio.h>
int main(void){
for (int i=0;i<=10;i++){
printf("The square of %d is %d\n",i,i*i);
}
return 0;
}
What is the output of the program?
While loops
This type of loop, alongside the do-while loop, are unbounded loops. This means that we cannot say beforehand how many times they will run. For the while loop, the condition is checked at the beginning of each iteration. This means that if the condition is not fulfilled in the beginning of the loop then the code in the loop will not be executed in the first place.
David wants a C program that accepts a positive integer and incrementally reduces it to zero. The following code is what he whips up:
#include <stdio.h>
int main(void){
int number;
printf("Please enter a positive number to be reduced to zero: ");
scanf("%d",&number);
while(number>=0){
printf("%d\n",number);
number--;
}
printf("Done!\n");
return 0;
}
What happens when he enters a positive number? What happens if he enters a negative number? What happens when he enters zero?
Do-while loops
This is similar to the while loop but the condition check is done at the end of each iteration. This means that the do-while loop is guaranteed to run at least once.
Jamie doesn’t want his family to know the secret ingredient for his secret formula so he creates a program to tell his friend Mary the ingredient as long as she enters the correct PIN. The code looks like this:
#include <stdio.h>
int main(void){
int input;
do{
printf("Please enter the correct PIN: ");
scanf("%d",&input);
}while(input!=0000);
printf("The secret ingredient of the secret formula is...nothing...\n");
return 0;
}
What value must Mary enter in order to find out that Jamie was just being a menace to society all along?