Loops in C and C++ | The Survival Guide for every Beginner

In this tutorial, we will begin our discussion by understanding the meaning of the term Loops followed by “Iteration” or “Looping”. It is important to note that the terms “Iteration” and “Looping” can be used interchangeably. Then, we will lay emphasis on how and why is looping done in C and C++. Further, we will discuss the significance of loops in C and C++. Then, we will move towards discussing its types in detail followed by control statements.

We will end this tutorial by analyzing the choice of looping.

It is important to have a great command over this topic to ease your way out in C and C++ programming as it plays an integral role while working with repetitive statements.

We all know how cumbersome it is to give a separate print statement each time we wish to display something, right? We can easily resolve this issue by covering every topic in detail to master the concept of looping.

1. What are Loops in C and C++?

Loops are nothing but a segment of code we use to repeat a specific block of code. It is important to note that ‘loop’ is a concept and ‘looping’ refers to a process to implement loops in C and C++.

Iteration or looping refers to the specified sequence in which a pattern or a block of code is repeated until the condition becomes no longer true. As long as the condition remains to be true, the loop is executed. It is terminated when the condition is false or no longer satisfied.

Take a break and explore the Applications of C

Every loop has two parts:

1.1 Body of the loop

It consists of the content, like the print statement or a fragment of code which we want to run multiple times.

1.2 Control Statement

These statements control the execution of the loop and are important for loop termination.

Since we now got an idea as to what are loops in C/C++, let’s acknowledge its importance by thinking about its significance.

  • It is of the utmost importance when the programmer wants to create a database. Creating a database requires taking multiple inputs several times, storing it, displaying it and performing modifications.
  • Most of the programs which require mathematical calculations are simplified using loops.
  • It saves time and effort.

This is a diagrammatic representation of how looping works in C and C++.

How looping works in C and C++

2. Types of Loops in C and C++

The C and C++ language offer you the facility of looping in various formats. There are basically 2 types of loops:

Do you know the major features of C++?

2.1 Entry-controlled loops

Before we execute the loop, we need to check the given conditions beforehand. For this loop to work, the test condition should necessarily be true. For example, for and while loops are entry-controlled.

Here is a diagrammatic representation of an entry-controlled loop which will help you better understand its working:

Entry-controlled loops in C and C++

2.2 Exit-controlled loops

In contrast to entry controlled loops, this type of looping offers the benefit to the user to execute the loop at least once before checking the condition. In this case, to execute the loop, the test condition might not necessarily be true.

For example, the do-while loop is exit-controlled. The C and C++ language offer this benefit, unlike Python.

Here is a diagrammatic representation of an exit-controlled loop which will help you better understand its working:

Exit-controlled loops in C and C++

Before we discuss the various types of loops in detail, let us understand that the control statements should correctly be specified, otherwise the loop might never terminate, which is formally referred to as, the infinite loop. It is a bad programming practice and hence should be avoided in every possible way.

The following steps prevent your program from going into an infinite (endless) loop:

  • When the termination conditions are not clearly mentioned.
  • The control statements are missing.
  • The conditions are never met.

Loops in C and C++1

3. While Loop in C and C++

It is the easiest and most basic type of looping which exists in the C and C++ language. It is an entry controlled loop.

As soon as the loop is executed for the first time, the flow of control goes back to the beginning of the loop again, checking if the subsequent conditions hold true or not.

After loop termination, the flow of control goes back to the immediate statement after the loop.

Before we move forward, let’s revise basic Syntax of C

Basic Syntax

while(condition)
{
statement(s)
}

Key takeaway: If the loop isn’t multiline, which means, it does not contain more than one line, it needn’t be enclosed within curly braces. It is applicable for while, for and do-while loops in C.

Here is a diagrammatic representation of the while loop:

Let us consider a very simple program to print a certain statement 10 times using the while loop:

Example of While loop in C

Here is a code in C that illustrates the basic syntax and working of the while loop:

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

int no_of_executions = 1; //Initializing the number of executions to 1

while ( no_of_executions <= 10 )
{
printf("Welcome to DataFlair tutorials!\n"); //Statement to be displayed 10 times
no_of_executions++; //Incrementing the number of executions
}
return 0;
}

Code on Screen

Example of While loop in C

Output

Output of While loops in C

To run and execute the above program, Install C on Linux with GCC Compiler

Example of While loop in C++

Here is a code in C++ that illustrates the basic syntax and working of the while loop:

#include <iostream>
using namespace std;

int main()
{

int no_of_executions = 1; // Initializing the number of executions to 1

while ( no_of_executions <= 10 )
{
cout<<"Welcome to DataFlair tutorials!"<<endl; // Statement to be displayed 10 times
no_of_executions++; // Incrementing the number of executions
}

return 0;
}

Code-

