While loop
A while loop is a control flow statement that allows a block of code to be repeatedly executed as long as a specified condition is true. It consists of a condition and a block of code. The condition is checked before each iteration, and if it evaluates to true, the code block is executed. The loop continues until the condition becomes false.
the examples
C++
#include <iostream>
int main() {
int i = 1;
while (i <= 5) {
std::cout << i << " ";
i++;
}
return 0;
}
Output
1 2 3 4 5
n this example, the while loop executes as long as the variable i
is less than or equal to 5. It prints the value of i
and increments it by 1 in each iteration.
Python
i = 1
while i <= 5:
print(i, end=' ')
i += 1
Output
1 2 3 4 5
Java
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.print(i + " ");
i++;
}
}
}
Output
1 2 3 4 5
JavaScript
let i = 1;
while (i <= 5) {
console.log(i + ' ');
i++;
}
Output
1
2
3
4
5