Table of Contents
In this lesson, you will learn about C++ while loop and its usage, declaration, and benefits. We will provide examples to understand the topic better.
C++ while Loop explained
A while loop executes a block of code as long as a specific condition is met. The loop evaluates the condition first and executes the code if the condition is true. The loop exists once the condition is evaluated to be false.
More like this:
Syntax of while Loop in C++
while (condition) { // code block to be executed if condition is true }
Flowchart
Example I of while Loop in C++
#include <iostream> using namespace std; int main() { int num = 0; while (num < 5) { cout << num << endl; num++; } return 0; }
Output
0
1
2
3
4
Example II of while Loop in C++
#include <iostream> using namespace std; int main() { // declare an array string languages[4] = { "C++", "C", "Python", "Java" }; // get the size of the array int arrSize = sizeof(languages) / sizeof(languages[0]); int i = 0; // loop through array element while (i < arrSize) { cout << languages[i] << "\n"; i++; } }
Output
C++
C
Python
Java
Points to remember
- ‘while’ loop evaluates the condition before it executes the loop body.
- ‘while’ loop body starts and ends with curly brackets.
- ‘while’ loop condition cannot always be true, or an infinite loop will occur.