Example of While loop in C++

Output-

Output of while loop in C++

Elucidation

Let us understand every statement step by step:

  • Initialization: Since we want to display the text within the print statement 10 times, therefore, we start with 1. If we initialize no_of_executions to 0, the loop will display the message 11 times as indexing starts from 0.
  • Condition: Here, while is a reserved keyword which indicates the use of while loop. The condition for the loop to be terminated is mentioned within simple brackets. The loop will be executed 11 times. The message will be displayed 10 times, the other one time the loop would check if the condition is true, which is not the case here, so the loop will terminate.
  • Incrementation: For the flow of control to be passed onto the next condition, that is, for no_of_exections to change its value to 2, we use increment operator.

In order to realize the contribution of looping in mathematical aspects, let us now discuss the syntax and working of while loop with the help of a simple example by printing numbers from 1 to 10.

Here is a code in C that illustrates the working of the while loop when playing with numbers:

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

printf("Welcome to DataFlair tutorials!\n\n");

int no_of_executions = 1; // Initializing the number of executions to 1
while(no_of_executions <= 10) // Condition
{
printf("%d\n",no_of_executions);
no_of_executions++; // Incrementing the number of executions
}
return 0;
}

Code on Screen

Do while loop in C with Example

Output

Output of While loop in C Programming

Elucidation

As mentioned earlier, we initialize, specify the condition and increment the variable in order to use the while loop. Now, let us understand how to display numbers from 1 to 10 using the while loop:

  • We initialized the no_of_executions to 1 as we want to start printing the numbers from 1. If we wanted to begin with 5 and end with 15, we would initialize no_of_executions to 5 and changed the condition to no_of_exections <=15.
  • The loop will be executed till the number is incremented and a point is achieved where the no_of_executions becomes 11 and the loop terminates.

Haven’t you studied Variables in C?

4. Do-While Loop in C and C++

The do-while loop is pretty similar to while loop with an additional feature. It is an exit-controlled loop that gives the user the provision to execute the loop at least one.

It safe to say that the do-while loop is better than while loop in all aspects. Here, the flow of control goes something like this: First, the body of the loop is executed, then the condition is checked which is in contrast to the while loop.

Basic Syntax-

do
{
statement(s)
} while(condition)

In the while loop, the keyword while is written at the beginning of the loop, but here, it is written at the end of the loop.

Here is a diagrammatic representation of the do while loop:

do while in C and C++

Let us consider a simple program to print the squares of first 10 natural numbers using the do while loop:

Here is a code in C that illustrates the basic syntax and working of the do while loop:

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

printf("Welcome to DataFlair tutorials!\n\n");

int number = 1; // Initializing the number to 1
do // Starting of the do-while loop
{
printf("%d\n",number*number);
number ++; // Incrementing the number from 1 to 10
}
while(number <= 10);
return 0;
}

Code on Screen

Example of Do-while loops in C

Output

Output of Do while loop in C

Here is a code in C++ that illustrates the basic syntax and working of the do while loop:

#include<iostream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

int number = 1; // Initializing the number to 1
do // Starting of the do-while loop
{
cout<< number*number <<endl;
number ++; // Incrementing the number from 1 to 10
}
while(number <= 10);
return 0;
}

Code-

Example of Do while in C++

Output-

Output of Do-While in C++

Elucidation

  1. We initialized the number to 1 so that it prints the squares of numbers starting from 1.
  2. In the do-while loop, we use the keyword do at the starting of the loop.
  3. In the print statement, we performed the multiplication of the variable with itself to find its square for simplicity. To find cubes or other higher powers to which the number is to be raised by, we use math functions that have a wide range of inbuilt functions to perform mathematical operations.
  4. We increment the number from 1, now it has a value 2 which will follow the same process and further keep on incrementing till the specific condition is met.

Build your basic knowledge with Functions in C

5. For Loop in C and C++

It is safe to say that it is the best loop for iteration by programmers since it is very easy to implement and has a well-built structure. It is an entry controlled loop.

Basic Syntax:

for( initialization ; condition ; increment / decrement )
{
statement(s)
}

The for loop takes into account three parameters:

  • Initialization
  • Condition
  • Increment or decrement

Here is a diagrammatic representation of the for loop:

For loop in C and C++

Let us consider a simple example to display all the even numbers from 1 to 10 using for loop. In order to keep things simple, we use the concept that all numbers from 1 to 10 are multiples of 2

Example of for loop in C

Here is a code in C that illustrates the working of the for loop to display even numbers from 1 to 10:

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

printf("Welcome to DataFlair tutorials!\n\n");

int number;
for(number=1;number<=5;number++) //Use of for loop to print even numbers from 1 to 10
{
printf("%d\n",2*number); // Printing all the even numbers from 1 to 10

}
return 0;
}

