while while (condition) { statements } Can put anything in “statements” The entire construct is called a while loop statements are executed until condition is true Even before executing it the first time condition is evaluated A while loop may not execute even once
Example class justAnExample { public static void main(String arg[]) { int x = 5; int y = 0; while (x < 10) { y--; x++; } System.out.println(y);
Example class justAnExample { public static void main(String arg[]) { int x = 15; int y = 0; while (x < 10) { y--; x++; } System.out.println(y);
Sum of natural numbers class naturalSum { public static void main(String arg[]) { int n = 2; int y = 1; while (n <= 100) { y += n; n++; } System.out.println(“Sum of the first ” + (n-1) + “ natural numbers is ” + y);
Sum of natural numbers class naturalSumAnotherWay { public static void main(String arg[]) { int n = 99; int m = n+1; int y = 100; while (n > 0) { y += n; n--; } System.out.println(“Sum of the first ” + m + “ natural numbers is ” + y)
do-while do { statements } while (condition); “statements” execute at least once irrespective of condition
for loops for (expression1; condition; expression2) { statements } Same as expression1 while (condition) { expression2
Sum of natural numbers class naturalSum { public static void main(String arg[]) { int n; int y = 1; for (n=2; n <=100; n++) { y += n; } System.out.println(“Sum of the first ” + (n-1) + “ natural numbers is ” + y)
Comma operator in for loop for (expression1a, expression2a, …; condition; expression1b, expression2b,…) { statements } Same as expression1a expression2a … while (condition) { expression1b expression2b …
Sum of natural numbers class naturalSum { public static void main(String arg[]) { int n; int y; for (n=2, y=1; n <=100; y += n, n++) { } System.out.println(“Sum of the first ” + (n-1) + “ natural numbers is ” + y) }
Empty for loop body for (expression1; condition; expression2) { } Same as for (expression1; condition; expression2);
Infinite loops Loops that never terminate while (true) { statements } do { } while (true);
Infinite loops for (expression1; ;expression2) { statements } for (i=0; i > -10; i++) { for (i=0; i<=100; i--) {