Program to Print Heart Number Pattern
In the previous article, we have discussed Java Program to Print Plus Number Pattern
In this article we are going to see how to print the Heart number pattern.
Example: When number of rows = 5 22 22 4444 4444 555555555 4444444 33333 222 1
The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.
Approach to Print Heart Number Pattern
- Enter total row and store it in an integer variable say
row
. - Take a inner loop to print the column values.
- Take a nested for loop to print left semi-circle at the beginning.
- Take a nested for loop to print right semi-circle beginning.
- Take another nested loop to print a inverted pyramid below the semi-circles.
Java Code to Print Heart Number Pattern
import java.util.Scanner; public class Main { public static void main(String[] args) { int r,c, row; Scanner sc= new Scanner(System.in); System.out.print("Enter no of rows = "); row=sc.nextInt(); // loop to print 2 semicircles at the top for(r = row/2; r <= row; r+=2) { // print spaces for(c = 1; c < row-r; c+=2) { System.out.print(" "); } // loop to print left semi-circle for(c = 1; c <= r; c++) { System.out.print(r); } // print spaces for(c = 1; c <= row-r; c++) { System.out.print(" "); } // loop to print right semi-circle for(c = 1; c <= r; c++) { System.out.print(r); } // move to next line/row System.out.println(""); } // loop to print the inverted pyramid for(r = row; r >= 1; r--) { // adds spaces in each row for(c = r; c < row; c++) { System.out.print(" "); } // keep on printing number from c=1 till (r*2)-1 for(c = 1; c <= (r*2)-1; c++) { System.out.print(r); } // move to next line/row System.out.println(""); } } }
Output: Enter no of rows = 5 22 22 4444 4444 555555555 4444444 33333 222 1
Are you seeking professional help for coding in the Java programming language? The tutorial of Java Programming Examples for beginners and experts will strongly improve your coding skills then you can program for any logic in Java.
Related Java Number Pattern Programs: