## Tuesday, 15 January 2019

### Java Code to Print the Numbers as Pyramid - Examples

This question is also one of the popular java interview question for freshers. The interviewer will check the logical thinking, how to solve the this kind of problems in real time.  I have written sample patterns in the below code, you can practice others also.

1)                                                                                          2)

The above 1st pattern code is ,

PyramidWithNumbers.java,

```package com.sample;

public class PyramidWithNumbers {

public static void main(String[] args) {

int rowCount = 1;
System.out.println("Pyramid code output");
int noOfRows = 5;            // number of rows for pyramid

for (int i = noOfRows; i > 0; i--) {

// print the spaces at begining of each row.
for (int j = 1; j <= i; j++) {```
`                                 System.out.print(" ");`
```                        }

//print the value of rowcount for each row, for example 2, it will print 2 times 2 2.
for (int j = 1; j <= rowCount; j++) {```
`                               System.out.print(rowCount+" ");`
`                        }`
```
System.out.println();
rowCount++;
}
}
}
```

Output :--
Pyramid code output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

The above second pattern of code is,

PyramindWithStar.java

```package com.sample;

public class PyramidWithStar {

public static void main(String[] args) {

int rowCount = 1;
System.out.println("Pyramid code output");
int noOfRows = 5;            // number of rows for pyramid

for (int i = noOfRows; i > 0; i--) {

// print the spaces at begining of each row.
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}

//print the * value to each rowcount
for (int j = 1; j <= rowCount; j++) {
System.out.print("*"+" ");
}
System.out.println();
rowCount++;
}
}
}
```

Output:--

Pyramid code output
*
* *
* * *
* * * *
* * * * *

Related Posts:--
1) Java Program to check the given number is a palindrome or not
2) Write a Java program to print the Floyd's triangle
3) Java Program for Bubble Sort in Ascending and Descending order
4) Java Program to Reverse a Linked List using Recursion and Loops
5) Java Program to Count Occurrence of Word in a Sentence
6) How to Remove duplicates from ArrayList in Java
7) Java program to print the first n prime numbers
8) Java Program to find the Missing Number in an Array