Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised January 9, 2026)

Previous: Loops

Sequences

//
// Sequences.java
//


public class Sequences
{
    public static void main(String[] args)
    {
        System.out.println("Sequences");
        System.out.println();

        // print multiples of 7

        for (int i=0; i<30; i++)
        {
            if (i%7 == 0)
                System.out.println(i);
        }

        System.out.println();

        // print multiples of 7 again;
        // i+=7 is shorthand for i=i+7

        for (int i=0; i<30; i+=7) 
            System.out.println(i);

        System.out.println();

        // an arithmetic sequence has a common difference:
        //  3, 10, 17, 24, ...

        // print sequence using explicit formula
        
        for (int i=0; i<5; i++)
            System.out.println(i*7 + 3);

        System.out.println();

        // print sequence using recursive formula

        int value = 3;

        for (int i=0; i<5; i++)
        {
            System.out.println(value);
            value += 7;
        }

        System.out.println();
    }
}

Output:

Sequences

0
7
14
21
28

0
7
14
21
28

3
10
17
24
31

3
10
17
24
31

Next: