Skip to content

Loops - For & While

Python Examples

For Loop

# Basic for loop
for i in range(5):
    print(f"Iteration {i}")

# For loop with list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(f"Fruit: {fruit}")

# For loop with range (start, end, step)
for i in range(0, 10, 2):
    print(f"Even number: {i}")

# For loop with enumerate
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
    print(f"Color {index}: {color}")

While Loop

# Basic while loop
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1

# While loop with condition
user_input = ""
while user_input.lower() != "quit":
    user_input = input("Enter text (or 'quit' to exit): ")
    print(f"You entered: {user_input}")

# While loop with break
number = 0
while True:
    if number >= 5:
        break
    print(f"Number: {number}")
    number += 1

Loop Control

# Break statement
for i in range(10):
    if i == 5:
        break  # Exit loop
    print(i)

# Continue statement
for i in range(10):
    if i % 2 == 0:
        continue  # Skip even numbers
    print(f"Odd: {i}")

# Nested loops
for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

Java Examples

For Loop

// Basic for loop
for (int i = 0; i < 5; i++) {
    System.out.println("Iteration " + i);
}

// Enhanced for loop (for-each)
String[] fruits = {"apple", "banana", "orange"};
for (String fruit : fruits) {
    System.out.println("Fruit: " + fruit);
}

// For loop with array
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Number: " + numbers[i]);
}

While Loop

// Basic while loop
int count = 0;
while (count < 5) {
    System.out.println("Count: " + count);
    count++;
}

// While loop with condition
Scanner scanner = new Scanner(System.in);
String userInput = "";
while (!userInput.equals("quit")) {
    System.out.print("Enter text (or 'quit' to exit): ");
    userInput = scanner.nextLine();
    System.out.println("You entered: " + userInput);
}
scanner.close();

// Do-while loop (executes at least once)
int number;
do {
    System.out.print("Enter a positive number: ");
    number = scanner.nextInt();
} while (number <= 0);

Loop Control

// Break statement
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // Exit loop
    }
    System.out.println(i);
}

// Continue statement
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue; // Skip even numbers
    }
    System.out.println("Odd: " + i);
}

// Nested loops
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 2; j++) {
        System.out.println("i=" + i + ", j=" + j);
    }
}

C++ Examples

For Loop

#include <iostream>
using namespace std;

// Basic for loop
for (int i = 0; i < 5; i++) {
    cout << "Iteration " << i << endl;
}

// Range-based for loop (C++11)
int numbers[] = {10, 20, 30, 40, 50};
for (int num : numbers) {
    cout << "Number: " << num << endl;
}

// For loop with array
string fruits[] = {"apple", "banana", "orange"};
for (int i = 0; i < 3; i++) {
    cout << "Fruit: " << fruits[i] << endl;
}

While Loop

// Basic while loop
int count = 0;
while (count < 5) {
    cout << "Count: " << count << endl;
    count++;
}

// While loop with user input
string userInput;
while (userInput != "quit") {
    cout << "Enter text (or 'quit' to exit): ";
    cin >> userInput;
    cout << "You entered: " << userInput << endl;
}

🎯 When to Use Which Loop?

Scenario Best Loop Why
Known iterations for loop Clear start/end conditions
Iterating collections for-each loop Cleaner syntax
Unknown iterations while loop Condition-based
At least once execution do-while loop Guarantees one run
Searching/breaking while with break Flexible exit

📚 Learn Loop Theory →