Lesson 06: Loops
Loops in C/C++ come into use when we need to repeatedly execute a block of statements.
There are mainly two types of loops:
- Entry Controlled loops: In this type of loops, the test condition is tested before entering the loop body. For Loop and While Loop are entry controlled loops.
- Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. do-while loop is exit controlled loop.
Figure 1: Loops
6.1 for Loop
A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line.
Syntax
for (initialization ; condition ; increment) {
// statement block - body of the loop statements we want to execute
}
If the statement block is only one statement, the braces ({}) are not necessary.
Although the for allows a number of variables, generally the initialization sets a loop control variable to its starting value. The condition is usually a relational statement that checks the loop control variable against a termination value, and increment increments (or decrements) it. If the condition is false to begin with, the body of the for loop will not execute even once.
How does a for loop execute?
- Control falls into the for loop. initialization is done.
- The flow jumps to condition.
- Condition is tested.
- If the condition yields true, the flow goes into the body of the loop.
- If the condition yields false, the flow goes outside the loop (goto step 7).
- The statements inside the body of the loop get executed.
- The flow goes to the increment.
- Updation takes place and the flow goes to Step 3 again.
- The for loop has ended and the flow has gone outside.
Flowchart diagram for loop :
Figure 1.1: The Flowchart of For Loop
Print a String 5 Times using for Loop
This program will try to print "Hello World" 5 times. The program will execute in the following manner:
// C program to illustrate for loop #include <stdio.h> int main() { int i = 0; // Writing a for loop // to print Hello World 5 times for (i = 1; i <= 5; i++) { printf("Hello World\n"); } return 0; }
Output
Hello World
Hello World
Hello World
Hello World
Hello World
- Program starts. A variable i is created with initial value zero.
- i is initialized with value 1.
- Condition is checked. 1 <= 5 yields true.
- "Hello World" gets printed the 1st time.
- Updation is done. Now i = 2.
- Condition is checked. 2 <= 5 yields true.
- "Hello World" gets printed the 2nd time.
- Updation is done. Now i = 3.
- Condition is checked. 3 <= 5 yields true.
- "Hello World" gets printed the 3rd time
- Updation is done. Now i = 4.
- Condition is checked. 4 <= 5 yields true.
- "Hello World" gets printed the 4th time
- Updation is done. Now i = 5.
- Condition is checked. 5 <= 5 yields true.
- "Hello World" gets printed for the 5th time
- Updation is done. Now i = 6.
- Condition is checked. 6 <= 5 yields false.
- The flow goes outside the loop to return 0
Multiple Initialization Inside for Loop
We can have multiple initialization in the for loop as shown below:
int i;
char ch;
for (i = 0, ch = 'a'; i < 25; i++) {
printf("%c ", ch + i);
}
What is the difference between the above for loop and a simple for loop?
- It is initializing two variables that are separated by comma (,).
6.2 while loop
While loops are used in situations where we do not know the exact number of iterations of loop beforehand. The loop execution is terminated on the basis of test condition.
The while loop has the general form:
Syntax
while ( condition ) {
// statement block - the body of the loop statements we want to execute
}
If a single statement is the object of the while, then the braces ({}) may be omitted. The while loop iterates as long as condition is true.
The while tests the condition at the top of the loop. Therefore, if the condition is false to begin with, the loop will not execute even once. The condition may be any expression.

- Control falls into the while loop.
- The flow jumps to condition.
- Condition is tested.
- If the condition yields true, the flow goes into the Body of the loop.
- If the condition yields false, the flow goes outside the loop (to step 7)
- The statements inside the body of the loop get executed.
- Updation for the control variable.
- Control flows back to Step 2.
- The while loop has ended and the flow has gone outside.

