C++

C++ Example Of A While Loop – Q&A

In the previous tutorial, we covered the for loop. We shall talk about the while loop in this lesson. As was previously mentioned, loops are used to continually run a block of program statements until the specified loop condition returns false.

Syntax of while loop

while(condition)
{
   statement(s);
}

How does while Loop operate?

In a while loop, the condition is first tested to see if it is true, and if it is, the statements inside the loop are then repeatedly executed until the condition is false. When the condition returns false, the control exits the while loop and moves on to the following statement in the program.

When utilizing a while loop, it’s vital to keep in mind that we must use an increment or decrement statement inside the loop to modify the value of the variable each time, causing the condition to eventually return false. In this manner, the while loop can be terminated; otherwise, it would continue running forever.

C++ while loop example

#include <iostream>
using namespace std;
int main(){
   int i=1;
   /* The loop would continue to print
    * the value of i until the given condition
    * i<=6 returns false.
    */
   while(i<=6){
      cout<<"Value of variable i is: "<<i<<endl; i++;
   }
}

Output:

Value of variable i is: 1
Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6

Endless while loop

When the condition is set up so that it never returns false, the while loop becomes endless and continues continuously. This is referred to as an infinite while loop.
An illustration of an infinite while loop: Since I’m decreasing the value of I which is 1, the condition i=6 would never return false in this loop.

#include <iostream>
using namespace std;
int main(){
   int i=1; while(i<=6) {
      cout<<"Value of variable i is: "<<i<<endl; i--;
   }
}

Example: Using a while loop to display the elements of an array.

#include <iostream>
using namespace std;
int main(){
   int arr[]={21,87,15,99, -12};
   /* The array index starts with 0, the
    * first element of array has 0 index
    * and represented as arr[0]
    */
   int i=0;
   while(i<5){
      cout<<arr[i]<<endl;
      i++;
   }
}

Output:

21
87
15
99
-12

Related Articles

Leave a Reply

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

Back to top button