# Loops in Java – For Loop and While Loop (Complete Guide with Examples)

Loops in Java are used to execute a block of code repeatedly until a condition becomes false. Loops help reduce code repetition and make programs more efficient.

In Java, the most commonly used loops are:

*   for loop
    
*   while loop
    
*   do-while loop (we will briefly cover this too)
    

* * *

# 1\. for Loop in Java

The `for` loop is used when we know **how many times** we want to run the loop.

## Syntax:

```java
for (initialization; condition; update) {
    // code to execute
}
```

## How for loop works:

1.  Initialization → Runs only once
    
2.  Condition → Checked before every iteration
    
3.  Code inside loop executes
    
4.  Update → Increases/decreases variable
    
5.  Loop repeats until condition becomes false
    

* * *

## Example 1: Print numbers from 1 to 5

```java
public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}
```

**Output:**

```plaintext
1
2
3
4
5
```

* * *

## Example 2: Sum of first 5 numbers

```java
public class SumExample {
    public static void main(String[] args) {
        int sum = 0;

        for (int i = 1; i <= 5; i++) {
            sum = sum + i;
        }

        System.out.println("Sum = " + sum);
    }
}
```

* * *

## Example 3: Reverse loop

```java
for (int i = 5; i >= 1; i--) {
    System.out.println(i);
}
```

* * *

# 2\. while Loop in Java

The `while` loop is used when we **do not know how many times** the loop will run. It runs until the condition becomes false.

## Syntax:

```java
while (condition) {
    // code
}
```

## Example 1: Print numbers from 1 to 5

```java
public class WhileExample {
    public static void main(String[] args) {
        int i = 1;

        while (i <= 5) {
            System.out.println(i);
            i++;
        }
    }
}
```

* * *

## Example 2: Sum of numbers until user enters 0

```java
import java.util.Scanner;

public class WhileSumExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int sum = 0;
        int num = 1;

        while (num != 0) {
            System.out.print("Enter number: ");
            num = sc.nextInt();
            sum += num;
        }

        System.out.println("Total Sum = " + sum);
    }
}
```

* * *

# 3\. do-while Loop (Important)

This loop executes **at least once**, even if the condition is false.

## Syntax:

```java
do {
    // code
} while (condition);
```

## Example:

```java
public class DoWhileExample {
    public static void main(String[] args) {
        int i = 1;

        do {
            System.out.println(i);
            i++;
        } while (i <= 5);
    }
}
```

* * *

# for vs while Loop Difference

| for loop | while loop |
| --- | --- |
| Used when number of iterations is known | Used when number of iterations is unknown |
| Initialization, condition, update in one line | Initialization outside |
| Mostly used for arrays, fixed loops | Mostly used for user input |
| Syntax shorter | Syntax longer |

* * *

# Real Life Example

## ATM Example using while loop

```java
import java.util.Scanner;

public class ATMExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int pin = 1234;
        int enteredPin;

        while (true) {
            System.out.print("Enter PIN: ");
            enteredPin = sc.nextInt();

            if (enteredPin == pin) {
                System.out.println("Login Successful");
                break;
            } else {
                System.out.println("Wrong PIN, try again");
            }
        }
    }
}
```

* * *

# Conclusion

| Loop | Use |
| --- | --- |
| for | When iterations are fixed |
| while | When condition-based loop |
| do-while | Runs at least once |

**Simple rule to remember:**

*   Use **for loop** → when you know the count
    
*   Use **while loop** → when you don't know the count
    
*   Use **do-while** → when code must run at least once
    

* * *

# Practice Questions

1.  Print table of a number
    
2.  Factorial of a number
    
3.  Reverse a number
    
4.  Count digits in a number
    
5.  Sum of digits
    
6.  Prime number check
    

Practice these using both **for loop** and **while loop**.

* * *