Figure 2.1: The Flowchart of a while Loop
Print a String 5 Times using while Loop
This program will try to print "Hello World" 5 times. The program will execute in the following manner:
// C program to illustrate while loop #include <stdio.h> int main() { // initialization expression int i = 1; // test expression while (i < 6) { printf("Hello World\n"); // update expression i++; } return 0; }
Output
Hello World
Hello World
Hello World
Hello World
Hello World
- Program starts.
- i is initialized with value 1.
- Condition is checked. 1 < 6 yields true.
- "Hello World" gets printed 1st time.
- Updation is done. Now i = 2.
- Condition is checked. 2 < 6 yields true.
- "Hello World" gets printed 2nd time.
- Updation is done. Now i = 3.
- Condition is checked. 3 < 6 yields true.
- "Hello World" gets printed 3rd time
- Updation is done. Now i = 4.
- Condition is checked. 4 < 6 yields true.
- "Hello World" gets printed 4th time
- Updation is done. Now i = 5.
- Condition is checked. 5 < 6 yields true.
- "Hello World" gets printed 5th time
- Updation is done. Now i = 6.
- Condition is checked. 6 < 6 yields false.
- Flow goes outside the loop to return 0.
6.3 do-while loop
do-while loop is similar to while loop with the only difference that it checks for the condition after executing the statements, and therefore is an example of Exit Control Loop.
Syntax
do {
// statement block - the body of the loop statements we want to execute
} while ( condition );
The do-while loop is the only loop in C/C++ that will always have at least one iteration because the condition is tested at the bottom of the loop.

- Control falls into the do-while loop.
- The statements inside the body of the loop get executed.
- You may need to update the control variable
- The flow jumps to condition.
- The condition is tested:
- If the condition yields true, go to Step 6.
- If the condition yields false, the flow goes outside the loop. (go to Step 7)
- Flow goes back to Step 2.
- The do-while loop has ended and the flow has gone outside.

