Jeeven Nullatamby
Jeeven Nullatamby

Reputation: 37

How would I get this specific pattern, for loop pattern

I need to be able to get this pattern using for loops:

Q. Write a program to complete the first N rows of the following output. The number of rows N should be read from the keyboard.

Intended output:

1              
2 4              
3 6 9                  
4 8 12 16                            

Result:

1              
24              
399               
4161616         
525252525    

Attempt:

(I haven't used scanner yet, because I wanted to try understand how to do it without scanner.)

import java.util.Scanner;

public class Test {
  public static void main(String [] args){

    int odd = 1;
    for(int i=1;i<=5;i++)
    {
      int no=i;
      for(int j=1; j<=i;j++)
      {
        System.out.print(no);
        no = i*i;
      }
      System.out.println();

    }
  }
}

Upvotes: 1

Views: 57

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53525

You were very close!

for(int i = 1; i <= 5; i++) {
    for(int j = 1; j <= i; j++) {
        System.out.print(i * j + " ");        
    }
    System.out.println();
}

See demo

Upvotes: 3

Related Questions