The for loop#
for (initialisation; condition; update) {
// body
}
9 x 1 = 9 9 x 2 = 18 9 x 3 = 27 9 x 4 = 36 9 x 5 = 45 9 x 6 = 54 9 x 7 = 63 9 x 8 = 72 9 x 9 = 81 9 x 10 = 90
15! = 1307674368000 Sum of even numbers 1-100 = 2550 5 4 3 2 1
The while loop#
Use while when the number of iterations depends on a condition, not a count:
12321 is a palindrome Money doubles in 10 years
The do-while loop#
The body runs first, then the condition is checked - perfect for menus and "ask until valid" input:
120 is invalid, enter 0-100 -5 is invalid, enter 0-100 Accepted: 86
The enhanced for (for-each) loop#
To visit every element of an array or collection without an index:
I am learning C I am learning C++ I am learning Java I am learning Python I am learning SQL Total = 316
break, continue and labelled break#
1 3 5 7 9 11 Found 42 at row 1, col 1
break loop से बाहर निकल जाता है, continue बाकी code छोड़कर अगले चक्कर (iteration) पर चला जाता है। Nested loops में बाहर वाले loop से निकलना हो तो उसे label दें (outer:) और break outer; लिखें।
Nested loops and patterns#
*
**
***
****
*****
*
***
*****
*******
*********
*******
*****
***
*String.repeat(n) (Java 11+) saves an inner loop. In exams you may be asked to write the inner loops explicitly - both approaches give the same output.
Prime numbers - a classic#
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 15 primes below 50
Summary#
forfor counted loops,whilefor condition loops,do-whilewhen the body must run once.- The enhanced for (
for (T x : collection)) reads every element. breakexits,continueskips; labels let you break out of nested loops.- Digit tricks (
% 10,/ 10) and nested loops solve most classic problems.