Figure 3.1: The Flowchart of a do-while Loop
Print a String using do-while Loop
This program will try to print "Hello World". The program will execute in the following manner:
// C program to illustrate do-while loop #include <stdio.h> int main() { // initialization expression int i = 2; do { // loop body printf("Hello World\n"); // update expression i++; // test expression } while (i < 1); return 0; }
Output
Hello World
- Program starts.
- i is initialized to 2.
- Execution enters the loop.
- "Hello World" gets printed 1st time.
- Updation is done. Now i = 2.
- Condition is checked. 2 < 2 yields false.
- Flow goes outside the loop to return 0.
6.4 Infinite Loop
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition always evaluates to true.
Most of the time we create infinite loops by mistake. However, this doesn't mean that the infinite loops are not useful. Infinite loops are commonly used in programs that keep running for long periods of time until they are stopped like the webserver.
Intentional Infinite Loops
Intentional Infinite Loops
In the following situations, the infinite loop must be used in the code:
- Programming in Embedded Systems
- The task functions in multitasking or multithreading system
Infinite Loops by Mistake
Infinite Loops by Mistake
The reason behind the occurrence of Infinite loop
Generally, there are six reasons that become the reason behind the occurrence of an infinite loop.
- No terminating condition.
- Having one condition that can never be met.
- Having a condition that causes the loop to start again and again.
- Miss the incrementer or decrementer (if your logic needs one)
- Continue statement in the wrong place (if your logic needs one)
- Wrong comparisons in loop condition (less than or greater mixed up)
So whenever you get an infinite loop just check from these six conditions, there are high chances that you'll get your mistake.
The harm that Infinite Loop can do
Mainly Infinite loop can harm your system in two ways:
- By using your processor time and power — As a general rule if your processor is working on any process it takes time and power to do it. Same as any other process Once started infinite loop will use your processor time and power. And at one point in time, it slows down your system and made it unresponsive.
- By using your memory — In computer mainly all running processes reside inside the RAM. And when an infinite loop occurs, it just started to fill up your RAM space and at one point of time your system will run out of memory and it can result in complete system failure.
In the following examples, we demonstrate what kind of mistakes can lead to an infinite loop:
Impossible termination condition
An example for loop in C:
unsigned int i;
for (i = 1; i != 0; i++) {
// loop code
}
It appears that this will go on indefinitely, but in fact the value of i will eventually reach the maximum value storable in an unsigned int and adding 1 to that number will wrap-around to 0, breaking the loop. The actual limit of i depends on the details of the system and compiler used. With arbitrary-precision arithmetic, this loop would continue until the computer's memory could no longer hold i. If i was a signed integer, rather than an unsigned integer, overflow would be undefined. In this case, the compiler could optimize the code into an infinite loop.
Mathematical errors
Here is one example of an infinite loop in C:
int x;
while (x < 5) {
x = 1;
x = x + 1;
}
This creates a situation where x will never be greater than 5, since at the start of the loop code x is given the value of 1, thus, the loop will always end in 2 and the loop will never break. This could be fixed by moving the x = 1 instruction outside the loop. Essentially what this infinite loop does is to instruct a computer to keep on adding 1 to 1 until 5 is reached. Since 1 + 1 always equals 2, this will never happen.
Assignment Operator in Condition Expression
Another common mistake that leads to an infinite loop is to use the assignment operator (=) where the equality operator is needed (==). For example, here is a snippet in C:
#include <stdio.h>
int main(void)
{
int a = 0;
while (a < 10) {
printf("%d\n", a);
if (a = 5)
printf("a equals 5!\n");
a++;
}
return 0;
}
The expected output is the numbers 0 through 9, with an interjected "a equals 5" between 5 and 6. However, in the line "if (a = 5)" above, the programmer has confused the = (assignment) operator with the == (equality test) operator. Instead, this will assign the value of 5 to a at this point in the program. Thus, a will never be able to advance to 10, and this loop cannot terminate.
Variable handling errors
Unexpected behavior in evaluating the terminating condition can also cause this problem. Here is an example (in C):
float x = 0.1;
while (x != 1.1) {
printf("x = %f\n", x);
x += 0.1;
}
On some systems, this loop will execute ten times as expected, but on other systems, it will never terminate. The problem is that the loop terminating condition (x != 1.1) tests for exact equality of two floating-point values, and the way floating-point values are represented in many computers will make this test fail because they cannot represent the value 0.1 exactly, thus introducing rounding errors on each increment (the x += 0.1 statement).
Forget to Update Control Variable
int i = 1;
while(i < 10) {
printf("%d\n", i);
}
Here we are not updating the value of i. So after each iteration, the value of i remains the same. As a result, the condition (i < 10) will always be true. For the loop to work correctly add i++;, just after the printf() statement.
Always remember, it is easy to forget update expression in while and do-while loop, than in the for loop.
Condition Never Be Ture
short int i;
for (i = 32765; i < 32768; i++) {
printf("%d\n", i);
}
This loop is an infinite loop. Here is why? According to the condition, the loop will execute until (i < 32768). Initially, the value of i is 32765 and after each iteration, its value is incremented by the update expression (i++). But the value of short int type ranges from -32768 to 32767. If you try to increment the value of i beyond 32767, it goes on the negative side and this process keeps repeating indefinitely. Hence the condition (i < 32768) will always be true.
Float-Pointer Number
float f = 2;
while(f != 31.0)
{
printf("%f\n", f);
f += 0.1;
}
This loop is infinite because computers represent floating-point numbers as approximate numbers, so 3.0 may be stored as 2.999999 or 3.00001. So the condition (f != 31.0) never becomes false. To fix this problem write the condition as (f <= 31.0).
Semicolon at Wrong Place
int i = 0;
while(i <= 5);
printf("%d\n", i);
This loop will produce no output and will go on executing indefinitely. Take a closer look and notice the semicolon (;) at the end of while condition. We know semicolon (;) after the condition is a null statement. So the loop is equivalent to the following:
int i = 0;
while(i <= 5) {
; // a null statement
}
printf("%d\n", i);
We can now clearly see that we are not updating the value if i inside the while loop. As a result, it will go on executing indefinitely.
Alderson loop
Alderson loop is a rare slang or jargon term for an infinite loop where there is an exit condition available, but inaccessible in the current implementation of the code, typically due to a programmer's error. These are most common and visible while debugging user interface code.
The following C code example of an Alderson loop, where the program is supposed to sum numbers given by the user until zero is given, but where the programmer has used the wrong operator:
sum = 0;
while (true) {
printf("Input a number to add to the sum or 0 to quit");
i = getUserInput();
if (i * 0) { // if i times 0 is true, add i to the sum.
// Note: ZERO means FALSE, Non-Zero means TRUE. "i * 0" is ZERO (FALSE)!
sum += i; // sum never changes because (i * 0) is 0 for any i;
// it would change if we had != in the condition instead of *
}
if (sum > 100) {
break; // terminate the loop; exit condition exists but is never reached because sum is never added to
}
}
Difference between for and while loop in C/C++
for Loop | while Loop |
---|---|
Initialization may be either in the loop statement or outside the loop. | Initialization is always outside the loop. |
Once the statement(s) is executed then after increment is done. | The increment can be done before or after the execution of the statement(s). |
It is normally used when the number of iterations is known. | It is normally used when the number of iterations is unknown |
Condition is a relational expression. | The condition may be an expression or non-zero value. |
It is used when initialization and increment are simple. | It is used for complex initialization. |
The for is entry controlled loop. | The while is also entry controlled loop. |
for ( init ; condition ; increment ) { statement(s); } |
while ( condition ) { statement(s); } |
Difference between for and do-while loop in C/C++
for Loop | do-while Loop |
---|---|
Statement(s) is executed once the condition is checked. | Condition is checked after the statement(s) is executed. |
It might be that statement(s) gets executed zero times. | Statement(s) is executed at least once. |
For the single statement, the bracket is not compulsory. | Brackets are always compulsory. |
Initialization may be outside or in the condition box. | Initialization may be outside or within the loop. |
for loop is entry controlled loop. | do-while is exit controlled loop. |
for ( init ; condition ; increment) { statement(s); } |
do { statement(s); } while ( condition ); |
Difference between while and do-while loop in C/C++
while Loop | do-while Loop |
---|---|
Condition is checked first then statement(s) is executed. | Statement(s) is executed at least once, thereafter condition is checked. |
It might occur statement(s) is executed zero times if the condition is false. | At least once the statement(s) is executed. |
No semicolon at the end of the while. while (condition) |
A semicolon at the end of the while. do { } while(condition); |
If there is a single statement, brackets are not required. | Brackets are always required. |
The variable in the condition is initialized before the execution of the loop. | Variable may be initialized before or within the loop. |
while loop is entry controlled loop. | The do-while loop is exit controlled loop. |
while (condition) { statement(s); } |
do { statement(s); } while (condition); |
Summary
- Use for loop when the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known.
- Use while loops where the exact number of iterations is not known, but the loop termination condition is known.
- Use do-while loop if the code needs to be executed at least once like in Menu-driven programs
Questions
- Binary and Hexadecimal: Input an unsigned 8-bit integer (uint8_t) and display its binary and hexadecimal value on the screen. (Using shifter and bitmask to get all digits from left to right).
- Use for loops to construct a program that displays the following pattern on the screen:
-
X
XX
XXX
XXXX
XXXXX
-
X
XX
XXX
XXXX
XXXXX
-
X
XXX
XXXXX
XXXXXXX
XXXXXXXXX
-
XXXXXXXXX
XXXXXXX
XXXXX
XXX
X
-
X
XXX
XXXXX
XXXXXXX
XXXXXXXXX
XXXXXXX
XXXXX
XXX
X
-
X
XX
XXX
XXXX
XXXXX
XXXX
XXX
XX
X
-