📖 Loops Kya Hain?
Bina loop ke: Loop ke saath: print("Hello"); for(int i=0; i<5; i++) { print("Hello"); print("Hello"); print("Hello"); } print("Hello"); // sirf 4 lines mein same kaam! print("Hello");
Loop = Ek kaam baar baar karo jab tak condition true hai
for → Jab pata ho kitni baar chalana hai while → Jab condition pe depend karna ho do-while → Kam se kam EK baar zaroor chalana ho for-each → Array/Collection ke har element pe kaam
for LoopDeep Explanation — Memory Mein Kaise Kaam Karta Hai:
for (initialization ; condition ; update) {
↑ ↑ ↑
Step 1: ek baar Step 2: har Step 4: body ke
shuru mein iteration se baad update
pehle check
↓ ↓ ↑
TRUE → body ← Step 3: body
FALSE → exit execute
Execution Order:
1. initialization → sirf ek baar
2. condition check → true? → 3. body → 4. update → 2. again
→ false? → loop khatam
Teen Parts Optional Hain:
for(;;) // infinite loop - teeno skip for(;i<5;) // init aur update bahar for(int i=0;;i++) // condition nahi - infinite
public class ForLoop1 { public static void main(String[] args) { // Basic for loop - step by step trace System.out.println("Basic for loop:"); for (int i = 1; i <= 5; i++) { System.out.println("i = " + i); } // Step trace: // i=1: 1<=5 true → print 1 → i becomes 2 // i=2: 2<=5 true → print 2 → i becomes 3 // i=3: 3<=5 true → print 3 → i becomes 4 // i=4: 4<=5 true → print 4 → i becomes 5 // i=5: 5<=5 true → print 5 → i becomes 6 // i=6: 6<=5 false → STOP System.out.println("\nBackward loop:"); for (int i = 5; i >= 1; i--) { System.out.println("i = " + i); } System.out.println("\nStep of 2:"); for (int i = 0; i <= 10; i += 2) { System.out.print(i + " "); } } }
i=1 se shuru, i<=5 condition, i++ har baar. Jab i=6 hota hai condition false hoti hai aur loop khatam. Backward mein i-- use karo.public class ForLoop2 { public static void main(String[] args) { // Sum of numbers 1 to 100 int sum = 0; for (int i = 1; i <= 100; i++) { sum += i; // sum = sum + i } System.out.println("Sum 1 to 100 = " + sum); // 5050 // Multiplication table int num = 7; System.out.println("\nTable of " + num + ":"); for (int i = 1; i <= 10; i++) { System.out.println(num + " x " + i + " = " + (num * i)); } } }
public class ForLoop3 { public static void main(String[] args) { // Optional parts demonstration System.out.println("--- Init outside loop ---"); int i = 1; // initialization bahar for (; i <= 3; i++) { // init part empty System.out.println("i = " + i); } System.out.println("\n--- Update inside body ---"); for (int j = 1; j <= 3; ) { // update part empty System.out.println("j = " + j); j++; // update andar } System.out.println("\n--- Multiple init and update ---"); for (int a = 0, b = 10; a <= b; a++, b--) { System.out.println("a=" + a + " b=" + b); } } }
a=0,b=10 — dono ek saath badhte/ghatte hain.public class ForLoop4 { public static void main(String[] args) { // Factorial int n = 6; long factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } System.out.println(n + "! = " + factorial); // 720 // Prime check int num = 29; boolean isPrime = true; for (int i = 2; i <= num / 2; i++) { if (num % i == 0) { isPrime = false; break; } } System.out.println(num + " is prime: " + isPrime); // Fibonacci series System.out.println("\nFibonacci (10 terms):"); int a = 0, b = 1; for (int i = 1; i <= 10; i++) { System.out.print(a + " "); int temp = a + b; a = b; b = temp; } } }
public class ForLoop5 { public static void main(String[] args) { // Nested for loop - Star patterns System.out.println("Square Pattern:"); for (int i = 1; i <= 4; i++) { // rows for (int j = 1; j <= 4; j++) { // columns System.out.print("* "); } System.out.println(); // new line after each row } System.out.println("\nRight Triangle:"); for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { // j goes till i System.out.print("* "); } System.out.println(); } System.out.println("\nMultiplication Table:"); for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { System.out.printf("%4d", i * j); // formatted } System.out.println(); } } }
while LoopDeep Explanation:
while (condition) { // body // update zaroori warna infinite loop! }
Flow:
condition check → TRUE → body → update → condition check again
→ FALSE → loop skip/exit
Agar condition shuru mein hi FALSE hai:
→ Body ZERO times execute hogi!
→ while loop skipped!
Kab use karein:
✅ Jab pata nahi kitni baar chalana hai ✅ User input pe depend kare ✅ File end tak padhna ho ✅ Game loop - jab tak game over nahi
public class WhileLoop1 { public static void main(String[] args) { // Basic while loop int i = 1; while (i <= 5) { System.out.println("i = " + i); i++; // update zaroori! warna infinite loop } System.out.println("Loop ended, i = " + i); // i = 6 // Zero times execution - condition pehle hi false int x = 10; System.out.println("\nCondition false from start:"); while (x < 5) { // 10 < 5 = FALSE System.out.println("This will NEVER print!"); x++; } System.out.println("While body executed 0 times, x = " + x); } }
while condition pehle check karta hai. Agar shuru mein hi false hai toh body ek baar bhi nahi chalegi.public class WhileLoop2 { public static void main(String[] args) { // Digits of a number int num = 12345; System.out.println("Digits of " + num + ":"); while (num > 0) { int digit = num % 10; // last digit System.out.println("Digit: " + digit); num = num / 10; // remove last digit } // Sum of digits int number = 9876; int sumDigits = 0; int temp = number; while (temp > 0) { sumDigits += temp % 10; temp /= 10; } System.out.println("\nSum of digits of " + number + " = " + sumDigits); } }
num % 10 last digit nikalata hai, num / 10 last digit hatata hai. Yeh while loop ka classic use case hai jab iterations pehle se pata nahi.public class WhileLoop3 { public static void main(String[] args) { // Reverse a number int num = 12345; int reversed = 0; int original = num; while (num > 0) { int lastDigit = num % 10; reversed = reversed * 10 + lastDigit; num /= 10; } System.out.println("Original: " + original); System.out.println("Reversed: " + reversed); // Palindrome check int n = 121; int rev = 0, t = n; while (t > 0) { rev = rev * 10 + t % 10; t /= 10; } if (n == rev) System.out.println("\n" + n + " is Palindrome"); else System.out.println("\n" + n + " is NOT Palindrome"); // Power without Math.pow int base = 2, exp = 8; long result = 1; int e = exp; while (e > 0) { result *= base; e--; } System.out.println("\n" + base + "^" + exp + " = " + result); } }
public class WhileLoop4 { public static void main(String[] args) { // Collatz Conjecture - while ka perfect use // Rule: even → n/2, odd → 3n+1, 1 pe stop int n = 27; int steps = 0; System.out.print("Collatz: " + n); while (n != 1) { if (n % 2 == 0) n = n / 2; else n = 3 * n + 1; System.out.print(" → " + n); steps++; if (steps % 10 == 0) System.out.println(); // new line every 10 } System.out.println("\nTotal steps: " + steps); // GCD using while int a = 48, b = 18; int x = a, y = b; while (y != 0) { int r = x % y; x = y; y = r; } System.out.println("\nGCD of " + a + " and " + b + " = " + x); } }
do-while LoopDeep Explanation:
do { // body - PEHLE execute hoti hai } while (condition); ← semicolon ZAROORI! ↑ BAAD MEIN check
while vs do-while:
while: condition → body → condition → body...
do-while: body → condition → body → condition...
↑
MINIMUM EK BAAR body chalegi!
Kab use karein:
✅ Menu show karna (pehle dikhao, phir puchho continue karein?) ✅ User input validation (pehle lo, phir check karo) ✅ Game - pehle ek baar khelo, phir puchho dobara? ✅ OTP/Password - pehle enter karo, phir validate karo
public class DoWhile1 { public static void main(String[] args) { // Basic do-while int i = 1; do { System.out.println("i = " + i); i++; } while (i <= 5); System.out.println("After loop, i = " + i); // KEY DIFFERENCE - condition FALSE from start System.out.println("\n--- while (condition false) ---"); int x = 10; while (x < 5) { // FALSE - never enters System.out.println("while: " + x); } System.out.println("while ran 0 times"); System.out.println("\n--- do-while (condition false) ---"); int y = 10; do { System.out.println("do-while: " + y); // EK BAAR chalega! y++; } while (y < 5); // FALSE - but already ran once System.out.println("do-while ran 1 time minimum!"); } }
while → 0 times bhi ho sakta hai. do-while → MINIMUM 1 baar hamesha chalega!public class DoWhile2 { public static void main(String[] args) { // Menu system - perfect do-while use case // (Simulated without Scanner for online compiler) int[] userChoices = {1, 2, 3, 4}; // simulating user input int choiceIndex = 0; int choice; do { // Menu dikhao System.out.println("\n=== FOOD MENU ==="); System.out.println("1. Pizza - Rs.299"); System.out.println("2. Burger - Rs.149"); System.out.println("3. Pasta - Rs.199"); System.out.println("4. Exit"); // User ka choice (simulated) choice = userChoices[choiceIndex++]; System.out.println("Your choice: " + choice); switch (choice) { case 1: System.out.println("Pizza ordered!"); break; case 2: System.out.println("Burger ordered!"); break; case 3: System.out.println("Pasta ordered!"); break; case 4: System.out.println("Goodbye!"); break; default: System.out.println("Invalid choice!"); } } while (choice != 4); // jab tak exit nahi chuna } }
public class DoWhile3 { public static void main(String[] args) { // Password validation simulation String correctPassword = "java123"; String[] attempts = {"hello", "pass", "java123"}; // simulated int attemptIndex = 0; int maxAttempts = 3; int attemptsUsed = 0; boolean success = false; do { String entered = attempts[attemptIndex++]; attemptsUsed++; System.out.println("Attempt " + attemptsUsed + ": " + entered); if (entered.equals(correctPassword)) { success = true; System.out.println("Password correct! Login successful!"); } else { System.out.println("Wrong password! " + (maxAttempts - attemptsUsed) + " attempts left"); } } while (!success && attemptsUsed < maxAttempts); if (!success) { System.out.println("Account locked after " + attemptsUsed + " attempts!"); } } }
public class DoWhile4 { public static void main(String[] args) { // Number guessing game simulation int secretNumber = 42; int[] guesses = {10, 70, 42}; // simulated guesses int guessIndex = 0; int guess; int attempts = 0; System.out.println("=== Number Guessing Game ==="); System.out.println("Guess a number between 1-100"); do { guess = guesses[guessIndex++]; attempts++; System.out.println("\nGuess #" + attempts + ": " + guess); if (guess < secretNumber) System.out.println("Too LOW! Go higher"); else if (guess > secretNumber) System.out.println("Too HIGH! Go lower"); else System.out.println("CORRECT! You got it!"); } while (guess != secretNumber); System.out.println("Total attempts: " + attempts); } }
for-each LoopDeep Explanation:
for (dataType element : arrayOrCollection) { // element use karo }
Normal for vs for-each:
// Normal for: for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); // index se access } // for-each: for (int num : arr) { System.out.println(num); // directly element }
Important Rules:
✅ Array aur Collection traverse ke liye ✅ Read-only access - simple aur clean ❌ Element modify karna array ko affect NAHI karta ❌ Index access nahi milta ❌ Reverse traverse nahi kar sakte ❌ Skip nahi kar sakte (every element visit hoga)
public class ForEach1 { public static void main(String[] args) { // Basic for-each with array int[] numbers = {10, 20, 30, 40, 50}; System.out.println("Using for-each:"); for (int num : numbers) { System.out.println("num = " + num); } // String array String[] fruits = {"Apple", "Banana", "Mango", "Orange"}; System.out.println("\nFruits:"); for (String fruit : fruits) { System.out.println("→ " + fruit); } // Sum using for-each int sum = 0; for (int num : numbers) { sum += num; } System.out.println("\nSum = " + sum); } }
public class ForEach2 { public static void main(String[] args) { // IMPORTANT: for-each mein modify karna array affect NAHI karta! int[] arr = {1, 2, 3, 4, 5}; System.out.println("Before modification:"); for (int n : arr) { System.out.print(n + " "); } // array modify karne ki koshish for (int n : arr) { n = n * 10; // sirf local copy badla, array nahi! } System.out.println("\nAfter 'modification' with for-each:"); for (int n : arr) { System.out.print(n + " "); // original values! } // Sahi tarika - normal for loop se modify karo for (int i = 0; i < arr.length; i++) { arr[i] = arr[i] * 10; // actual array modify hoga } System.out.println("\nAfter actual modification (normal for):"); for (int n : arr) { System.out.print(n + " "); } } }
for-each mein n ek copy hai array element ki. n ko change karo, array nahi badlega! Array modify karna ho toh normal for loop use karo with index.public class ForEach3 { public static void main(String[] args) { // 2D array with for-each int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println("2D Array:"); for (int[] row : matrix) { // outer: each row for (int elem : row) { // inner: each element System.out.printf("%4d", elem); } System.out.println(); } // Find max in array int[] scores = {45, 89, 23, 67, 91, 34, 78}; int max = scores[0]; for (int score : scores) { if (score > max) max = score; } System.out.println("\nScores: "); for (int s : scores) System.out.print(s + " "); System.out.println("\nMax Score: " + max); } }
public class ForEach4 { public static void main(String[] args) { int[] arr = {5, 3, 8, 1, 9, 2, 7}; // for-each: READ only kaam - clean & simple System.out.println("for-each (read only):"); int total = 0; for (int n : arr) { total += n; } System.out.println("Total = " + total); // Normal for: index chahiye System.out.println("\nNormal for (with index):"); for (int i = 0; i < arr.length; i++) { System.out.println("arr[" + i + "] = " + arr[i]); } // Count even numbers int evenCount = 0; for (int n : arr) { if (n % 2 == 0) evenCount++; } System.out.println("\nEven count: " + evenCount); // char array char[] vowels = {'a', 'e', 'i', 'o', 'u'}; System.out.println("\nVowels:"); for (char v : vowels) { System.out.print(v + " "); } } }
break aur continueDeep Explanation:
break → loop se BAHAR niklo abhi! continue → is iteration SKIP karo, agli pe jao
break:
for(i=1 to 10) { if(i==5) break; ← loop khatam, i=5 pe print(i) } // Output: 1 2 3 4
continue:
for(i=1 to 5) { if(i==3) continue; ← sirf i=3 skip print(i) } // Output: 1 2 4 5
public class BreakContinue1 { public static void main(String[] args) { // break - loop se bahar niklo System.out.println("--- break demo ---"); for (int i = 1; i <= 10; i++) { if (i == 6) { System.out.println("Break at i=" + i); break; // loop khatam } System.out.print(i + " "); } System.out.println("\n\n--- continue demo ---"); for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; // even numbers skip } System.out.print(i + " "); // sirf odd print } // break in while System.out.println("\n\n--- break in while ---"); int n = 1; while (true) { // infinite loop System.out.print(n + " "); if (n == 5) break; // yahan se bahar n++; } } }
Deep Explanation: Normal break/continue sirf inner loop ko affect karta hai!
outer: ← label for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { if(j==1) break outer; ← OUTER loop band! } }
Without label:
break → sirf inner loop band continue → sirf inner loop ki current iteration skip
With label:
break outerLabel → outer loop band continue outerLabel → outer loop ki current iteration skip
public class LabelledLoop1 { public static void main(String[] args) { // Normal break - sirf inner loop System.out.println("--- Normal break (inner only) ---"); for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (j == 2) break; // sirf inner loop band System.out.println("i=" + i + " j=" + j); } } // Labelled break - outer loop bhi band System.out.println("\n--- Labelled break (outer too) ---"); outer: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (j == 2) break outer; // OUTER loop band! System.out.println("i=" + i + " j=" + j); } } // sirf i=1,j=1 print hoga phir outer loop band! } }
public class LabelledLoop2 { public static void main(String[] args) { // Labelled continue System.out.println("--- Normal continue ---"); for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (j == 2) continue; // inner j=2 skip System.out.println("i=" + i + " j=" + j); } } // j=2 wali lines skip hongi but loop chalta rahega System.out.println("\n--- Labelled continue ---"); outer: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (j == 2) continue outer; // OUTER next iteration! System.out.println("i=" + i + " j=" + j); } } // j=2 aate hi outer loop next i pe jump karega // j=3 kabhi nahi chalega! } }
public class LabelledLoop3 { public static void main(String[] args) { // Real use: 2D array mein search int[][] grid = { { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 42, 12} // 42 yahan hai }; int target = 42; boolean found = false; System.out.println("Searching for " + target + " in grid:"); search: // label for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { System.out.print("Checking ["+i+"]["+j+"]="+grid[i][j]+" "); if (grid[i][j] == target) { System.out.println("\nFound " + target + " at position [" + i + "][" + j + "]"); found = true; break search; // dono loops band! } } System.out.println(); } if (!found) System.out.println("Not found!"); } }
public class InfiniteLoop1 { public static void main(String[] args) { // Infinite loop types // for(;;) { } // ← teeno parts empty // while(true) { } // ← always true // do { } while(true); // ← always true // Controlled infinite loop with break int count = 0; for (;;) { // infinite loop count++; System.out.println("Count: " + count); if (count == 5) { System.out.println("Breaking out!"); break; // yahan se bahar } } // Unreachable code - compiler error deta hai // for(;;) { // System.out.println("infinite"); // } // System.out.println("unreachable!"); // ← ERROR! // ISLIYE yeh comment kar diya System.out.println("Program ended normally"); } }
break se controlled exit karo.| Loop Type | Key Points |
|---|---|
| for | Jab iterations pata ho | init ; condition ; update | Teeno parts optional — for(;;) = infinite |
| while | Condition-based, pehle check | Condition false → 0 times execute | Update body mein karo |
| do-while | Body PEHLE, condition BAAD | MINIMUM 1 baar hamesha chalega! | while ke baad semicolon ZAROORI |
| for-each | Array/Collection traverse | Read-only — modify array affect NAHI | Index access nahi milta |
| Mistake | Wrong ❌ | Right ✅ |
|---|---|---|
| do-while semicolon | } while(x<5) | } while(x<5); |
| for-each modify | for(int n:arr) n*=2 | Use normal for with index |
| Infinite loop | Forgetting update in while | Always update variable |
| Break scope | Thinking break exits outer | Use labelled break |
| Unreachable code | Code after infinite loop | Add break before that code |
ForLoop1 hai toh file ForLoop1.java hogi!