- To print sideway triangle pattern using numbers
User Input: 3
Output:
1 1 2 1 2 3 1 2 1
import java.util.Scanner;
public class Pattern {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter number of columns : ");
int columns,trows,k,num;
columns=userInput.nextInt();
trows=2*columns-1;
k=1;
for(int i=1; i<=trows; i++) {
num=1;
for(int j=1; j<=k; j++) {
System.out.print(num++ +" ");
}
if(i<columns)k++;
else k--;
System.out.print("\n");
}
}
}
Enter number of columns: 4 1 1 2 1 2 3 1 2 3 4 1 2 3 1 2 1Program
Main Logic :
trows=2*columns-1; // trows : total rows to print
k=1; // Used to trigger decreasing order of number
for(int i=1; i<=trows; i++) {
num=1;
for(int j=1; j<=k; j++) {
System.out.print(num++ +" ");
}
//check for position change at which triangle number value to decrease
if(i<columns)k++;
else k--;
System.out.print("\n");
}
Concept
Coming Soon !
QuickPractice isn’t the thing you do once you’re good. It’s the thing you do that makes you good.