For loops and arrays are a great way of simplifying your code. Consider the task of displaying which students did better on which test.

Name

Test 1

Test 2

Bert

8

3

Fiona

5

7

Sally

7

6

George

7

7

Fred

5

4

If we stored the values into an array we would end up with 3 arrays -

Array

Position

0

1

2

3

Names array 4

Value

Bert

Fiona

Sally

George

Fred

 

Array

Position

0

1

2

3

Test1 array

4

Value

8

5

7

7

5

 

Array

Position

0

1

2

3

Test2 array 4

Value

3

7

6

7

4

 

To display all of the values we could then write the code -

  1. for(int a=0;a<=4; a = a + 1){
  2. System.out.println(names[a] + " test 1 = " + test1[a] + " test 2 = " + test2[a]);
  3. }

To work out the avearage for test 1 we could do -

  1. int sum =0;
  2. for (int a=0; a<test1.length; a = a + 1){
  3. sum = sum + test1[a];
  4. }
  5. System.out.println("Average for test 1 = " + sum / test1.length);

Arrays and loops go together like peas in a pod. If you use an array you will most likely use loops. It just goes without saying.

next while loops >>

 
Basics
Menu
Search