What Is Loops In C/C++?

What Is Loops In C/C++?
What Is Loops In C/C++?

Introduction

Loops in programming come into use when there is a need to execute a specific block of code repeatedly. Loops are handy while a repetitive task has to be performed. If loops are not there, the task becomes cumbersome. They make the code readable, which in turn makes the debugging process less tiring.

There are three types of loops in C/C++, namely for loop, while loop, and do…while loop. Let’s learn about each one of them in detail.

Why is a loop needed?

Loops are used when a specific code has to be executed several times. Consider a case where one has to print numbers from 1 to 10. This can be done by writing the print statement 10 times like this.

Code in C

#include <stdio.h>
 
int main(void) {
 // print the numbers from 1 to 10
 printf("1\n");
 printf("2\n");
 printf("3\n");
 printf("4\n");
 printf("5\n");
 printf("6\n");
 printf("7\n");
 printf("8\n");
 printf("9\n");
 printf("10\n");
 return 0;
}

Code in C++

#include <iostream>
using namespace std;
 
int main() {
 // print the numbers from 1 to 10
 cout<<"1"<<endl;
 cout<<"2"<<endl;
 cout<<"3"<<endl;
 cout<<"4"<<endl;
 cout<<"5"<<endl;
 cout<<"6"<<endl;
 cout<<"7"<<endl;
 cout<<"8"<<endl;
 cout<<"9"<<endl;
 cout<<"10"<<endl;
}

Output:

1
2
3
4
5
6
7
8
9
10

This process is really cumbersome and can get tiring when the execution times get larger in number. To solve this issue, loops come into the picture. These ten lines can be easily shortened using loops in C/C++. Loops make the code more manageable and organised.

Execution of a loop

The loop consists of two parts:

  • Test Condition: It controls the termination of the loop 
  • Code body: It contains the code which is executed when the test condition is true

The test condition is checked to decide the execution of the code. If the condition is true, the code executes; else, it terminates.

General Flow Chart of a Loop

blog banner 1

Depending on the position of the termination criteria, loops are divided into two types: Entry-controlled loops and Exit-controlled loops. Let’s discuss them in the next section.

Entry controlled loop

In the entry controlled loop, the test condition is tested before entering the loop. This works only if the test condition is true. for loop and while loop come under this category.

Control Flow of Entry Controlled Loop

Exit controlled loop

In an exit controlled loop, the test condition is tested or evaluated at the end of the loop body. This type of loop is executed at least once, irrespective of whether the test condition is true or false. do… while loop comes under this category.

Control Flow of Exit Controlled Loop

for Loop in C/C++

A for loop is used to perform a repetitive task a specific number of times. The number of times it is executed depends on the test statement and updation value. It is commonly used to traverse through the data structures like the array and linked list.

Syntax:

for(initialisation; test condition; updation) { 
	// body of the loop
}

How does the for loop work?

  • First is the initialisation statement, which is executed only once. In this step, the loop control variables are declared and initialised.
  • Next, the test condition is evaluated. If it is true, the body of the loop is executed, or else, the loop terminates.
  • After the body of the loop is executed, the loop control variable is updated. 
  • And the process repeats till the condition becomes false and the loop terminates.

Flow Chart of for loop

Let’s look at a simple program of printing numbers from 1 to 10 using the for a loop.

Code in C

#include <stdio.h>
 
int main(void) {
 // initial i as the loop control variable and declare it as 1
 // run the loop till i is less than or equal to 10
 // update i by 1 after every iteration
 for(int i = 1 ; i <= 10 ; i++) {
   // print the value of i
   printf(" %d \n", i);
 }
 return 0;
}

Code in C++

#include <iostream>
using namespace std;
 
int main() {
 // initial i as the loop control variable and declare it as 1
 // run the loop till i is less than or equal to 10
 // update i by 1 after every iteration
 for(int i = 1 ; i <= 10 ; i++) {
   // print the value of i
   cout<<i<<endl;
 }
}

Output

1
2
3
4
5
6
7
8
9
10

Notice how effectively the code has been reduced when a for loop is used.

while loop in C/C++

A while loop executes the loop body until the test statement is false. It is mainly used in situations where the exact number of iterations is not known beforehand.

Syntax:

initialisation
while(condition) { 
    // body of the loop
    // updation
}

How does the while loop work?

  • The loop control variables are declared outside the loop.
  • First, the test condition is checked.
  • If the test statement is true, the body of the loop is executed, or else the loop terminates.
  • Loop control variables are then updated inside the loop body.
  • And the process repeats till the condition becomes false and the loop terminates.

FlowChart of while loop

Let’s look at a simple program of guessing the number using the while loop.

Problem Statement: Write a program for guessing the correct number game. In this game, the user has to guess a number, which in this case is 10. The game should not stop until the user gets the correct answer.

