Loops in Programming: 4 Types & Details

a loop is a string of given single or multiple instructions that are continuously recounted as the condition check process is running until a particular process is done.

In this blog post, you will learn the fundamentals of loops to sharpen your knowledge of decision-making statements and loops.

In computer programming, a loop is a string of given single or multiple instructions that are continuously recounted as the condition check process is running until a particular process is done, such as getting an item of data and altering it, & then some condition checking process such as whether a counter has brought the expected number.

All the programming languages provide a notion called loop, which helps in executing one or more statements up to a desired number of times. All high-level programming languages provide eclectic forms of loops, which can be used to execute one or more statements repeatedly.

Additionally, Loops are programming elements that repeat a portion of code a set number of times until the desired process is complete. Repetitive tasks are common in programming, and loops are necessary to save time and minimize errors.

For Loop

A for loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly. A for loop has two parts: a header specifying the iteration, and a body that is executed once per iteration.

A “For” Loop is used to repeat a specific block of code a known number of times.A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

syntax of for loop is :

for ( init; condition; increment ) {
   statement(s);
}

Let’s see this as a flow chart diagram

for loop diagram representation
for loop diagram

The flow of control in for loop :

  • The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not needed to put a statement here, as long as a semicolon appears.
  • Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the ‘for’ loop.
  • After the body of the ‘for’ loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
  • The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the ‘for’ loop terminates.

Below program has for loop statements:

#include <stdio.h>
 
int main () {

   int a;
	
   /* for loop execution */
   for( a = 10; a < 20; a = a + 1 ){
      printf("value of a: %d\n", a);
   }
 
   return 0;
}

While Loop

A while loop is represented with the following syntax −

while ( condition ) {
/….while loop body …./
}

Let’s see this as a flow chart diagram

while loop diagram representation
while loop diagram
  • A while loop starts with a keyword while-minded by a condition enclosed in ( ).
  • Additional to the while() statement, you will have the body of the loop held in curly braces {…}.
  • A while loop body can have one or more lines of source code to be executed continually.
  • If the body of a while loop has just one line, then it is optional to use curly braces {…}.
  • A while loop keeps executing its body till a given condition equals to true. If the condition becomes equal to false, the while loop exits that process and continues executing from the immediate next statement (i++) after the while loop body.
  • A condition is usually a relational statement, which is evaluated as either true (return 1;) or false(return 0;). A value equal to zero is treated as false and any non-zero value works as true.

Do-while Loop

A while loop matches a given condition before it executes any statements given in the body part, And another form of loop, called do…while allows the code to execute a loop body before matching a given condition.

A do-while loop is represented with the following syntax −

do {
   /*....do...while loop body ....*/
} 
while ( condition );

Let’s see this as a flow chart diagram

do while diagram representation
do while diagram

let’s see an example of a do-while loop program:

#include <stdio.h>

int main() {
   int i = 0;
   
   do {
      printf( "Hello, World!\n");
      i = i + 1;
   }
   while ( i < 5 );
}

There are two important statements in the do-while loop :

Break Statement

When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.

// syntax
break;
do while loop break statement diagram
do while loop break statement diagram

below the program is a do-while loop with a break statement :

#include <stdio.h>

int main() {
   int i = 0;
   do {
      printf( "Hello, World!\n");
      i = i + 1;
      
      if( i == 3 ) {
         break;
      }
   }
   while ( i < 5 );
}

Continue Statement

The continue statement in a programming language works somewhat like the break statement. Instead of forcing termination, continue forces the next iteration of the loop to take place, and skips any code in between.

// syntax
continue;
do while loop continue statement diagram
do while loop continue statement diagram

below the program is a do-while loop with a continue statement:

#include <stdio.h>

int main() {
   int i = 0;
   do {
      if( i == 3 ) {
         i = i + 1;
         continue;
      }
      printf( "Hello, World!\n");
      i = i + 1;
   }
   while ( i < 5 );
}

For each Loop

For-each is another array traversing method like for loop, while loop and do-while loop introduced in the previous section of this post.

the for-each loop starts with the keyword for like a normal for-loop. This type of for loop structure eases the traversal over an iterable data set. It does this by eliminating the initialization process and traversing over each and every element rather than an iterator.

syntax of for-each loop :

for(type variable_name : array/vector_name)
{
    loop statements
    ...
}

The below program is the for-each loop program:

#include<iostream>
using namespace std; 
int main() 
{ 
    int arr[]={1,2,3,4,5};   //array initialization
    cout<<"The elements are: ";
    for(int i : arr)
    {
    	cout<<i<<" ";
    }
    return 0;
}

Key points of the for-each loop –

  • It eliminates the possibility of errors and makes the code more readable.
  • Easy to implement
  • Does not require pre-initialization of the iterator
  • Cannot directly access the corresponding element indices
  • Cannot traverse the elements in reverse order
  • It doesn’t allow the user to skip any element as it traverses over each one of them

Map

There are 3 different ways to Iterate over a map.

  • Iterating over the map using std::for_each and lambda function
  • Iterating over the map using rang based for loop
  • Iterate over a map using STL Iterator

A loop is a fundamental programming idea that is commonly used in writing programs.

An infinite loop is one that lacks a functioning exit routine. The result is that the loop repeats continually until the operating system senses it and terminates the program with an error or until some other event occurs (such as having the program automatically terminate after a certain duration of time).

We hope that this information might have stirred your brain cells. though these are a few examples when you dive into the field of learning, and once you start with coding, then you will get to know the real usage of While Loop for yourself.

Share your love
Lamba Pankaj
Lamba Pankaj
Articles: 11

Leave a Reply

Your email address will not be published.

I'm not a robot *Captcha loading...

Website Design Trends in 2022 5 Movies that Programmers Should Watch Best Search Engine for Developers – You.com 06 Free Website Hosting Providers for Developers You should Know Learn Programming while playing games
Secured By miniOrange