Pyramid Pattern of Numbers code in java

Yash Walke
2 min readNov 30, 2021

--

If you look at the first pattern, every row contains the same number printed the same number of times. However, every row has leading white spaces whose count is “rows-i”. Let’s look at the program to print this pattern.

package com.journaldev.patterns.pyramid;

import java.util.Scanner;

public class PyramidPattern {

private static void printPattern1(int rows) {
// for loop for the rows
for (int i = 1; i <= rows; i++) {
// white spaces in the front of the numbers
int numberOfWhiteSpaces = rows — i;

//print leading white spaces
printString(“ “, numberOfWhiteSpaces);

//print numbers
printString(i + “ “, i);

//move to next line
System.out.println(“”);
}
}

//utility function to print string given times
private static void printString(String s, int times) {
for (int j = 0; j < times; j++) {
System.out.print(s);
}
}

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
System.out.println(“Please enter the rows to print:”);
int rows = scanner.nextInt();
// System.out.println(“Rows = “+rows);
scanner.close();

System.out.println(“Printing Pattern 1\n”);
printPattern1(rows);

}

}

Notice that I have created a utility function for the common string printing task. If you can divide your program into short reusable functions, then it shows that you are not only looking to write the program but also want to make sure of its quality and reusability.

When we run the above program, we get the following output.

--

--

Yash Walke

I'm a tech guy, who engaged with codes. Loves to spread knowledge.👨‍💻.