3. Write a JAVA program to accept a number ‘n’ from the user and display triangle with ‘n’ number of rows.
E.g., n=5
1
2 4
1 3 5
2 4 6 8
1 3 5 7 9
Answers
Answered by
0
Answer:
import java.util.*;
class pattern
{
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows:");
int n=sc.nextInt();
int ch=0;
for(int i=1;i<=n;i++)
{
if(i%2==0)
{
ch=2; //if i is even, the printing starts from 2
}
else
{
ch=1; //if i is odd, the printing starts from 1
}
for(int j=1;j<=i;j++)
{
System.out.print(ch+" ");
ch=ch+2;
}
System.out.println(); // to change the position of cursor to next line
}
}
}
Similar questions