Lecture 4
Lecture 4
Lecture 4
• Let i = 0
• Now i < 2 is true, let's display the text:
Iteration 0
• Execute i++, and now i becomes 1
• The condition i < 2 is still true, let's display the text:
Iteration 1
• Execute i++, and now i becomes 2
• Finally i < 2 is false, we won't display another line.Loop ends.
How many lines have we displayed? What numbers were shown?
Example
System.out.println("The first 10 natural numbers:");
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
Result
The first 10 natural numbers:
1
2
3
4
5
6
7
8
9
10
for loop flowchart
for (i = 2; i <= 6; i = i + 2) {
print (i + 1)
}
• An array of 10 zeros
• An array of 3 numbers
• An array of 3 strings
Getting array length
int[] a = {2, 4, 6};
System.out.println(a.length); // 3
Result
#0: 0.2
#1: 0.4
#2: 0.1
#3: -0.13
#4: 0.9
How to stop a for loop
• When we search for something with a for
loop, we may want to stop looking as soon as
it is found.
• E.g. Find one negative number from an array
such as: int[] a = {6,4,-2,6,5,9,15,-6,2};
for (int i = 0; i < a.length; i++) {
if (a[i] < 0) {
System.out.println("Found: " + a[i]);
}
}
Output:
Found: -2
Output:
4,8
4,9
The while loop
• Repeat a block of code as long as a condition holds true
• The number of iterations is not specific and can be zero
int n = 0;
while (n < 10) {
block of
System.out.println("n = " + n);
code to
n++; repeat
}
while loop explained
int n = 1, e = 0;
while (n < 10) {
What is the output?
n = n * 2;
e++;
}
System.out.println("2^" + e + " = " + n);
• Let n = 1, e = 0
• Now n < 10 is true, let's continue the loop.
• Execute n = n * 2 and e++ → n becomes 2, e becomes 1
• The condition n < 10 is still true, let's continue the loop.
• Execute n = n * 2 and e++ → n becomes 4, e becomes 2
• The condition n < 10 is still true, let's continue the loop.
• Execute n = n * 2 and e++ → n becomes 8, e becomes 3
• The condition n < 10 is still true, let's continue the loop.
• Execute n = n * 2 and e++ → n becomes 16, e becomes 4
• Finally n < 10 is false, the loop ends.
while loop flowchart
int n = 0;
do { block of
System.out.println("n = " + n); code to
n++; repeat
} while (n < 10);
• Let n be uninitialized
• Print a text message to ask user to enter a positive integer.
• Get n's value from the keyboard with sc.nextInt() method.
• Repeat if the user does not obey you.
do…while loop flowchart
System.out.println(s2);