While loop in C++
C++ while loop syntax is similar to C and Java. The loop continues executing as long as the condition evaluates to true
.
#include <iostream>
using namespace std;
int main() {
int count = 0;
while (count < 5) {
cout << count << std;
count++;
}
return 0;
}
Output
0 1 2 3 4
Explanation: This C++ code initializes an integer variable count
with the value 0
. The while loop iterates as long as count
is less than 5
. Inside the loop, the current value of count
is printed to the console using std::cout
, and then count
is incremented by 1
using the ++
operator.
Working: The loop starts with count
equal to 0
. It prints the value of count
(which is 0
) to the console and then increments count
to 1
. This process repeats until count
reaches 5
, at which point the loop terminates.
While loop in Programming
While loop is a fundamental control flow structure in programming, enabling the execution of a block of code repeatedly as long as a specified condition remains true. While loop works by repeatedly executing a block of code as long as a specified condition remains true. It evaluates the condition before each iteration, executes the code block if the condition is true, and terminates when the condition becomes false. This mechanism allows for flexible iteration based on changing conditions within a program.
In this post, we will explore the while loop, its syntax, functionality, and applications across various programming domains.
Table of Content
- What is While Loop?
- While Loop Syntax
- How does While Loop work?
- While Loop in Different Programming Languages
- While loop in Python
- While loop in JavaScript
- While loop in Java
- While loop in C
- While loop in C++
- While loop in PHP
- While loop in C#
- Use Cases where While Loop is Used
- While Loop vs Other Loops