Code in C

#include <stdio.h>
#include <stdbool.h> 
 
int main(void) {
 // the number to be guessed is 10
 int number = 10;
 // guess is the loop control variable
 bool guess = true;
 // executes the loop till guess is false
 while(guess == true) {
   int numberGuessed;
   printf("Enter the number:");
   scanf("%d", &numberGuessed);
   // checks if the guessed number and the number to be guessed is same
   if(numberGuessed == number) {
     printf("You won!!!\n");
     guess = false;
   } else {
     printf("Try again.\n");
   }
 }
 return 0;
}

 Code in C++

#include <iostream>
using namespace std;
 
int main() {
  // the number to be guessed is 10
 int number = 10;
 // guess is the loop control variable
 bool guess = true;
 // executes the loop till guess is false
 while(guess == true) {
   int numberGuessed;
   cout<<"Enter the number:"<<endl;
   cin>>numberGuessed;
   // checks if the guessed number and the number to be guessed is same
   if(numberGuessed == number) {
     cout<<"You won!!!"<<endl;
     guess = false;
   } else {
     cout<<"Try again."<<endl;
   }
 }
 return 0;
}

Output:

Enter the number:
8
Try again.
Enter the number:
-4
Try again.
Enter the number:
10
You won!!!

do…while loop in C/C++

The do…while loop is an exit controlled loop where the condition is tested after the execution of the loop body. It is used when the loop has to execute at least once, for example, in a menu-driven program where the termination condition depends upon the end-user.

Syntax:

initialisation
do { 
    // body of the loop
    // updation
}

How does the do…while loop work?

  • In this, first, the body of the loop is executed
  • The test condition is then evaluated
  • If the test condition is true, the process continues, or else it continues
  • This process goes on till the test condition is false, and the loop terminates

Flow Chart of do…while loop

Let’s look at a program to play the music till the user wants it to be played.

Code in C

#include <stdio.h>
#include <stdbool.h> 
 
int main(void) {
 // loop control variable
 bool play = true;
 // executes the loop before checking test case
 do {
   printf("Music played.\n");
   printf("Do you want to play it again? (0/1)");
   int input;
   scanf("%d",&input);
   // updation
   if(input == 0) {
     play = false;
     printf("Music stopped.");
   }
 } while(play == true); // test condition
 return 0;
}

Code in C++

#include <iostream>
using namespace std;
 
int main() {
 // loop control variable
 bool play = true;
 // executes the loop before checking test case
 do {
   cout<<"Music played."<<endl;
   cout<<"Do you want to play it again? (0/1)"<<endl;
   int input;
   cin>>input;
   // updation
   if(input == 0) {
     play = false;
     cout<<"Music stopped.";
   }
 } while(play == true); // test condition
 return 0;
}

Output

Music played.
Do you want to play it again? (0/1)
1
Music played.
Do you want to play it again? (0/1)
1
Music played.
Do you want to play it again? (0/1)
0
Music stopped.

for_each loop in C++

There is one more type of loop in C++, the for_each loop. It accepts a function that executes each of the elements in the container. It improves the code readability and overall performance of the code. This loop is defined in the “algorithm”  header file.

Syntax:

for_each (InputIterator first, InputIterator last, Function func)

where,
first: Input iterator to the initial position
last: Final iterator to the final position
func: Unary function that accepts an element in the range as an argument

Let’s look at a simple program to print odd numbers in an array.

Code in C++

#include <iostream>
#include <algorithm>
using namespace std;
 
int printOdd(int n) {
   if (n % 2 != 0)
       cout << n << ' ';
   return 0;
}
 
int main() {
   int arr[5] = {1, 2, 3, 4, 5};    
   cout << "The Array contains the following odd numbers" << endl;
   // starts from index 0 and ends at index 4
   // printOdd is the function
   for_each(arr, arr + 5, printOdd);
   return 0;
}

Output

The Array contains the following odd numbers
1 3 5

Check this out for more details.

Infinite loops in C/C++

An infinite loop (or an endless loop) is a loop that does not terminate and keeps on executing. This happens as the test condition does not become false. 

Let’s see how to write “Hello World” infinite times in all the cases.

Infinite for loop 

In an infinite for loop, expression is not given in the syntax. Instead, two semicolons are provided.

Syntax:

for(	;	;	) {
	// body of the loop
}

Code in C

#include <stdio.h>
 
int main(void) {
 for(  ; ; ) {
   printf("Hello World\n");
 }
 return 0;
}

Code in C++

#include <iostream>
using namespace std;
 
int main() {
 for(  ; ; ) {
   cout<<"Hello World"<<endl;
 }
 return 0;
}

Infinite while loop 

If the expression passed in the while loop results in any non-zero value, the loop will run infinite times.

Code in C

#include <stdio.h>
 
int main(void) {
 while(1) {
   printf("Hello World\n");
 }
 return 0;
}

Code in C++

#include <iostream>
using namespace std;
 
int main() {
 while(1) {
   cout<<"Hello World"<<endl;
 }
 return 0;
}

Infinite do…while loop 

The do…while loop will run infinite times if any non-zero value is passed in the test condition.

Code in C

#include <stdio.h>
 
int main(void) {
 do {
   printf("Hello World\n");
 } while(1);
 return 0;
}

Code in C++

#include <iostream>
using namespace std;
 
int main() {
 do {
   cout<<"Hello World"<<endl;
 } while(1);
 return 0;
}

Output

Hello World
Hello World
Hello World
Hello World
Hello World
.
.
.

Nested for loops in C/C++

Nested loops basically mean a loop inside another loop. Nested while loop and do…while loop also exists but nested for loop is the most commonly used one. Nested for loop is widely used in problems involving 2-D arrays. Each time the outer loop is iterated, the inner loop repeats itself.

Syntax:

for(initialisation; test condition; updation) { 
	for(initialisation; test condition; updation) { 
		// body of the loop
	}
}

Flow Chart of Nested for loop

Let’s look at a simple program to display the elements of a 2-D array.

Code in C

#include <stdio.h>
 
int main(void) {
 // declare a 2-D array
 int arr[3][3]={{1,2,3},{4,5,6},{7,8,9}}; 
 // initial i as the loop control variable and declare it as 0 as array index starts from 0
 // run the loop till i is less than 3
 // update i by 1 after every iteration
 for(int i = 0 ; i < 3 ; i++) {
     // initial j as the loop control variable and declare it as 0
     // run the loop till j is less than 3
     // update j by 1 after every iteration
    for(int j = 0 ; j < 3 ; j++) {
       // print element at ith row and jth column
       printf("%d ",arr[i][j]); 
   }
   printf("\n");
 }
 return 0;
}

Code in C++

#include <iostream>
using namespace std;
 
int main() {
 // declare a 2-D array
 int arr[3][3]={{1,2,3},{4,5,6},{7,8,9}}; 
 // initial i as the loop control variable and declare it as 0 as array index starts from 0
 // run the loop till i is less than 3
 // update i by 1 after every iteration
 for(int i = 0 ; i < 3 ; i++) {
     // initial j as the loop control variable and declare it as 0
     // run the loop till j is less than 3
     // update j by 1 after every iteration
    for(int j = 0 ; j < 3 ; j++) {
       // print element at ith row and jth column
       cout<<arr[i][j]<<" ";
   }
   cout<<endl;
 }
}

Output

1 2 3
4 5 6
7 8 9

for loop vs. while loop vs. do…while loop

for loopwhile loopdo…while 
Syntax:for(initialisation; test condition; updation) {     // body of the loop}Syntax:initialisationwhile(condition) {     // body of the loop    // updation}Syntax:initialisationdo {     // body of the loop    // updation} while(condition) ;
entry controlled loop entry controlled loop exit controlled loop 
if the condition is not true for the first time, then the control will never enter the loopif the condition is not true for the first time, then the control will never enter the loopeven if the condition is not true for the first time, the control will enter the loop.
can terminate even without executing it oncecan terminate even without executing it onceexecuted at least once
the syntax does not end with a “;”the syntax does not end with a “;”the syntax ends with a “;”

Which loop to choose?

The choice of the loop depends on the conditions. In most cases, for loop is preferred as it is better than any other loop. If the given problem requires pre-conditions, for loop or while loop is used, and if post-condition is needed, do…while loop is used.

Try out some of the problems on loops to get a firm hold on the looping concept:

Frequently Asked Questions

What are the loops in C/C ++?

The loops in C/C++ are for loop, while loop, and do…while loop.

Which are the entry-controlled loops in C/C++/?

for loop and while loop are entry-controlled loops.

In which loop is the code executed at least once?

In do…while loop, the code is executed at least once as the condition is tested after the execution.

How to suddenly quit any loop in C/C++?

The control statement break can be used to terminate the loop suddenly.

Which loop is used to access the elements of a 2-D array?

The nested for loop is used to access elements of a 2-D array.

What is the difference between the while loop and the do…while loop?

In the while loop, the test condition is tested before execution, and in the do…while loop, the test condition is tested after execution.

Key Takeaways

This was all about loops in C/C++. This blog attempted to give a thorough explanation of the various loops in C/C++ with the help of examples.

Loops play an essential role in any programming language. In interview questions, too, the knowledge of loops is very handy. Questions can be asked combining the knowledge of loops and conditional statements like the FizzBuzz program.

Don’t stop here. Try out your understanding of loops with the help of these MCQs. Also, check out our C++ guided path to learn C++ from scratch.

By Hari Sapna Nair