For Loop and Array

Array

We have an array, it is quite common to go through the elements of the array and do some processing on them.

First, let's create the array first. The following code is to create an array intArray of type int.

int[] intArray = {4,3,6};

How to refer to an element inside the array? by using arrayName[i]

In this case,

intArray[0] --> 4

intArray[1] --> 3

intArray[2] --> 6

If we want to display the element, we can just write

System.out.println(intArray[0]); //display the first element which is at index 0

The output will be

4

How to update an element of an array? just use = (Assignment operator)

intArray[0] = 5; //the new value stored in index 0 of the array is 5

Common Question Types for Array

Display all elements in the array

The type of the array is int in this case. How to display an int value? By using System.out.println()

Step 1: Write the code without FOR loop.

System.out.println(intArray[0]); 
System.out.println(intArray[1]); 
System.out.println(intArray[2]);

Step 2: Identify the constant part and the varying part

varying - the number "0...1...2" inside the []

constant - the rest of the code

Step 3: Use a variable to replace the varying part

System.out.println(intArray[n]);

This code would be inside the body of the FOR loop.

Step 4: Identify the starting number, the ending number, the step/update and the comparison operator

  • start: 0
  • end: 2
  • step/update: +1 (add 1 every time)
  • Comparison Operator: <=

Step 5:  Construct a FOR loop

for(int n=0; n <= 2; n++)
{
   System.out.println(intArray[n]); 
}

To make one last improvement. we can replace 2 (the ending number) by intArray.length -1 since the last index of the array is always one less than the array length.

 
for(int n=0; n <= intArray.length-1 ; n++)
{
   System.out.println(intArray[n]); 
}

By using intArray.length, we need not find the ending number for the FOR loop any more.

Alternatively, you can also write

for(int n=0; n < intArray.length ; n++){
   System.out.println(intArray[n]); 
}

By now, we have find a common pattern for the Array type of questions. Most of the Array questions will have the same starting number, ending number, step/update, and comparison operator. So we can just use this template for future questions involving array and for loop.

for(int n=0; n < arrayName.length ; n++)
{
   //statements 
}


Last modified: Friday, 2 November 2018, 5:52 PM