Loops

Loops are used when we need to execute one or more statements repeatedly within the same scope. There are three types of loops: while, for, and do-while loops, which we’ll cover in this lesson. Each type of loop has its own syntax and use cases, and understanding how to use loops effectively can help simplify and streamline our code.

The while loop

A while loop is often preferred when the number of loop iterations is unknown in advance, and the loop continues until a certain condition is met. The advantage of a while loop is that it allows for greater flexibility in controlling the termination of the loop based on the condition that is evaluated at runtime.

The body of the while loop can be a single statement or a block of statements enclosed in curly braces. If we want to execute more than one statement in the body, we must enclose them in a block statement. Here’s the general syntax.

while(condition)
    //single_statement; 


while(condition)
{
     //chunck of statements
}

Example: Digit summation

Let’s write a program that calculates the sum of the digits of the given positive number and prints it.

Press + to interact
#include <iostream>
using namespace std;
int main()
{
// Example of a while loop that calculates the sum of digits of a number
int n;
cin >> n;
if(n>=0)
{
int store = n;
int sum = 0;
while (n > 0)
{
sum += n % 10;
n /= 10;
}
n = store; // this instruction is added because n has zero at the end of the loop.
cout << "Sum of digits of " << n << " is: " << sum << endl;
}
else
{
cout << n << " is a -ve number.";
}
return 0;
}

Enter the input below

Tip: Write a positive number in the input (such as 12,564) and press the "Run" button. If you enter a negative number (such as -512), it won't compute an answer.

In the above example, the while loop calculates the sum of a number's digits entered by the user. The loop continues until the number n becomes zero, which means that we have processed all the number's digits. Inside the loop, we extract the last digit of n using the modulus operator %, add it to the sum, and then remove the last digit from n by assigning n to the quotient by 10. This process is repeated until n becomes zero, at which point the loop terminates, and we output the final result.

This example demonstrates how the while loop can be used to repeatedly perform a task until a certain condition is met without requiring a predetermined number of iterations.

Problem: Performing prime factorization

Assume we’re given a number n of the type int. Let’s find the prime factors of n.

Two possible solutions to the above problem are provided in the following tabs.

  • The first solution is using the single-loop approach to solve the problem.

  • The second solution is using the nested-loop approach to solve the problem.

#include <iostream>
using namespace std;
int main()
{
int n = 70;
cin>>n;
if(n>1)
{
int div = 2;
while(n != 1)
{
if(n % div == 0)
{
cout<< div; // prints the factors
n = n / div; // updating the number
if(n != 1)
cout<< " X ";
}
else
div++;
}
}
else
{
cout << n << " should be a +ve integer!";
}
return 0;
}

Enter the input below

Finding the prime factors using the single loop

In the Single Loop.cpp tab, the program utilizes the while loop to find the prime factors of a given number n by dividing it by its potential factors starting from 2. If n is divisible by a div factor, it is printed to the console and n is updated by dividing it by div. If n is not divisible by div, div is incremented and checked again. This continues until n is equal to 1, indicating that all the prime factors have been found. The program outputs the prime factorization of the original number by printing the factors separated by 'X'. For instance, if n is 70, the output would be 2 X 5 X 7 representing the prime factorization of 70.

In the Nested Loop.cpp tab, the program solves a similar problem as the Single Loop.cpp tab by using a nested loop, in which we initialize two variables: n is the number to be factorized, and div is the starting divisor. The outer while loop runs until n becomes equal to 1, which means that we have finished factorizing the number. The inner while loop divides n by div as long as div is a factor of n, and prints it to the console. We then update n by dividing it by div. The if statement checks if n is not equal to 1, in which case we print a multiplication symbol ('X') to separate the factors. After finishing the inner while loop, we increment the div by 1 to check the next potential factor. This process repeats until n becomes equal to 1, at which point we have successfully factorized the number.

The do-while loop

A do-while loop is similar to a while loop, but it executes the body of the loop at least once, regardless of whether the condition is true or false. The loop first executes the body of the loop and then checks the condition. If the condition is true, the loop repeats. If the condition is false, the loop terminates, and the program continues with the next statement after the loop.

