In this tutorial, we will write a program to print even and odd number pyramid in java. Before that, you may go through the following topic in java.
Example:
1 2 3 4 5 6 7 8 9 10 | <strong>Input: </strong> No. of rows: 7 <strong>Output:</strong> <strong>* 1* *2* 1*3* *2*4* 1*3*5* *2*4*6*</strong> |
Java Program to print Even Odd number Pyramid
The program takes a user input for the number of rows with the help of a Scanner class in Java. Then iterating through for loop and inner for loop, it prints the even and odd number pattern in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import java.util.Scanner; public class Main { public static void main(String[] args) { int i, j, k, num; Scanner sc = new Scanner(System.in); System.out.print("Enter the no. of rows: "); num = sc.nextInt(); for (i = 1; i <= num; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) System.out.print(j); else System.out.print("*"); } System.out.print("\n"); } } } |
Output: