Programming

What are Loops in C and C++ Programming

Have you ever thought that if you want to display 100 times message like “hello” on screen, or if you want a function/ part of the program to be executed several times, then without typing that much times you can go through Loop for the solution?

These are also referred to as repetitive tasks. As we know, when the process is repeated several times in a loop, the execution time will be reduced significantly. This kind of programming is required in various games, multimedia applications, etc. In all these applications, the loop is used to run the same program multiple times. Therefore, we can say that the loop is the best component for running a program multiple times.

loops in c and c++

Loop in C/C++ is defined as a process of repeating the same task as per the requirement. A counter variable is always present there, and the program executes until the counter variable satisfies the condition. Loops are defined in two main types:

  • Entry Controlled Loop
  • Exit Controlled Loop

Entry Controlled Loop : As the name suggest, the condition is checked at the beginning of the loop. Example For loop and while loop.

For example,

Syntax in for loop

for ( initializer ; condition ; iteration){

}

//For loop

#include<iostrem>

using namespace std;

int main()

{

   int i=0;

   for( i=0 ; i<10 ; i++)

   {

      cout<<”Hello”<<endl;

   }

   return 0;

}

// while loop

Syntax :

initialization

while ( condition )

{

  increment;

}

Example

int i=0;

while ( i < 10 )

{

   cout<<”hello”<<endl;

i++;

}

Exit Controlled Loop :   Here the condition is checked at the end of the loop.

For example,  do – while () loop

Syntax

initialization

do {

   iteration

}while (condition);

Even if the condition is false, the expression is executed atleast one time.

For example,

int i = 0;

do {

 i++;

 cout<<”Hello”<<endl;

} while ( i < 10 )

Infinite Loop

A loop which continues to run forever is known as infinite loop. For example,

for ( ; ; )

{

   cout<<”Hello”<<endl;

}

Or

int i = 0;

while ( i ==0 )

{

  cout<<”Hello”<<endl;

}

Conclusion

So we can create a simple loop for the given task and then exit the loop when the given task completes. Loops are used to execute a block of code at least once. So, loops are an essential concept in programming. C/C++ has the concept of while loops. A loop in C/C++ consists of a header block and a body block. The header block contains the condition or loop control statement. When the condition is true the body block is executed. If the condition is false the body block is not executed. Loops in C/C++ also come with different statements which are used to control the loop.

Leave a Reply

Back to top button