The syntax of the do-while loop is as follows:

do
{
// chunk of instructions
}
while(condition);
Syntax of the do-while loop

Example: Taking valid input

Write a program that takes valid input from the user based on the following criteria:

  • The program should ask the user to enter a positive integer less than or equal to 10.

  • If the user enters an invalid number, the program should display an error message and ask the user to enter a valid number.

  • The program should continue to ask for input until the user enters a valid number.

#include <iostream>
using namespace std;

int main() 
{
    // Example of a do-while loop that validates user input
    int num;
    do 
    {
        cout << "Enter a positive integer less than or equal to 10: ";
        cin >> num;
        if (num <= 0 || num > 10) 
        {
            cout << "Invalid input. Please enter a valid number." << endl;
        }
    } 
    while (num <= 0 || num > 10);

    cout << "You entered a valid number: " << num << endl;

    return 0;
}
Validating input using the do-while loop
  • Line 7: The program starts by declaring an integer variable called num. The do-while loop is then used to take input from the user and validate it. The loop continues until the user enters a valid number.

  • Lines 8–17: Inside the do-while loop, the program first prompts the user to enter a positive integer less than or equal to 10. The input is then stored in the variable num using the cin statement.

  • Lines 12–15: Next, an if statement is used to check if the input is valid. The program displays an error message if the input is less than or equal to 0 or greater than 10. The loop continues as long as the input is invalid. If the input is valid, the loop terminates, and the program displays a message indicating that a valid number was entered along with the value of the input.

Let’s solve another nontrivial problem using do-while.

Problem: Decimal to binary conversion

We are given a number in decimal form. Our task is to convert it into its equivalent binary representation using a repeated division-by-two algorithm. The given illustration describes the algorithm.

Let’s look at the code for decimal to binary conversion using the do-while loop.

Press + to interact
#include <iostream>
using namespace std;
int main()
{
int decimal = 23;
int binary = 0;
int remainder = 0;
int product = 1;
do
{
remainder = decimal % 2;
binary = binary + (remainder * product);
decimal = decimal / 2;
product *= 10;
}
while (decimal != 0);
cout << binary ;
return 0;
}
  • Lines 6–9: We initialize four integer variables and set their values: decimal to 23 (the decimal value to be converted), binary to 0 (the binary value to be computed), remainder to 0 (the remainder of the division operation), and product to 1 (the multiplier used to construct the binary representation).

  • Lines 10–17: Inside the do-while loop, we compute the remainder of decimal divided by 2 using the modulo operator % and store it in the remainder variable. The program updates the binary variable by adding the product of remainder and product to it, where product keeps track of the position of the binary digit by multiplying it by 10 in each iteration of the loop. The loop continues until decimal becomes 0. Once the loop finishes executing, the binary representation of decimal is stored in the binary variable.

  • Line 18: We print the binary representation to the console using the cout statement.

The for loop

This loop is defined by the keyword for followed by a list of instructions, including:

  • The initialization of a loop control variable on which the iterations of the loop are dependent. This will only execute at the start of the loop.

  • In the conditional statement, after evaluating the condition, the control will enter into the body of the loop and execute the statements present in the body.

  • The update statement will be executed after the complete execution of the body statements. This statement can contain any arithmetic change like increment/decrement or multiply/divide.

Note: The above three instructions in the for loop will be seperated by the semicolon(;). We can also define the loop control variable outside the loop and skip the increment statement.

Press + to interact
for(initialization; condition; update)
{
// chunk of statements
}

Let’s solve a problem to understand this better.

Example: Factorial, permutation, and combination

Write a program that takes two numbers, nn and rr, as input and computes the following three quantities:

  1. n!n!

  2. r!r!

  3. (nr)!(n-r)!

Then, it should compute and print the number of permutations and combinations defined by nn and rr. Use the following formulae for these quantities:

Let’s look at the following code:

