While Loop in C++

Hey guys,
Today we would be learning what a while loop is and how it works in C++.
So read this article…

What is a while loop?

A while loop is a keyword that creates a loop until the required condition is met. It first checks the condition and if it is valid, only then it will execute the code.

Syntax:
while (condition)
{
    //code
}

The most important part of this is understanding when to use a while loop and when to use a do-while loop and how they are different.

Syntax of Do-while:
do{
    //code
} while(condition);

Well, there are 3 notable differences:
1) While checks the condition and then executes the code whereas do-while first executes the code and then checks the condition.
2) There is a semicolon present at the end of do-while but no semicolon after a while.
3) Do-while executes 1 time more compared to while.

Example of while loop in C++ is given below:

while((i%3)!=0)
{
     cout<<i<<" ";
     i++;
}

Assuming i starts from 1,
Output would be

1 2

3 would not be present because 3%3 is 0 and hence the loop never executes.

Dry Run of the above example:

i     i%3!=0     Output     i++
1     True       1           2
2     True       1 2         3
3     False      DNE         DNE
Hence o/p= 1 2

Code Sample in C++:

Take a look at the following code:

#include <iostream>
using namespace std;
int main()
{
    cout<<"Enter a limit\n";
    int i;
    cin>>i;
    int lim = 1;
    while(lim<=i)
    {
        cout<<"* ";
        lim++;
    }
}

Let us take a look at it line by line.

  1. cout<<"Enter a limit\n"; 
    int i; 
    cin>>i;

    First, we are asking the user to enter a particular value i.e. the limit.
    We are creating variable i of type int and storing the inputted number in i.

  2. int lim = 1;

    Now we are defining our counter i.e. lim of type int which will iterate from 1 to the value of i

  3. while(lim<=i) 
    { 
        cout<<"* "; 
        lim++; 
    }

    Using the syntax, we are printing a star until the value of lim reaches i.
    Once it does cross the value of i, the loop would terminate and the program continues till the end.

Hence the output would be:

Enter a limit
5
* * * * *

For better understanding take a look at this dry run:

i     lim     while(lim<=i)     Output        lim++
5     1       True              *             2
5     2       True              * *           3
5     3       True              * * *         4
5     4       True              * * * *       5
5     5       True              * * * * *     6
5     6       False             DNE           DNE
Hence o/p = * * * * *

And that covers what a while loop is.
I hope you understood it and were able to execute it by yourself.
If you have any doubts, feel free to ask in the comments section below.

Also, read: How to Terminate a Loop in C++?

 

Leave a Reply

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