Welcome to ICSE Java Answers. Ask any questions you have related to Java and we will answer them.
Java is a registered trademark of Oracle. This site is in no way related to or endorsed by Oracle.

Print pattern - 1 3 2 4 5, 4 5 6 9, 9 11 15, 20 26 46

+1 vote
1 3 2 4 5
4 5 6 9
9 11 15
20 26
46
asked by Chiku
edited by Ranjith

1 Answer

+1 vote

Following is the logic in the pattern. The first line has numbers 1 3 2 4 5. Subsequent lines are created by adding pairs of numbers on the previous line. The following diagram illustrates this.

Start with an array initialized with {1, 3, 2, 4, 5}

int[] array = {1, 3, 2, 4, 5};

There are five lines in the pattern. So, have a create a loop that runs five times.

for (int i = 1; i <= 5; i++) {
}

In each iteration of the loop, print the current array contents.

Then, create a new array of size less than the current array and compute its contents by adding numbers of the current array and then set it as the new array.

int[] newArray = new int[array.length - 1];
for (int j = 0; j < newArray.length; j++) {
    newArray[j] = array[j] + array[j + 1];
}
array = newArray;

Following is the complete program

public class Pattern {
    public static void main(String[] args) {
        int[] array = {1, 3, 2, 4, 5};
        for (int i = 1; i <= 5; i++) {
            for (int j = 0; j < array.length; j++) {
                System.out.print(array[j] + " ");
            }
            System.out.println();

            int[] newArray = new int[array.length - 1];
            for (int j = 0; j < newArray.length; j++) {
                newArray[j] = array[j] + array[j + 1];
            }
            array = newArray;
        }
    }
}

Following is the output

1 3 2 4 5 
4 5 6 9 
9 11 15 
20 26 
46 

 

answered by Ranjith (2,683 points)
...