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 1 2 3 4, 5 6 7 8, 9 10 11 12

0 votes
Write a program to print the following pattern

1 2 3 4

5 6 7 8

9 10 11 12
asked by Samarth
edited by Ranjith

1 Answer

0 votes

Given an input n, the pattern contains n lines and each line contains n numbers. This can be implemented with a nested for loop with both the loop counters, i and j, ranging from 1 to n.

We declare another variable num, which is the current value to be printed. In the inner loop, we print this number and then increment it.

Below is the 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();
        int num = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                System.out.print(num + " ");
                num++;
            }
            System.out.println();
        }
    }
}

Sample output:

Enter n: 4
1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14 15 16 

 

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