For Loop and 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.
How to refer to an element inside the array? by using
In this case,
intArray --> 4
intArray --> 3
intArray --> 6
If we want to display the element, we can just write
The output will be
How to update an element of an array? just use = (Assignment operator)
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
Step 1: Write the code without FOR loop.
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
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
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.
intArray.length, we need not find the ending number for the FOR loop any more.
Alternatively, you can also write
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.