Loops in C++

Loops in C++ Language with Examples

Hey Guys, welcome back to C++ basics, here in this article, I am going to discuss Loops in C++. Please read our last article, where we discussed conditional statements and its relations to logical and relational operators. In this article, we are going to discuss one of the core concepts of any programming called Loops. If you are new to programming then please keep in mind that if you understand the working of loop correctly you could solve most of the problems in the real world. So keep a keen interest in this article while reading and try to solve the assignment articles on your own. If you find any difficulty, then only look at our assignment solution section.

Topics Discussed in this article:
  1. What is Loops/iterative statements/repetitive statements?
  2. Why Loops are used in programming and its advantages?
  3. Different types of Loops and use case scenarios for each type of loops.
  4. Assignments
What are the Loops?

Loop is nothing but repeating some tasks for some amount of time until the condition is true. There are two types of loops

  1. Counter loops
  2. Conditional loops

Before explaining, what are the counter and conditional loops let’s make you understand where we see loops in reality with real-time examples.

Loops exist in our daily routine.

Example: Every day I woke up at 6 ->go to jogging ->come home->take a bath->had breakfast->go to college/office->work/learn->come back at 6-> watch tv/mobile->had dinner ->go to sleep this routine is repeated every day without change and this we call it has loops in programming.

Here even when you wake up tomorrow you do the same following thing and this continues until your alive so here condition to break the loop is you have to die.

Now let us explain what is the counter loop and conditional Loop.

Counter loops are loop, which executes a specific set of instructions for a certain number of times. Example: Token system followed in hospitals where the whole intension could be getting the headcount of patients.

Conditional Loops is executing a specific task until the condition is true. Example: Attend the online classes until the covid-19 situation comes to control.

Why Loops?

The whole intention of using loops in programming is to make the developer job easy and make the code look clean and efficient. The developer goes for loops whenever he wants to execute some instructions a certain number of times. To give you a better understanding of the importance of loops in programming let us write a code without loops and with loops.

Program to print numbers from 1 to 10 without loops.

Till now what we learned using those concepts If I write a program to print 1 to 10 it looks something like this.

#include <iostream>
using namespace std;
int n = 0; 
 
int main() { 
   cout<<++n<<endl;
     
    if (n >= 10) { 
        exit(0); 
    }
    cout<<++n<<endl;
     
    if (n >= 10) { 
        exit(0); 
    }
    cout<<++n<<endl;
     
    if (n >= 10) { 
        exit(0); 
    }
    cout<<++n<<endl;
     
    if (n >= 10) { 
        exit(0); 
    }
    cout<<++n<<endl;
     
    if (n >= 10) { 
        exit(0); 
    }
    cout<<++n<<endl;
     
    if (n >= 10) { 
        exit(0); 
    }
    cout<<++n<<endl;
     
    if (n >= 10) { 
        exit(0); 
    }
    cout<<++n<<endl;
     
    if (n >= 10) { 
        exit(0); 
    }
    cout<<++n<<endl;
     
    if (n >= 10) { 
        exit(0); 
    }
    cout<<++n<<endl;
     
    if (n >= 10) { 
        exit(0); 
    }
    
    return 1; 
}

Output:

Program to print numbers from 1 to 10 without loops

Note: Even though we are able to print the from 1 to 10 code doesn’t look good same instruction is written multiple times also what is if want to print from 1 to 1000? Or from 1 to 100000? So without loops from not even looks understandable and efficient.

Program to print 1 to n with loops
#include <iostream>
using namespace std;
int main() { 
    for(int n=1;n<=10;++n)
    {
  	cout<<n<<endl;
    }
    return 1;
}

Output:

Program to print 1 to n with loops

Note: The above for loop is an example of a counter loop where the loop runs for a specific number of times. Syntax and other things will be discussed soon.

The above code looks simple and readable. In addition, if I want to print from 1 to 1000 just, I need to change n<=10 to n<=1000 that’s it. So, code can be easily maintainable.

The disadvantage of using loops:

Program with loops takes more execution time to compare to the program without loops. In the above output screenshot, you could see program without loops takes 2.054 seconds to print the value from 1 to 10 whereas a program with loops takes 5.276 to print from 1 to 10, and execution time is almost double when compared to a program without loops.

Different types of Loops in C++:

The different types of loops are as follows.

  1. For loop
  2. For-each loop
  3. While loop
  4. Do while loop
For Loop in C++:

The for loop is a repetitive, structure that allows the execution of instructions specific amount of time. It has four stages.

  1. Loop initialization
  2. Condition evaluation
  3. Execution of instruction
  4. Increment/Decrement
Syntax to use for loop in C++:

for (initialization; condition; increment/decrement)
{
// C++ instructions
}

Explanation:

Loop Initialization: Loop initialization happens only once while executing the for loop for the first time, which means that the initialization part of for loop only executes once.

Condition Evaluation: Conditions in for loop are executed for each iteration and if the condition is true it executes C++ instruction if false it comes out of the loop.

Execution of Instruction: After the condition is executed, control comes to the loop body i.e. C++ instructions and it gets executed.

Increment/Decrement: After executing the C++ instructions in for loop increment/decrement part of for loop executed and again it will go to the condition evaluation stage.

Use-case scenarios of for loop:

The for loop is used when we know exactly how many times we have to repeat. So, for loop is used for counting purpose usually. And for loop is closely associated with the advanced concept of C++ called STL. For loop is used in arrays as well which will be discussed in our next article.

Example:

Since I haven’t introduced you to arrays yet so I will take an example of a simple thing. Let’s say I want to print a multiplication table. The program takes, which multipliable table the user, wants to print as an input.

