Site icon DataFlair

Loops in C and C++ [with interactive quiz]

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.

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.

It’s just a nice way to see how much you know, or don’t know. Test your learnings with a fascinating quiz at the end.

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.

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.

This is a diagrammatic representation of 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:

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:

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:

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:

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

Output

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-

Output-

Elucidation

Let us understand every statement step by step:

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

Output

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:

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:

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

Output

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-

Output-

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.

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:

Here is a diagrammatic representation of the for loop:

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

Output

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-

Output-

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:

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

Output

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- 

Output – 

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:

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:

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

Output

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-

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:

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

Output

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- 

Output-

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:

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

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- 

Output-

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

Output

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-

Output-

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.

Quiz on Loops in C and C++

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    #include
    using namespace std;
    int main()
    {
    int count=3;
    while(count)
    {
    cout<<"count="<<count<<endl;
    –count;
    }
    return 0;
    }

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    int main()
    {
    int count=3;
    for(;)
    {
    cout<<"count="<<count<<endl;
    –count;
    }
    return 0;
    }

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    #include
    using namespace std;
    int main()
    {
    int i=2;
    do
    {
    cout<0);
    return 0;
    }

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    #include
    using namespace std;
    int main()
    {
    int i=3;
    do
    {
    cout<0)
    –i;
    else
    break;
    }
    }
    while(i>0);
    return 0;
    }

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    #include
    using namespace std;
    int main()
    {
    for(int n=5, m=7; n>0; n–,–m)
    {
    if(m==n)
    cout<<"for loop";
    m–;
    }
    }

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    #include
    using namespace std;
    int main()
    {
    for(int n=1; n<=3; n++)
    {
    for(int m=1; m<=n; m++)
    {
    cout<<"*";
    }
    cout<<endl;
    }
    }

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    #include
    using namespace std;
    int main()
    {
    for(int n=1; n=n-1; m–)
    {
    cout<<" ";
    }
    for(int k=1; k<=n; k++)
    {
    cout<<"* ";
    }
    cout<<endl;
    }
    return 0;
    }

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    #include
    using namespace std;
    int main()
    {
    int a[]= {1,2,3};
    for(int n: a)
    {
    cout<<n;
    }
    }

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    #include
    #include
    using namespace std;
    int main()
    {
    string s=”Delhi”;
    for(auto n: s)
    {
    cout<<n;
    }
    }

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    #include
    using namespace std;
    int main()
    {
    int n[]={1,2,3};
    while(n[0]==1)
    {
    cout<<&n;
    n[0]–;
    }
    }

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    What loop shall be used if the code needs to be executed at least once?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    Which loop shall be used when loop termination condition is known but the number of iterations are not known?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

    Select an Exit controlled loop from the below options:

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    What header file inclusion is required to use “for_each” loop in the program

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    Which among the following is an entry controlled loop?

    Correct
    Incorrect

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.

Exit mobile version