Code on Screen

For Loop in C with Example

Output

Output of For loop in C

Example of for loop in C++

Here is a code in C++ that illustrates the working of the for loop to display even numbers from 1 to 10:

#include <iostream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

int number;
for(number = 1; number <= 5; number ++) //Use of for loop to print even numbers from 1 to 10
{
cout<< 2*number <<endl; // Printing all the even numbers from 1 to 10
}

return 0;
}

Code-

Example of For loop in C++

Output-

Output of For loop in C++

To run and execute the above program, install C++ on Linux with G++ Compiler

Elucidation

  1. We declared the variable number in the main function.
  2. We initialized the value of the number to 1 and number<=5 since there are 5 even numbers between 1 to 10.
  3. We multiplied the variable number by 2 to obtain all the even numbers lying between 1 to 10.

In this way, we can implement the same program using if-else condition and modulus operator which we will discuss in detail in the section.

6. Nested For Loop in C and C++

Let’s further elaborate our discussion on nested for loop. Before we begin, let’s make it clear that nested while and do-while loops exist but aren’t popularly used. The term nested refers to a loop within a loop. Each time the outer loop is iterated, the inner loop repeats itself.

Basic Syntax:

for( initialization ; condition ; increment / decrement )
{
for( initialization ; condition ; increment / decrement )
{
statement(s)
}
}

Here is a diagrammatic representation of the nested for loop:

 Nested For Loop in C and C++

Let us consider an example of the nested for a loop by displaying the following pattern:

*
* *
* * *

Example of Nested Loop in C

Here is a code in C to display the above pattern:

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

printf("Welcome to DataFlair tutorials!\n\n");

int no_of_rows=3;
int iteration1, iteration2;
for( iteration1 = 1; iteration1 <= no_of_rows; iteration1++ )
{
for( iteration2 = 1; iteration2<=iteration1; iteration2++ )
{
printf("* ");
}
printf("\n"); //To display a gap between the lines
}
return 0;
}

Code on Screen

Nested For Loop in C

Output

Output of Nested For Loop in C

Example of Nested Loop in C++

Here is a code in C++ to display the above pattern:

#include<iostream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

int no_of_rows = 3;
int iteration1, iteration2;
for( iteration1 = 1; iteration1 <= no_of_rows; iteration1++ )
{
for( iteration2 = 1; iteration2<=iteration1; iteration2++ )
{
cout<<"* ";
}
cout<<endl; //To display a gap between the lines
}
return 0; 
}

Code- 

Example of Nested Loop in C++

Output – 

Output of Nested Loop in C++

Elucidation

  1. In the given sample problem, there are 3 rows and hence we initialize the number of rows to 3.
  2. We need 2 for loops, one to traverse row-wise and the other to traverse column-wise and hence we initialize iteration1 and iteration2 as 1. We keep iteration2 less than iteration1 because the loop would be executed 3 times.
  3. For each iteration of the outer loop, the inner loop gets executed every time.
    We used ‘*’ in the print statement to display it.

7. Control Statements in C and C++

Control statements are used to specify the flow of control in the program which basically refers to the sequence in which the program gets executed.
We use control statements in C because of the following reasons:

  • It is easy to implement and perform repetitive operations.
  • We can access any fragment of code in the entire program whenever required.
  • It maintains a sequential control of various segments of the code.

Here are a couple of keywords associated with control statements:

7.1 Break Statement in C and C++

The keyword break is used in the selection statement of the switch case. It enables us to terminate the loop immediately as per our requirement.

In order to understand the use of break, we must understand the switch case.

Sometimes, we have multiple operations to perform. Merging all the operations into a single program makes our program haphazard.

In order to simplify things, we divide our code into various segments and it depends on the choice of the user which segment he wishes to use. We can achieve this task by using the switch statement.

Here is a diagrammatic representation of break statement:

Execution Flow of Break Statement

A typical example of the switch statement is the construction of a calculator that performs basic mathematical operations like addition, subtraction, multiplication, and division. The user needs to switch cases between these 4 operations.

The role of break comes into play when we need to switch cases.

Example of Break Statement in C and C++

Here is a code in C to create a basic calculator which illustrates the use of break keyword:

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

printf("Welcome to DataFlair tutorials!\n\n");

int number1 = 10, number2 = 20;
char operation = '+';
switch(operation)
{
case '+':
printf("Addition of %d and %d is: %d\n", number1 , number2 , number1 + number2 );
break;
case '-':
printf( "Subtraction of %d and %d is: %d\n", number1 , number2 , number1 - number2 );
break;
case '*':
printf( "Multiplication of %d and %d is: %d\n", number1 , number2 , number1 * number2 );
break;
case '/':
printf( "Division of %d and %d is: %d\n", number1 , number2 , number1 / number2 );
break;
default:
printf( "Invalid choice\n");
break;
}
return 0;
}

Code on Screen

Example of Break Statement in C

Output

Output of Break Statement in C

Example of Break Statement in C++

Here is a code in C++ to create a basic calculator which illustrates the use of break keyword:

#include <iostream>
using namespace std;
int main()
{
cout<<"Welcome to DataFlair tutorials!"<<endl;

int number1 = 10, number2 = 20;
char operation = '+';
switch(operation)
{
case '+':
cout<< "Addition of "<< number1 <<" and " << number2 << " is " << number1 + number2 << endl;
break;
case '-':
cout<< "Subtraction of "<< number1 <<" and " << number2 << " is " << number1 - number2 << endl;
break;
case '*':
cout<< "Multiplication of "<< number1 <<" and " << number2 << " is " << number1 * number2 << endl;
break; 
case '/':
cout<< "Division of "<< number1 <<" and " << number2 << " is " << number1 / number2 << endl;
break;
default:
cout<<" Invalid choice "<<endl;
break;
}
return 0; 
}

Code-

Example of Break Statement in C++

Output-

Break Statement in C++ with Output

7.2 Continue Statement in C and C++

If the user wishes to skip to the next iteration without exiting the loop, the continue keyword comes in play.

Here is a diagrammatic representation of the continue statement:

Execution of Continue Statement

Let us consider a problem in which we want to display numbers from 1 to 10 but we don’t want to include 9, because 7 ate nine!

Example of Continue Statement in C

Here is a code in C which helps us to solve this problem:

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

printf("Welcome to DataFlair tutorials!\n\n");

int number = 10;
printf( "The numbers are:\n");
for( number = 1 ; number <= 10 ; number ++ )
{
if (number == 9)
{
continue;
}
printf("%d\n", number);
}
return 0;
}

Code on Screen

Continue Statement in C with Example

Output

Output of Continue Statement in C

Example of Continue Statement in C++

Here is a code in C++ which helps us to solve this problem:

#include <iostream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl;

int number = 10;
cout<<"The numbers are:"<<endl;
for( number = 1 ; number <= 10 ; number ++ )
{
if (number == 9)
{
continue;
}
cout<<number<<endl;
}
return 0;
}

Code- 

Example of Continue Statement in C++

Output-

Output of Continue statement in C++

7.3 Goto Statement in C and C++

It is basically a jumping statement, transferring the flow of control from one iteration to the other.

Here is a diagrammatic representation of the goto statement:

Execution Flow of goto statement

There are 2 ways in which goto statement can be used:

7.3.1 Down to top

Let us consider a problem where we wish to play the multiples of 3 in the range (1 to 30)

Here is a code in C that illustrates this approach:

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

printf( "Welcome to DataFlair tutorials!\n\n" );

int number=3;

repeat:
printf("%d\n",number);
number=number+3;

if(number<=30)
goto repeat;
return 0;
}

Code on Screen

Output of of goto statement in C

Output

Output of down to top approach in goto statement

Here is a code in C++ that illustrates this approach:

#include <iostream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

int number = 3;

repeat:
cout<< number <<endl;;
number=number+3;

if(number<=30)
goto repeat;
return 0; 
}

Code- 

Down to top Example in C++

Output-

Output of Down to top Example in C++

7.3.2 Top to down

Let us consider a problem where we wish to print any number which is greater than 10.

Here is a code in C that helps us to solve the above problem:

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

printf( "Welcome to DataFlair tutorials!\n\n" );

int number = 30;
if(number<=20)
goto end;
printf("The number is : %d\n", number);
end:
printf("Thank you!");
return 0;
}

Code on Screen

Down to top approach in goto statement in C

Output

Output of goto Statement in C

Here is a code in C++ that helps us to solve the above problem:

#include <iostream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

int number = 30;
if(number<= 20)
  goto end;
  cout<<"The number is :"<< number<<endl;
end:    
  cout<<"Thank you!"<<endl;
return 0; 
}

Code-

Example of Top to down in C++

Output-

Output of Top to down in C++

8. Which Loop to Select?

In order to make the choice of looping, the foremost thing to keep in mind is to decide whether the given problem at hand requires a pre-condition, for which we may use the while loop or the for loop, and, for a post-condition test, we may use the do-while loop.

Keeping this in mind, half of our problem would be solved.

If you are a good programmer, you would prefer to use for loop as it is better than any other loop.

9. Summary

From this tutorial, we inferred that iteration plays a major role when it comes to programming. Programming without the concepts of iteration is like reading a language without the knowledge of grammar.

We discussed by shedding light on what looping actually is, its need, classification of the types of loops in C and C++, various control statements and the choice of looping.

Don’t forget to check Stack and Queues in C

Comments and Suggestions are welcomed in the comment section!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.