Website For Developers

While Loop in C++



Loops are the iterative structure that means they repeats a statement or a set of statements for a several times.
There are three types of loops in C++:
1) for loop
2) while loop
3) do while loop


while loop

• while loop in C++ are used when the number of iterations (repetition) are not fixed.
• while loop body or statements are executed only if the given conditions are true.
• while loop is the simplest loops of C++.
• while loop in C++ executes the statements until the condition remain true either it executes only one statements or many.


Syntax

while (condition) {
//Statements in while loop
}


Example of while loop in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  int counter = 1;
  while(counter<=5) {
    cout<< counter<< endl;
    counter++;
  }
  getch();
  return 0;
}

Output

1
2
3
4
5


C++ program to display the square roots of the first 10 odd positive integers

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  int i = 0;
  while(i<20) {
    if (i%2 != 0) {
      cout<<"Square of "<< i<< cout<<" is: "<< i*i<< endl;
    }
    i++;
  }
  getch();
  return 0;
}

Output

Square of 1 is: 1
Square of 3 is: 9
Square of 5 is: 25
Square of 7 is: 49
Square of 9 is: 81
Square of 11 is: 121
Square of 13 is: 169
Square of 15 is: 225
Square of 17 is: 289
Square of 19 is: 361


Keep in mind there should be an end point of loop
otherwise it goes to infinite loop.
Example of infinite loop in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  int x = 0;
  while(x<5) {
    cout<< "Infinite Loop........"<< endl;
  }
  getch();
  return 0;
}

Output

Infinite Loop........
Infinite Loop........
Infinite Loop........
Infinite Loop........
Infinite Loop........
Infinite Loop........
Infinite Loop........
Infinite Loop........
Infinite Loop........
.
.
.
.
.