Skip to content

Activity 4: Loops and Arrays

Instructions

Example Code

Model 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Loops {

    public static void main(String[] args) {
        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 the following lines 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 the following lines in jshell one at a time.

String str = "hello world";

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