C++ While Loop C-PLUS-PLUS

C++ While Loop  

C++ While Loop

C++ While Loop

The while loop loops through a block of code as long as a specified condition is true:

Syntax

while (condition) {
  // code block to be executed
}

Let's take an example, the code in the loop will run, over and over again, as long as a variable (i) is less than 5.

Example

#include <iostream>
using namespace std;

int main() {
  int i = 0;
  while (i < 5) {
    cout << i << "\n";
    i++;
  }
  return 0;
}
 

Output:

0
1
2
3
4

Note: Do not forget to increase the variable i  used in the condition, otherwise, the loop will never end!

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries