Loops in programming come into use when we need to repeatedly execute a block of statements. For example: Suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below:
An iterative method to do this is to write the printf() statement 10 times.
// C program to illustrate need of loops #include <stdio.h> int main() { printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); return 0; }
And the output of the code in C would be like below.
Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World
Unlike copying and pasting what we want to iterate in the code, we could use loops to do iterations for us.
Loops are used commonly in all programming languages. In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below.
In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.
- An operation is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.
- Counter not Reached: If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeat it.
- Counter reached: If the condition has been reached, the next instruction “falls through” to the next sequential instruction or branches outside the loop.
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 loop body. Therefore, the loop body will execute atleast once, irrespective of whether the test condition is true or false. do – while loop is exit controlled loop.
while Loops ( Condition-Controlled Loops )
Both while loops and do-while loops ( see below ) are condition-controlled, meaning that they continue to loop until some condition is met. Both while and do-while loops alternate between performing actions and testing for the stopping condition. While loops check for the stopping condition first, and may not execute the body of the loop at all if the condition is initially false. Let’s do the same example.
// C program to illustrate while loop #include <stdio.h> int main() { // initialization expression int i = 1; // test expression while (i < 10) { printf( "Hello World\n"); // update expression i++; } return 0; }
The output of the code will be the same output like we did in first time. Printing Hello World statement ten times can be easily done as I have shown using while.
Is it the only way? Of course no.
do-while Loops
do-while loops are exactly like while loops, except that the test is performed at the end of the loop rather than the beginning. This guarantees that the loop will be performed at least once, which is useful for checking user input among other things.
In do while loops also the loop execution is terminated on the basis of test condition. The main difference between do while loop and while loop is in do while loop the condition is tested at the end of loop body, i.e do while loop is exit controlled whereas the other two loops are entry controlled loops.
// C program to illustrate do-while loop #include <stdio.h> int main() { int i = 1; // Initialization expression do { // loop body printf( "Hello World\n"); // update expression i++; } while (i < 10); // test expression return 0; }
In the above program the test condition (i<10) evaluates to false. But still as the loop is exit – controlled the loop body will execute ten times.
The following diagram shows the difference between while and do-while loops. Note that once you enter the loop, the operation is identical from that point forward:
As we have discussed do-while and while loops, the basic schematic is shown above. The basic idea for while and do-while is to ask the code if it is true. Then, the code will be executed. However, if it becomes false, then the loop will be done and it exits. However, there is the only difference between each other is to place of the usage of the body (the code willing to be done when the condition is valid(true)). Bear in mind, while is more used one instead of do-while because it has faster processing time(10-100 microseconds approximately) and sounds more logical for those coders. Feel free to try.
for Loops
Let’s move to one of the favorite one. For loops. For loops are counter-controlled, meaning that they are normally used whenever the number of iterations is known in advance. A for loop is a repetition control structure which 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.
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.
- Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: int i=1;
- Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: i <= 10;
- Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: i++;
Let’s do the same example using for loop.
// C program to illustrate for loop #include <stdio.h> int main() { int i=0; for (i = 1; i <= 10; i++) { printf( "Hello World\n"); } return 0; }
The output of the executed code will be same like before but the difference is that we used for loop.
Basically, we need to state the condition of the iteration which will be done for the for loop at the beginning, then we execute the main statements until the loop is valid.
Depending on programming language and IDE, the execution time may vary. I personally use while or for loop in common which have become my habit of coding. However, you are always encouraged to use your own favorite.
What about an 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. Usually, this is an error.
Just a friendly warning, you may need to shut down your computer after running the code below.
// C program to demonstrate infinite loops // using for and while // Uncomment the sections to see the output #include <stdio.h> int main () { int i; // This is an infinite for loop as the condition // expression is blank for ( ; ; ) { printf("This loop will run forever.\n"); } // This is an infinite for loop as the condition // given in while loop will keep repeating infinitely /* while (i != 0) { i-- ; printf( "This loop will run forever.\n"); } */ // This is an infinite for loop as the condition // given in while loop is "true" /* while (true) { printf( "This loop will run forever.\n"); } */ }
The comma operator
- C has a comma operator, that basically combines two statements so that they can be considered as a single statement.
- About the only place, this is ever used is in for loops, to either provide multiple initializations or to allow for multiple incrementations.
- For example:
int i, j = 10, sum; for( i = 0, sum = 0; i < 5; i++, j-- ) sum += i * j;
Break and Continue
Break and continue are two C/C++ statements that allow us to further control flow within and out of loops.
Break causes execution to immediately jump out of the current loop, and proceed with the code following the loop.
Continue causes the remainder of the current iteration of the loop to be skipped, and for execution to recommence with the next iteration.
In the case of for loops, the incrementation step will be executed next, followed by the condition test to start the next loop iteration.
In the case of while and do-while loops, execution jumps to the next loop condition test.
( We have also seen break used to jump out of switch statements. Continue has no meaning in switch statements. )
When to Use Which Loop ?
- If you know ( or can calculate ) how many iterations you need, then use a counter-controlled ( for ) loop.
- Otherwise, if it is important that the loop complete at least once before checking for the stopping condition,
or if it is not possible or meaningful to check the stopping condition before the loop has executed at least once,
then use a do-while loop. - Otherwise use a while loop.
Important Points:
- 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 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