Jagged Array in Java - Created by taking user input

Jagged Array in Java - Created by taking user input

creating and showing jagged arrays in java by taking user input

ยท

2 min read

What is a jagged array?

A jagged array is a multidimensional array where member arrays are of different sizes. For example, we can create a 2D array where the first array is of 3 elements and is of 4 elements. Following is the example demonstrating the concept of a jagged array.

Code for creating and showing jagged arrays in java by taking user input

JaggedArray.java

import java.util.Scanner;

public class JaggedArray {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Input array row : ");
        // creating the array 
        int n = sc.nextInt();
        int arr[][] = new int[n][];
        for (int i = 0; i < n; i++) {
            System.out.print("Input number of elemrnt in "+ (i+1) +" row : ");
            arr[i] = new int[sc.nextInt()];
        }
        // counting array elemnts 
        int count = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                count++;
            }
        }
        // input array elements  
        System.out.println("Input "+ count +" array Elemets : ");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = sc.nextInt();
            }
        }
        // array output 
        System.out.println("Your jaged array is : ");
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output :

Did you find this article valuable?

Support Rahul's Blog by becoming a sponsor. Any amount is appreciated!

ย