Do-While Loop
A do-while loop in programming is an exit-controlled control flow structure that executes a block of code at least once and then repeatedly executes the block as long as a specified condition remains true. The distinctive feature of a do-while loop is that the condition is evaluated after the code block, ensuring that the block is executed at least once, even if the condition is initially false.
The basic syntax for a for loop includes a block of code followed by a condition which is checked after each iteration and if the condition evaluates to true, the next iteration takes place otherwise the loop gets terminated.
Below is the implementation of Do while Loop in Programming:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
return 0;
}
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 0;
do {
System.out.print(i + " ");
i++;
} while (i < 5);
}
}
# Python program to demonstrate a simple do-while loop
def main():
# Initialize the counter variable
i = 0
# Execute the loop at least once, and continue while the condition is true
while True:
# Print the current value of i
print(i, end=" ")
# Increment the counter
i += 1
# Check if the loop condition is no longer true
if i >= 5:
break
# Call the main function
main()
using System;
class Program
{
static void Main()
{
// Initialize the counter variable
int i = 0;
// Execute the loop at least once
do
{
// Print the current value of i
Console.Write($"{i} ");
// Increment the counter
i++;
} while (i < 5);
// Return 0 to indicate successful completion
Environment.Exit(0);
}
}
// Define the main function
function main() {
// Initialize the variable i
let i = 0;
// Start a do-while loop
do {
// Print the current value of i
process.stdout.write(i + " ");
// Increment i
i++;
} while (i < 5); // Continue looping while i is less than 5
}
// 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