While Loop in Programming
- The
while
loop is used when you don’t know in advance how many times you want to execute the block of code. It continues to execute as long as the specified condition is true. - It’s important to make sure that the condition eventually becomes false; otherwise, the loop will run indefinitely, resulting in an infinite loop.
Example:
#include <iostream>
using namespace std;
int main()
{
int count = 0;
while (count < 5) {
cout << count << "\n";
count += 1;
}
cout << endl;
return 0;
}
#include <stdio.h>
int main()
{
int count = 0;
while (count < 5) {
printf("%d\n", count);
count += 1;
}
return 0;
}
public class Main {
public static void main(String[] args) {
int count = 0;
// Example: While loop to print numbers from 0 to 4
while (count < 5) {
System.out.println(count);
count += 1;
}
System.out.println();
}
}
count = 0
while count < 5:
print(count)
count += 1
let count = 0;
while (count < 5) {
console.log(count);
count += 1;
}
console.log();
Output
0 1 2 3 4
This prints the numbers 0 through 4, similar to the for
loop example.
Difference between For Loop and While Loop in Programming
Both for
loops and while
loops are control flow structures in programming that allow you to repeatedly execute a block of code. However, they differ in their syntax and use cases. It is important for a beginner to know the key differences between both of them.
Contact Us