Pattern 1
How Many Rows You Want In Your Pyramid? 9 Here Is Your Pyramid 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9
In this pattern also, we use same logic but instead of printing rowCount value rowCount times at the end of each row, we print ‘j’ where j value will be from 1 to rowCount.
Program
import java.util.Scanner; public class MainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //Taking noOfRows value from the user System.out.println("How Many Rows You Want In Your Pyramid?"); int noOfRows = sc.nextInt(); //Initializing rowCount with 1 int rowCount = 1; System.out.println("Here Is Your Pyramid"); //Implementing the logic for (int i = noOfRows; i > 0; i--) { //Printing i spaces at the beginning of each row for (int j = 1; j <= i; j++) { System.out.print(" "); } //Printing 'j' value at the end of each row for (int j = 1; j <= rowCount; j++) { System.out.print(j+" "); } System.out.println(); //Incrementing the rowCount rowCount++; } } }
Pattern 2
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9
Take the input from the user and assign it to noOfRows. This will be the number of rows he wants in a pyramid. Define one variable called rowCount and initialize it to 1. This will hold the value of current row count. At the beginning of each row, we print ‘i’ spaces where ‘i’ will be value from noOfRows to 1. At the end of each row, we print rowCount value rowCount times. i.e in the first row, 1 will be printed once. In the second row, 2 will be printed twice and so on. Below is the java code which implements this logic.
Program
import java.util.Scanner; public class MainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //Taking noOfRows value from the user System.out.println("How Many Rows You Want In Your Pyramid?"); int noOfRows = sc.nextInt(); //Initializing rowCount with 1 int rowCount = 1; System.out.println("Here Is Your Pyramid"); //Implementing the logic for (int i = noOfRows; i > 0; i--) { //Printing i spaces at the beginning of each row for (int j = 1; j <= i; j++) { System.out.print(" "); } //Printing 'rowCount' value 'rowCount' times at the end of each row for (int j = 1; j <= rowCount; j++) { System.out.print(rowCount+" "); } System.out.println(); //Incrementing the rowCount rowCount++; } } }