Lecture 6
Lecture 6
Programming I
• Fencepost Loop
• Nested for loops
• while and do-while loops
• Sentinel (indefinite) loops
A deceptive problem...
• Write code that prints each number from 1 to 5,
separated by commas.
should print:
1, 2, 3, 4, 5
Flawed solutions
• for (int i = 1; i <= 5; i++) {
System.out.print(i + ", ");
}
System.out.println(); // to end the line of output
– Output: 1, 2, 3, 4, 5,
place a post.
for (length of fence - 1) {
place some wire.
place a post.
}
Fencepost method solution
System.out.print(1);
for (int i = 2; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line
• Output:
Outer loop inner loop
i=1 j goes from 1 to 10
* * * * * * * * ** i=2 j goes from 1 to 10
* * * * * * * * ** i=3 j goes from 1 to 10
* * * * * * * * **
* * * * * * * * ** i=4 j goes from 1 to 10
* * * * * * * * ** i=5 j goes from 1 to 10
i=6 <=5? No then done
• Example:
int num = 1; // initialization
while (num <= 200) { // test
System.out.print(num + " ");
num = num * 2; // update
}
// output: 1 2 4 8 16 32 64 128
The while Count-controlled Loop
count
int count ;
count = 4;
count -- ;
}
System.out.print( " Done " ) ;
The while Count-controlled Loop
count
int count ;
count = 4; 4
count -- ;
}
System.out.print( " Done " ) ;
The while Count-controlled Loop
count
int count ;
count = 4; 4
count -- ;
}
System.out.print( " Done " ) ;
The while Count-controlled Loop
count
int count ;
count = 4; 4
count -- ;
}
System.out.print( " Done " ) ;
The while Count-controlled Loop
count
int count ;
count = 4; 3
count -- ;
}
System.out.print( " Done " ) ;
The while Count-controlled Loop
count
int count ;
count = 4; 3
count -- ;
}
System.out.print( " Done " ) ;
The while Count-controlled Loop
count
int count ;
count = 4; 3
count = 4; 2
count = 4; 2
count = 4; 2
count = 4; 1
count = 4; 1
count = 4; 1
count = 4; 0
count = 4; 0
count = 4; 0
if (<condition>) {
break;
}
<statement(s)> ;
}
• Can also be used to end the loop in the middle for any other
condition other than the loop test
The do/while loop
• do/while loop: Performs its test at the end of each repetition.
– Guarantees that the loop's {} body will run at least once.
do {
statement(s);
} while (test);
do {
int roll1 = 1 + (int) (Math.random() * 6); // one roll
int roll2 = 1 + (int) (Math.random() * 6);
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
tries++;
} while (sum != 7);
int x = 0;