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 the following pattern 1 21 123 4321 12345 654321 1234567

0 votes
1

2  1

1  2  3

4  3  2  1

1  2  3  4  5

6  5  4  3  2  1

1  2  3  4  5  6  7
asked by Yash
edited by Ranjith

1 Answer

0 votes

Following is the logic in the pattern. For odd numbered lines, print from 1 to i. For even numbers lines, print from i to 1 in reverse.

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++) {
            if (i % 2 == 1) {
                // Odd lines - Print from 1 to i
                for (int j = 1; j <= i; j++) {
                    System.out.print(j + " ");
                }
            } else {
                // Even lines - Print from i to 1 in reverse
                for (int j = i; j >= 1; j--) {
                    System.out.print(j + " ");
                }
            }
            System.out.println();
        }
    }
}

 

answered by Ranjith (2,683 points)
thank u very much
...