Computer programming – Loop statement

Computer programming – Loop statement


Loop statement are the set of codes that are used for repeating a block of code. They are very powerful statements in programming. Loops are also called repetitive structures.

A loop is a programming instruction that tells to repeat a code until a specified condition is reached. Loops are better for encountering that situation where the code needs to be repeated to perform the same task. A loop has an entry point, a loop body, and an exit point. Loop makes our code smaller and saves time.

 For example, to print 50 times we have to write it fifty times, to print 100 times we have to write it hundred times, and so on. But using a loop, one change in the condition can change the whole number of displays. Using a loop, we can code efficiently in fewer lines of code instead of adding extra lines of code. Many high-level programming uses loop statements.  

Types of loop in programming

while loop

The while loop is an entry control loop. It repeats a statement while its controlling expression is found to be true.

int i= 1
while i< 6:
  i += 1

do while loop

The do while loop is an exit control loop. The loop body is executed once even though the condition is false because the test expression is at the bottom of the loop.

Int i;
I = 1;
  do {
    } while (i<20);

for loop

The for loop is powerful and flexible loop which provides a more concise loop control structure.

int i = 0
for (i = 0; i<=40; i++) {
   print i;

nested loop

When the body part of the loop is in another loop then the inner loop is said to be nested within the outer loop.

color = ["red", "green", "blue"]
fruits = ["apple", "mango", "grapes"]
for a in color:
  for b in fruits:
    print(a, b)

Loop Interruption

Sometimes, we need to exit from the loop other than testing loop termination condition. There are two statements for the loop termination. They are:

Break statement

A break statement terminates the execution of the loop. When the loop is encountered in a loop, remaining part of the block is skipped and the lop is terminated.

Continue statement

Continue statement does not terminate the loop. It only interrupts a particular interruption. When the continue statement is encountered, the remaining loop statements are skipped and the computation proceeds directly to the next pass of the loop.

Spread the love