Lecture 4
Lecture 4
Lecture 4
Arrays in Java
The array structure
• At times, we have to handle a lot of values and
declaring too many variables is not a good option
• So they gave programming languages a tool to group
many values into one variable called array
• We can do something like this:
int[] a = {6, 2, 15, 4, 11};
System.out.println(a[0] + a[2]); // 6 + 15
• 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
Multi-Dimensional Arrays
• Example of a two-dimensional array:
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
while loop flowchart
while (i < n) {
print(i);
i++;
}
The do…while loop
• Repeat a block of code once, and then continues as long
as a condition holds true
• The number of iterations is not specific but always >= 1
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
Stop a while loop with break
• Similar to the for loop, the while loop can be
terminated with the break statement.
while (n < 10) {
if (sc.nextLine().equals("q")) {
System.out.println("Goodbye!");
break;
}
n++;
}
Skip the rest of an iteration with continue
• Similar to the for loop, an iteration of a while loop and
do…while loop can be interrupted with continue
int n = 0;
while (n < 3) {
n++;
System.out.println(n);
if (n == 2) continue;
System.out.println("...hi");
}
Output:
1
...hi
2
3
...hi
Example
• Replace all spaces in a string with underscores.
Answer 1
String s = "To infinity and beyond!";
System.out.println(s2);
Output:
1.0
25.5
13.730392156862745
8.685974371897991
7.221190474331159
7.072628275743689
7.071067984011346
7.071067811865477
7.0710678118654755
Result: 7.0710678118654755