#include <iostream>
using namespace std;
int main() { 
  int tables;
  cout<<"enter the table which you want to print"<<endl;
  cin>>tables;
  for(int i=1;i<=10;i++)
  {
  	 cout<<tables<<" "<< "X"<<" "<<i<<" "<<"="<<" "<<tables*i<<endl;
  }
    return 0;
}

Output:

For Loop in C++

Here to print table, I need to run the loop 10 times. Let us have a keen look at the working of the for loop once again as things will get complicated if you do not get it clearly.

See in the above example initialization happens once so initially i=1 and I <10 conditions will be evaluated and condition returns true as 1<10 so it enters the loop print 8X1=8 later i got incremented now I becomes i=2 again condition will be evaluated 2<10 true enter the condition 8 X 2=16 so on. until l become i=11 loop executes.

While Loop in C++:

It is popularly known as pre-tested loops. Here before entering into C++ statements condition will be tested and then only control will go to the block of statements in the while loop. It is an example of a conditional loop whereas for loop is an example of a counter loop.

While is used when you do not know how many times you have to repeat, so repeat WHILE condition is true. for is used when you know FOR how many times you have to repeat. In while loop Block of statements are repeatedly executed as long as the condition is true

General Syntax:

While(condition)
{
C++ statements
}

How does it work?

While loop checks the condition written inside ‘( )’ is true or not. If the condition is true, then statements written in the body of the while loop i.e., inside the braces { } are executed again condition is checked the process repeats until the condition is false.

Use case scenarios of while loop:

Program to reverse a number.

Here I want to reverse the number 1024. The reversal number is 4201. How we can achieve this reverse of a number using a while loop?

Here is the Logic.

Here is the Logic.
Here n=1024 to extract the last digit of the number to the first place we need to perform modulo of number 1024 by 10, which gives remainder 4.
Remainder =n%10 means 1024%10 gives 4.
Reverse number= Reverse number *10+remainder //here reverse number the first digit becomes 4
N=n/10; now divide the number 1024 now after division N=102

Repeat the same step
Remainder=N%10 which gives 2
Reverse number=Reverse number*10+remainder (4*10+2) means 42 in this step two number was reversed.
N=N/10 now divide the number 102 by 10 now after division N=10;

Repeat the same step
Remainder=N%10 remainder is zero
Reverse number= Reverse number *10+remainder (42*10+0) this step given reverse number has 420
N=N/10 now N becomes 1 after division
Note already three digits got reverses successfully

Repeat the same step
Remainder =N%10 1%10 means remainder 1
Reverse number=Reversenumber*10+ Remainder (420*10+1) 4201 successfully reversed
N=N/10 1/10 is 0;

So, to exit the condition N should not be equal to zero. This is the best use case of while loop as we don’t know how many times, I need to execute the loop however I know till what condition I need to execute the loop.

#include <iostream>
using namespace std;
int main() { 
  int N;
  cout<<"enter the number which you would like to reverse"<<endl;
  cin>>N;
  int remainder=0, reversenumber=0;
  while(N!=0)
  {
      remainder=N%10;
      reversenumber=reversenumber*10+remainder;
      N/=10;
  }
 cout<<"reversenumber is\t"<<reversenumber<<endl;
 return 0;
}

Output:

While Loop in C++

Do-while loop in C++:

Popularly known as a post-tested loop. The behavior is the same, as while loop with only difference loop is executed first then it will check the condition. This behavior of checking the condition last ensures the loop gets executed at least once. This is also an example of a conditional loop and the condition is tested after executing the loop body.

General Syntax:

do
{
C++ statements;
}while(condition);

Use case scenario of the do-while loop:

The do-while loop is used in menu-driven programs. To better explain this, consider the program below.

#include <iostream>
using namespace std;
int main() { 
  char choice;
  int menuoption;
  int a,b;
  do {
  	cout<<"press 1 to addition 2 to subtraction 3. mutiplication 4. division"<<endl;
  	cin>>menuoption;
  	switch(menuoption)
  	{
  	        case 1: 
                 cout<<"enter the value of two numbers"<<endl;
        cin>>a>>b;
        cout<<"sum is:"<<"  "<<a+b<<endl;
        break;
         case 2:
                 cout<<"enter the value of two numbers"<<endl;
        cin>>a>>b;
        cout<<"difference is:"<<"  "<<a-b<<endl;
        break;
     case 3:
                 cout<<"enter the value of two numbers"<<endl;
        cin>>a>>b;
        cout<<"multipy is:"<<"  "<<a*b<<endl;
        break;
     case 4: 
                 cout<<"enter the value of two numbers"<<endl;
        cin>>a>>b;
        cout<<"division is:"<<"  "<<a/b<<endl;
        break;
      default: 
                 cout<<"invalid choice"<<endl;
   }
      cout<<"do you want to continue seleting the menu option please enter y for yes"<<endl;
   cin>>choice;	  
    }while (choice=='y');
    return 0;
}

Output:

Do-while loop in C++

Note: For all the menu-driven programming it is better to go with do-while loops so that the menu condition will be executed at least once.

Assignments of C++ Loops:

1.Program to find the sum of first N natural numbers.
Testcase: input: N=20
Expected out: N=210
Note: Also select which loop is better to find the first N natural numbers.

2.Program to find factorial of a number.
Testcase: Input N=5;
Output=120;

3.Program to find a palindrome or not.
Testcase: input:1212121
Output: palindrome

4.Program to find GCD between two numbers
Testcase: input:81 153
Output:9

5.Program to perform banking operations.
option1: check bank balance
option2: deposit amount
option3: withdraw the amount
Note: The user is allowed to select any option at any time during the banking operation.

Testcase: input: 1 ,y,2,y,3,y,2,N
Output: balance amount is:
Deposit amount is:
Withdraw amount is:
Deposit amount is:

Leave a Reply

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