Loop or iteration or repetition is a programming construct that allows a set of instructions to be executed multiple times until a specific condition is met.
Loops are used to perform repetitive tasks without having to write the same code multiple times. They are fundamental in programming and are used in various applications, such as processing data, automating tasks, and creating interactive programs.
There are three main types of loops in C and other programming languages:
A for loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The syntax of a for loop in C is as follows:
for (initialization; condition; update) {
// code to be executed
}
In a for loop, the initialization step is executed only once at the beginning of the loop. The condition is evaluated before each iteration, and if it evaluates to true, the code block inside the loop is executed. After each iteration, the update step is executed, which typically modifies the control variable.
The update is done either by increasing (++) or decreasing (--) the control variable.
For instance if the control variable is i, the increment will be i++ and the decrement will be i--.
In most programming languages like C, you must declare and initialize the control variable before the loop.
For instance if we want to start the loop from 1 to 10, we can initialize the control variable as int i = 1;.
When ascending (from least to highest), the control variable is incremented.
When descending (from highest to least), the control variable is decremented.
You have to use appropriate comparator operators (e.g., <, >, <=, >=) in the condition to make the condition true from start and end at a point.
For instance, if we want the loop to iterate from 1 to 10, we can use any of the following conditions if we have initialized a control variable i to 1:
i < 11i <= 10The first condition reads as i is less than 11. The loop will continue as long as i is less than 11.
i increases after each iteration.
Note: most programmers use i as the control variable because of the word iteration but you can use any variable name of your choice.
| Iteration Number | Calculation | Value of i | Loop Status |
| 1 | i = 1 | 1 | True, loop continues (since 1 < 11) |
| 2 | i = 1 + 1 | 2 | True, loop continues (since 2 < 11) |
| 3 | i = 2 + 1 | 3 | True, loop continues (since 3 < 11) |
| 4 | i = 3 + 1 | 4 | True, loop continues (since 4 < 11) |
| 5 | i = 4 + 1 | 5 | True, loop continues (since 5 < 11) |
| 6 | i = 5 + 1 | 6 | True, loop continues (since 6 < 11) |
| 7 | i = 6 + 1 | 7 | True, loop continues (since 7 < 11) |
| 8 | i = 7 + 1 | 8 | True, loop continues (since 8 < 11) |
| 9 | i = 8 + 1 | 9 | True, loop continues (since 9 < 11) |
| 10 | i = 9 + 1 | 10 | True, loop continues (since 10 < 11) |
| 11 | i = 10 + 1 | 11 | False, loop terminates (since 11 is not less than 11) |
The second condition reads as i is less than or equal to 10. The loop will continue as long as i is less than or equal to 10.
i increases after each iteration.
| Iteration Number | Calculation | Value of i | Loop Status |
| 1 | i = 1 | 1 | True, loop continues (since 1 < 10) |
| 2 | i = 1 + 1 | 2 | True, loop continues (since 2 < 10) |
| 3 | i = 2 + 1 | 3 | True, loop continues (since 3 < 10) |
| 4 | i = 3 + 1 | 4 | True, loop continues (since 4 < 10) |
| 5 | i = 4 + 1 | 5 | True, loop continues (since 5 < 10) |
| 6 | i = 5 + 1 | 6 | True, loop continues (since 6 < 10) |
| 7 | i = 6 + 1 | 7 | True, loop continues (since 7 < 10) |
| 8 | i = 7 + 1 | 8 | True, loop continues (since 8 < 10) |
| 9 | i = 8 + 1 | 9 | True, loop continues (since 9 < 10) |
| 10 | i = 9 + 1 | 10 | True, loop continues (since 10 <= 10) |
| 11 | i = 10 + 1 | 11 | False, loop terminates (since 11 is not less than or equal to 10) |
For example, the following for loop prints the numbers from 1 to 10 as explained:
for (int i = 1; i <= 10; i++) {
printf("%d ", i);
}
Since there is no newline character in the printf statement, all the numbers will be printed on the same line.
If we wish each number to be printed on a new line, we can add a newline character (\n) to the printf statement:
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
To loop in a descending order, we can display the numbers from 10 to 1:
If we initialize our control variable i to 10 and the loop is supposed to continue while i is greater than 0, our condition will be i > 0:
i = 10
| Iteration Number | Calculation | Value of i | Loop Status |
| 1 | i = 10 | 10 | True, loop continues (since 10 > 0) |
| 2 | i = 10 - 1 | 9 | True, loop continues (since 9 > 0) |
| 3 | i = 9 - 1 | 8 | True, loop continues (since 8 > 0) |
| 4 | i = 8 - 1 | 7 | True, loop continues (since 7 > 0) |
| 5 | i = 7 - 1 | 6 | True, loop continues (since 6 > 0) |
| 6 | i = 6 - 1 | 5 | True, loop continues (since 5 > 0) |
| 7 | i = 5 - 1 | 4 | True, loop continues (since 4 > 0) |
| 8 | i = 4 - 1 | 3 | True, loop continues (since 3 > 0) |
| 9 | i = 3 - 1 | 2 | True, loop continues (since 2 > 0) |
| 10 | i = 2 - 1 | 1 | True, loop continues (since 1 > 0) |
| 11 | i = 1 - 1 | 0 | False, loop terminates (since 0 is not greater than 0) |
For example, the following for loop prints the numbers from 10 to 1 as explained:
for (int i = 10; i > 0; i--) {
printf("%d ", i);
}
For fun sake, let's print "*" characters 5 times:
Since our task is to display 5 starts (*), we can intialize our control variable to 1 and the loop is supposed to start at 5, hence our condition will either be i <= 5 or i < 6.
Since our task is to display horizontally, we won't use the newline character:
for (int i = 1; i <= 5; i++) {
printf("*");
}
Aternatively,
for (int i = 1; i < 6; i++) {
printf("*");
}
Alternatively,
for (int i = 0; i < 5; i++) {
printf("*");
}
Since our task is to display vertically, we will use the newline character:
for (int i = 1; i <= 5; i++) {
printf("*\n");
}
Aternatively,
for (int i = 1; i < 6; i++) {
printf("*\n");
}
Alternatively,
for (int i = 0; i < 5; i++) {
printf("*\n");
}
A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The syntax of a while loop in C is as follows:
while (condition) {
// code to be executed
// update control variable
}
In a while loop, the condition is evaluated before each iteration. If the condition evaluates to true, the code block inside the loop is executed. The loop continues until the condition becomes false.
For example, the following while loop prints the numbers from 1 to 5:
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
The control variable is i and its value is updated within the loop to ensure the loop terminates when the condition becomes false.
Note: if there is no update to the control variable within the loop, it may result in an infinite loop and the program may hang, freeze or crash.
A do-while loop is a control flow statement that allows code to be executed at least once and then repeatedly based on a given boolean condition. The syntax of a do-while loop in C is as follows:
do {
// code to be executed
// update control variable
} while (condition);
In a do-while loop, the code block inside the loop is executed first, and then the condition is evaluated. If the condition evaluates to true, the loop continues; otherwise, it terminates.
Since the condition is checked after the first iteration, the code block is guaranteed to execute at least once.
For example, the following do-while loop prints the numbers from 1 to 5:
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
It is mostly used to repeatedly ask a user for input until a valid response is received.
Let's modify our previous grading system that we built earlier to use a do while loop to repeated ask the user to enter a score until a user enters a score between 0 to 100.
Our previous code was:
#include <stdio.h>
int main() {
int score;
printf("Enter your score: ");
scanf("%d", &score);
if (score >= 75) {
printf("Your grade is 1.\n");
} else if (score >= 70) {
printf("Your grade is 2.\n");
} else if (score >= 65) {
printf("Your grade is 3.\n");
} else if (score >= 60) {
printf("Your grade is 4.\n");
} else if (score >= 55) {
printf("Your grade is 5.\n");
} else if (score >= 50) {
printf("Your grade is 6.\n");
} else if (score >= 45) {
printf("Your grade is 7.\n");
} else if (score >= 40) {
printf("Your grade is 8.\n");
} else {
printf("Your grade is 9.\n");
}
return 0;
}
We will put the taking of the value from the user in a loop to continually ask the user to enter until a valid response is given.
Caption of the part to modify is below:
do{
printf("Enter your score (0 - 100): ");
scanf("%d", &score);
}while((score < 0)||(score > 100));
The do while first ask the user to enter the score. If a user enters the correct range of score, the condition in the do while loop will be false and the loop ends but if not, the loop will be repeated until user enters the correct input.
Our updated code will be:
#include <stdio.h>
int main() {
int score;
do{
printf("Enter your score (0 - 100): ");
scanf("%d", &score);
}while((score < 0)||(score > 100));
if (score >= 75) {
printf("Your grade is 1.\n");
} else if (score >= 70) {
printf("Your grade is 2.\n");
} else if (score >= 65) {
printf("Your grade is 3.\n");
} else if (score >= 60) {
printf("Your grade is 4.\n");
} else if (score >= 55) {
printf("Your grade is 5.\n");
} else if (score >= 50) {
printf("Your grade is 6.\n");
} else if (score >= 45) {
printf("Your grade is 7.\n");
} else if (score >= 40) {
printf("Your grade is 8.\n");
} else {
printf("Your grade is 9.\n");
}
return 0;
}
We can also use a loop to make our program run multiple times until a user enters a particular number or character to exit the program.
We will modify the grading program above and place it in a while loop. We will ask a user to enter 0 to exit the program and any other number to continue.
We first have to initialize our control variable to a number which is not 0.
#include <stdio.h>
int main() {
int score;
int exit = 1;
while(exit !=0){
do{
printf("Enter your score (0 - 100): ");
scanf("%d", &score);
}while((score < 0)||(score > 100));
if (score >= 75) {
printf("Your grade is 1.\n");
} else if (score >= 70) {
printf("Your grade is 2.\n");
} else if (score >= 65) {
printf("Your grade is 3.\n");
} else if (score >= 60) {
printf("Your grade is 4.\n");
} else if (score >= 55) {
printf("Your grade is 5.\n");
} else if (score >= 50) {
printf("Your grade is 6.\n");
} else if (score >= 45) {
printf("Your grade is 7.\n");
} else if (score >= 40) {
printf("Your grade is 8.\n");
} else {
printf("Your grade is 9.\n");
}
/* Alert user to enter 0 to exit or other number to continue and get the value from the user */
printf("Enter 0 to exit or any other number to continue: ");
scanf("%d",&exit);
}
return 0;
}
Python has two loop types
The syntax for a while loop in Python is:
initialize variable
while condition:
//Do something
// Update variable
i++ in Python but i += 1i-- in Python but instead i -= 1For example, to print 1 to 10, we can write the code below:
i = 1
while i <= 10:
print(i)
i +=1
To print from 10 to 1, we can write the code below:
i = 10
while i >= 1:
print(i)
i -=1
To demonstrated that all indented line of codes after a while loop is exectuted, we can write the code below:
i = 10
while i >= 1:
print(i)
i -=1
print("This is part of loop")
As you can see if you run this, "This is part of loop" is displayed 10 times at each iteration.
We will modify the code by bringing that part of code to the edge.
i = 10
while i >= 1:
print(i)
i -=1
print("This part is out of the loop")
When you run the above code, you will realize that the "This part is out of the loop" is run only once. Which means it is executed after the loop block is executed.
There is no do-while loop in Python. To implement a system where you continually ask a user to enter a value until the response is correct, you must implement it this way:
For instance, I can implement the above concept in the syntax below:
repeat = True
while repeat:
//I get the user's information
//I validate the information. If the input is correct, I set repeat to False to end the loop
Let's modify the Python grading system in our previous lesson to repeated ask user to enter score until the correct input is entered.
repeat = True
while repeat:
score = int(input("Enter your score: "))
if((score >= 0) and (score <= 100)):
repeat = False
if score >= 75:
print("Your grade is 1.")
elif score >= 70:
print("Your grade is 2.")
elif score >= 65:
print("Your grade is 3.")
elif score >= 60:
print("Your grade is 4.")
elif score >= 55:
print("Your grade is 5.")
elif score >= 50:
print("Your grade is 6.")
elif score >= 45:
print("Your grade is 7.")
elif score >= 40:
print("Your grade is 8.")
else:
print("Your grade is 9.")
Notes: in Python,
Now let's put our entire program in a loop so that the program can run multiple times until user enters a value to exit the program. We will use 0 for exit and any other number to continue.
exit = 1
while exit != 0:
repeat = True
while repeat:
score = int(input("Enter your score: "))
if((score >= 0) and (score <= 100)):
repeat = False
if score >= 75:
print("Your grade is 1.")
elif score >= 70:
print("Your grade is 2.")
elif score >= 65:
print("Your grade is 3.")
elif score >= 60:
print("Your grade is 4.")
elif score >= 55:
print("Your grade is 5.")
elif score >= 50:
print("Your grade is 6.")
elif score >= 45:
print("Your grade is 7.")
elif score >= 40:
print("Your grade is 8.")
else:
print("Your grade is 9.")
exit = int(input("Enter 0 to exit or any other number to continue: "))
Python for loop is used for iterating over a sequence (either a list, a tuple, a dictionary, a set or a string).
For instance, we can iterate over the list of fruits and print each fruit using the code below:
fruits = ["mango","apple","pineapple","pawpaw","banana"]
for x in fruits:
print(x)
Note: just like the while loop, you must indent the block of code
Similarly, can also loop through each character in a string.
name = "Godwin"
for i in name:
print(i)