Q:

Program to create a two dimensional array fill it with given few characters in Java

belongs to collection: Java Array Programs

0

Given number of rows, cols and the characters we have to create a two dimensional array and fill all elements with the given characters using java program.

Example:

    Input
    Enter size of the Array : 5 (rows are cols are same here)
    Enter first character : @
    Enter second character : *
    Enter third character : #

    Output

    # @ @ @ # 
    * # @ # * 
    * * # * * 
    * # @ # * 
    # @ @ @ # 

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program

import java.util.Scanner;

public class ExArrayFillWithDIffCharacters {
  public static void main(String args[]) {
    // create scanner class object.
    Scanner Sc = new Scanner(System.in);

    // enter the size here.
    System.out.print("Enter size of the Array : ");
    int n = Sc.nextInt();
    // enter size in given range.
    if (n < 2 || n > 10)
      System.out.print("Size out of Range");
    else {
      // declare array object.
      char A[][] = new char[n][n];

      // enter different characters for filling the array
      System.out.print("Enter first character : ");
      char c1 = Sc.next().charAt(0);

      System.out.print("Enter second character : ");
      char c2 = Sc.next().charAt(0);

      System.out.print("Enter third character : ");
      char c3 = Sc.next().charAt(0);

      for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
          // Filling the diagonals with third character
          if (i == j || (i + j) == (n - 1))
            A[i][j] = c3;
          else // Filling all other positions with second character
            A[i][j] = c2;
        }
      }

      for (int i = 0; i < n / 2; i++) {
        for (int j = i + 1; j < n - 1 - i; j++) {
          // Filling the upper positions.
          A[i][j] = c1;

          // Filling the lower positions.
          A[n - 1 - i][j] = c1;
        }
      }

      // Printing the Matrix
      System.out.println("\nOutput : \n");
      for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
          System.out.print(A[i][j] + " ");
        }
        System.out.println();
      }
    }
  }
}

Output

Enter size of the Array : 5
Enter first character : @
Enter second character : *
Enter third character : #

Output : 

# @ @ @ # 
* # @ # * 
* * # * * 
* # @ # * 
# @ @ @ # 

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to create a matrix and fill it with p... >>
<< Java program to read and print a two dimensional a...