Download presentation
Presentation is loading. Please wait.
1
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
2
Example class justAnExample { public static void main(String arg[]) {
int x = 5; int y = 0; while (x < 10) { y--; x++; } System.out.println(y);
3
Example class justAnExample { public static void main(String arg[]) {
int x = 15; int y = 0; while (x < 10) { y--; x++; } System.out.println(y);
4
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);
5
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)
6
do-while do { statements } while (condition);
“statements” execute at least once irrespective of condition
7
for loops for (expression1; condition; expression2) { statements }
Same as expression1 while (condition) { expression2
8
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)
9
Comma operator in for loop
for (expression1a, expression2a, …; condition; expression1b, expression2b,…) { statements } Same as expression1a expression2a … while (condition) { expression1b expression2b …
10
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) }
11
Empty for loop body for (expression1; condition; expression2) { }
Same as for (expression1; condition; expression2);
12
Infinite loops Loops that never terminate while (true) { statements }
do { } while (true);
13
Infinite loops for (expression1; ;expression2) { statements }
for (i=0; i > -10; i++) { for (i=0; i<=100; i--) {
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.