For Loop

The for-i loop, often referred to simply as a for loop, is commonly used for iterating over a range of values, such as the elements in an array.

Novice · Java · Updated

By

The for-i loop, often referred to simply as a for loop, is commonly used for iterating over a range of values, such as the elements in an array. We know exactly how many times the loop will execute.

Example

This code loops 3 times, the number of names stored in the array.

public class ForLoopExample
{
    public static void main(String[] args)
    {
        String[] names = {"Alice", "Bob", "Charlie"};

        for (int i = 0; i < names.length; i++)
        {
            String name = names[i];
            System.out.println(name);
        }
    }
}

In this example, the for loop initializes i to 0, checks that i is less than the length of the names array, and increments i after each iteration. Each name is printed out sequentially.

Do it: show the score after each quarter

A TV graphic shows a team's score after every quarter, not only at the end. Write a function that works those scores out.

The function gets one value:

  • quarterPoints: the points scored in each quarter, an int[], in order. It always has at least one quarter, and a game that goes to overtime has more than four.

For example:

int[] quarterPoints = {12, 14, 6, 7};
Quarter Index Points Score after it
1 0 12 12
2 1 14 12 + 14 = 26
3 2 6 26 + 6 = 32
4 3 7 32 + 7 = 39

So runningScores(quarterPoints) returns a new array, {12, 26, 32, 39}.

Your job: write the function int[] runningScores(int[] quarterPoints).

  • Return a new int[] with one element for each quarter.
  • Each element is the score after that quarter: its points plus the points of every quarter before it.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets