Blog

Java Numerical Pattern-1

How to draw the following figure through a java program.

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

Drawing the figure without numbers we get

*

*  *

*  * *

* * * *

*  * * * *

If we consider i to be row number and j the column number. Then we have

i(row number)   j(Stars)

1                           1

2                           2

3                           3

4                           4

5                           5


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

Now, analyze the numerical data.

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

Every line starts with the line number i. Then we add 4,3,2, etc.

The following code should be self explanatory now.


package holyjava;

import java.util.Scanner;

&nbsp;

public class SimplePattern {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();

;
for(int i=1;i<=n;i++)
{
int increment=n-1;
int x=i;
for(int k=1;k<=i;k++)
{
if(k==1)
System.out.print(x);
else
{
x=x+increment;
System.out.print(x);
increment--;
}
System.out.print(" ");
}



System.out.println();
}
}
}

end

Leave a Reply

Your email address will not be published. Required fields are marked *