Welcome to ICSE Java Answers. Ask any questions you have related to Java and we will answer them.
Java is a registered trademark of Oracle. This site is in no way related to or endorsed by Oracle.

Print pattern 44441 33321 22321 14321

0 votes
asked by anonymous
edited by Ranjith

1 Answer

0 votes

Following is the logic in the pattern:

  • Let the number of lines to be printed be n, with the lines numbered from i = 1 to n.
  • To print line i,
    • Print number (n-i+1) (n-i+1) times
    • Print numbers from i to 1

Program

import java.util.Scanner;

public class Pattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = scanner.nextInt();
        for (int i = 1; i <= n; i++) {
            int num = n - i + 1;
            for (int j = 1; j <= num; j++) {
                System.out.print(num + " ");
            }
            for (int j = i; j >= 1; j--) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

Sample output

Enter n: 4
4 4 4 4 1 
3 3 3 2 1 
2 2 3 2 1 
1 4 3 2 1 

 

answered by Ranjith (2,683 points)
...