Johnathan White
Johnathan White

Reputation: 13

Java nested for loop print out

I'm a total beginner to java and need help writing this nested for loop. This is the desired output.

2     3      5
5     10     26
11    31     131
23    94     656

I understand that the increment is 2 times the first number + 1, but I don't understand how to create the loop for it.

public static void main(String[] args) {
    for(int i = 2; i <= 5; i++) {   
        for(int j = i; j <= i; j++) {
            System.out.print(j+(i*j));
        }   
        System.out.println();
    }
}

Upvotes: 1

Views: 583

Answers (2)

RamPrakash
RamPrakash

Reputation: 1836

Question is so simple it consists of two things read the pattern and use the appropriate loop statements in java to achieve this. Printing them is another task which is not difficult.
@Jonathan your pattern is right but your algorithm is incorrect. I'm not giving you perfect solution but you have to use proper loop statement to make it efficient. I'm here giving you a thought so that you can think in this way..hope you get it.

public static void main(String[] args) {
/*  2     3      5
    5     10     26
    11    31     131
    23    94     656
*/
    int two = 2;
    int three = 3;
    int five = 5;
    int i=0;
     //use do-while to print 2 3 5
        do{
            System.out.println(two +"  "+ three +"  "+five);
            two=two*2+1; // apply math pattern
            three= three*3+1;
            five= five*5+1;

            i++;
        }while(i<4);;

}

Upvotes: 2

Tsung-Ting Kuo
Tsung-Ting Kuo

Reputation: 1170

Please try the following code (I have tested the code, the output is exactly the same as yours):

public static void main(String args[]) {
    int[][] results = new int[4][3];
    results[0][0] = 2;
    results[0][1] = 3;
    results[0][2] = 5;

    for (int i = 1; i < results.length; i++) {
        for (int j = 0; j < results[0].length; j++) {
            results[i][j] = results[i - 1][j] * results[0][j] + 1;
        }
    }

    for (int i = 0; i < results.length; i++) {
        for (int j = 0; j < results[0].length; j++) {
            System.out.print(results[i][j] + "\t");
        }
        System.out.println();
    }
}

Upvotes: 0

Related Questions