Press + to interact
#include <iostream>
using namespace std;
int main()
{
int n, r;
cin>>n>>r;
int nFactorial = 1;
for(int i = n; i > 0; i--)
{
nFactorial *= i;
}
int rFactorial = 1;
for(int i = r; i > 0; i--)
{
rFactorial *= i;
}
int n_rFactorial = 1;
for(int i = n-r; i > 0; i--)
{
n_rFactorial *= i;
}
cout<< "Permutation("<< n << ", "<<r<< ") = " <<nFactorial/n_rFactorial<<'\n';
cout<< "Combination("<< n << ", "<<r<< ") = " <<nFactorial/(n_rFactorial*rFactorial)<<'\n';
}

Enter the input below

Instruction: Add two different values in the above input prompt (such as 6 and 2) and click the “Run” button. The input values can be separated by a single space or written on a new line.

  • Lines 9–12: The program calculates the factorial of the given variable n using the for loop, and stores the result in the nFactorial variable.

  • Lines 15–18: The program calculates the factorial of the value r using the for loop, and stores the result in the rFactorial variable.

  • Lines 21–24: The program uses the for loop to calculate the factorial of the expression n-r and stores the result in the n_Factorial variable.

  • Lines 26–27: We compute and display the permutation and combination, respectively.

The break and continue statements

In terms of control structure, the break and continue statements are used to alter the normal flow of execution within a loop.

The break statement

The break statement is used to immediately terminate the loop and continue with the execution of the statement following the loop. This can be useful when a certain condition is met within the loop and further iterations are unnecessary.

Example: Printing Fibonacci numbers less than a limit

Let’s write a program that prints the Fibonacci numbers lesser than the limiting value TT (taken from the user).

We know that Fibonacci sequence numbers are 0, 1, 1, 2, 3, 5, ...

Finding the exact pattern of these numbers is not easy; all we know is that the next Fibonacci is the sum of the previous two Fibonacci numbers starting from 0 and 1.

For printing the sequence up to a limiting number, the problem is that we don’t know exactly how long the loop should proceed, which we’ll figure out during the next Fibonacci number computation. We’ll use the break statement to end the loop and print the sequence. Let’s look at the following implementation:

Press + to interact
#include <iostream>
using namespace std;
int main()
{
int T;
cin>>T; // Take the limiting sequence number as input
int prev=0, current = 1;
int next;
cout << "Fibonacci Sequence is: "<< prev << " " << current;
for(int i = 1; true; i++)
{
next = prev+current;
if(next >T)
{
break; // Terminate the loop when i is equal to 5
}
cout<< " "<< next;
prev = current;
current = next;
}
return 0;
}

Enter the input below

Tip: Run the above program with an input of 1000 (or any positive integer). We should see the program print the Fibonacci sequence up to the largest possible sequence value of the input we gave.

The continue statement

The continue statement is used to skip the remaining statements in the current iteration of the loop and continue with the next iteration. This can be useful when a certain condition is met within the loop and we want to skip the remaining statements for the current iteration.

Example: Summing the even Fibonacci numbers

Let’s extend the previous program so that after it prints the Fibonacci sequence, it should also print the sum of the even values.

The idea is that if there was no restriction of even values accumulation, we could have just added them normally. First, we’ll check whether the next generated sequence number is odd. If it is odd, we skip that value’s accumulation. Let’s look at the following implementation of the continue statement:

Press + to interact
#include <iostream>
using namespace std;
int main()
{
int T;
cin>>T; // Take input the limiting sequence number
int prev=0, current = 1;
int next;
int Sum=0; // Sum will accumulate all the "evens Fibonacci" numbers only
for(int i = 1; true; i++)
{
next = prev+current;
if(next >T)
{
break; // terminate loop when i is equal to 5
}
cout<< " "<< next;
prev = current;
current = next;
if(next%2==1)
continue;
Sum+=next; // Accumulating only those fibonacci number which are not prime
}
cout << "\n\nThe Sum of even Fibonacci values lesser than "
<<T<<" is: "<<Sum<<endl;
}

Enter the input below

Tip: Run the above code by giving an input of 1000 (or any integer); it should give "798" as the output, which is the sum of 2+8+34+144+610.2+8+34+144+610.