C++ While Loop C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
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
}
// 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!