While Loop
A while loop in programming is an entry-controlled control flow structure that repeatedly executes a block of code as long as a specified condition is true. The loop continues to iterate while the condition remains true, and it terminates once the condition evaluates to false.
The basic syntax for a for loop often includes a condition which is checked before each iteration and if the condition evaluates to true, the loop body containing the code gets executed otherwise the loop gets terminated.
Below is the implementation of While Loop in Programming:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}
return 0;
}
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 0;
while (i < 5) {
System.out.print(i + " ");
i++;
}
}
}
# code
i = 0
while i < 5:
print(i, end=" ")
i += 1
using System;
class Program
{
static void Main()
{
// Initialize the counter variable
int i = 0;
// Execute the loop while the condition is true
while (i < 5)
{
// Print the current value of i
Console.Write($"{i} ");
// Increment the counter
i++;
}
// Return 0 to indicate successful completion
Environment.Exit(0);
}
}
function main() {
let i = 0;
while (i < 5) {
process.stdout.write(i + " ");
i++;
}
}
// Call the main function
main();
Output
0 1 2 3 4
Loops in Programming
Loops or Iteration Statements in Programming are helpful when we need a specific task in repetition. They’re essential as they reduce hours of work to seconds. In this article, we will explore the basics of loops, with the different types and best practices.
Table of Content
- What are Loops in Programming?
- Types of Loops in Programming
- For loop
- While Loop
- Do-While Loop
- Nested Loops
- For Loop vs While Loop vs Do-While Loop in Programming
- Common mistakes to avoid in Programming