What is the loop in Programming

Loops play important role in programming. Loops come into usage when there is a requirement to continuously run a block of statements.

Types of Loops

There are two types of loops

  1. Entry Controlled loops

    In this kind of loop, the mentioned condition is checked before entering the loop body. Two loops named For Loop and While Loop are entry-controlled.

  2. Exit Controlled Loops

    In this type of loop, the mentioned condition is checked or reckoned at the end of the loop body. Thus, the loop body will run at least once, regardless of whether the mentioned condition is satisfied or not. One loop do-while loop is exit controlled loop.

 

So, let's start discussing each type of loop one by one.

1-for Loop

For loop follows a repeat command structure. It permits the programmer to write a loop that is run multiple times. The loop allows the programmer to execute n number of actions together in a single line.

Syntax


for (initialization of expression; check expression; update expression)
{
// write body of the loop
// lines you want to run
}

In this loop, a loop variable is utilized to regulate the loop. At first, initialize the loop variable to any value, then test whether this variable is smaller than or greater than the counter value. If the mentioned statement is correct, then the loop body is run and the loop variable gets modified. Steps are replicated until the end condition arrives.

 

2-While Loop

In the for loop, we have noticed that the number of iterations is understood beforehand, i.e. the number of times the loop body is required to be performed is known to us but While loops are utilized in conditions where we are unknown with the actual number of iterations of the loop beforehand. The loop performance is ended according to the test condition.

Syntax

It is already being mentioned that the loops mostly consist of three declarations – initialization expression, check expression, modify an expression. The syntax of all loops – For, while, and do while mostly varies on the sequence of these three statements.

initialization expression;
while (test_expression)
{
// statements

modify_expression;
}

 

3-do-while loop

In do-while loops, the loop is ended based on the mentioned condition. the do-while loop is exit controlled loop.

Note: In the do-while loop the body will run at least once regardless of the mentioned condition.

Syntax


initialization expression;
do
{
// statements

modify_expression;
} while (test_expression);