Skip to content

Activity 4: Loops and Arrays

Provided Files

Tip

Some examples below require running one line at a time. You can triple-click any word to select an entire line. That makes copying each line easier, especially on a touchpad.

Example Code

Model 1

Run each code snippet in jshell.

int i;
System.out.println("\nLoop 1A");
i = 1;
while (i <= 10) {
    System.out.println(i);
    i++;
}
System.out.println("\nLoop 1B");
i = 10;
while (i >= 1) {
    System.out.println(i);
    i--;
}
System.out.println("\nLoop 4A");
for (i = 1; i <= 10; i++) {
    System.out.println(i);
}
System.out.println("\nLoop 4B");
for (i = 10; i >= 1; i--) {
    System.out.println(i);
}

Model 2

Run each line in jshell one at a time.

char[] letterArray = {'H', 'i'};
letterArray[0]
letterArray.length

double[] numberArray = new double[365];
numberArray[0]
numberArray.length
int[] a = {3, 6, 15, 22, 100, 0};
double[] b = {3.5, 4.5, 2.0, 2.0, 2.0};
String[] c = {"alpha", "beta", "gamma"};

a[3] + a[2]
b[2] - b[0] + a[4]
c[1].charAt(a[0])
a[4] * b[1] <= a[5] * a[0]

Model 3

Run each line in jshell one at a time.

String str = "hello world";

str.charAt(8)
str.indexOf("wo")
str.length()
str.substring(4, 7)
str.toUpperCase()