Shubham Batra
Shubham Batra

Reputation: 1278

How to make pattern of numbers in java using only two variables?

#1
#2 3
#4 5 6
#7 8 9 10
#11 12 13 14 15

this is the required pattern and the code which i used is

  public class Test{
    public static void main(String[] args) {
        int k = 1;
        for (int i = 0; i <= 5; i++){
            for (int j = 1; j <= i; j++){
                System.out.print(k + " ");
                k++;
            }
            System.out.println();
        }
    }
}

as you can see i used the variable k to print the numbers. My question is that is there a way to print the exact same pattern without using the third variable k? I want to print the pattern using only i and j.

Upvotes: 2

Views: 809

Answers (3)

Alok Chaudhary
Alok Chaudhary

Reputation: 3511

You can use this:

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

Or you can the find the nth term and subtract it each time:

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

Upvotes: 0

You can use

System.out.println((i+j) + " ");

e.g.

i    j    (i+j)

0    1      1
1    1      2
2    1      3
2    2      4
..........

Upvotes: -5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

Since this problem is formulated as a learning exercise, I would not provide a complete solution, but rather a couple of hints:

  • Could you print the sequence if you knew the last number from the prior line? - the answer is trivial: you would need to print priorLine + j
  • Given i, how would you find the value of the last number printed on i-1 lines? - to find the answer, look up the formula for computing the sum of arithmetic sequence. In your case d=1 and a1=1.

Upvotes: 6

Related Questions