How to Use While Loops in C++

Loops in any programming language are simply the repetition of execution of sets of statements. There are number of loop types that we can use to introduce repetition. I have written an article on using for loops, and you can go through it by clicking this link (using for loops in C++). In this article, I will describe the use of while loops in C++. The functionality of while loops is almost similar to ‘for loops’, but there is a slight difference between syntax and the use of both of them. Following step by step guide will introduce you to while loops and their use in C++.

Instructions

  • 1

    “While loops” are used to execute a set of statements repeatedly depending on a single condition. That condition could be anything, a simple check on a value or any comparison. The syntax of “while loop” is very simple and is shown below.


    while (condition){


    //set of statements to execute if the condition is true.


    }


    You can see that the syntax of 'while loop' is very simple as compared to 'for loop'. In the following step I will demonstrate a simple example of using while loop.

  • 2

    The following simple example will update the value of an integer every time the loop is executed.


    #include


    using namespace std;


    int main()


    {


    int temp = 0;


    while ( temp < 20 ) {


    cout<< temp <


    temp =temp+1;


    }


    return 0;


    }


    The above loop will simply check value of temp variable and if the value is less than 20, it will print out the value and will increment the temp value by 1.


    This is all you need to start working with while loops.

Leave a Reply

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


− five = 2