SUNDAY, 12 JULY 2026
Guide For School logo Guide For SchoolStudy Guide For Students On Java Programming
Physics | Chemistry | Mathematics
ICSE | ISC | CBSE
Guide For School logo Guide For SchoolICSE and ISC Resources

Fill Matrix with Three Characters Program in Java and Python

30 September 2015

Fill matrix with three characters using diagonal and region logic, with algorithm, explanation, Java solution and simple Python solution for ISC students.

Question:

Given a square matrix of order n, where the maximum value of n is 10, accept three different characters. Fill the upper and lower regions formed by the diagonals with the first character, the left and right regions with the second character, and both diagonals with the third character.

Example 1 ENTER SIZE: 4 FIRST CHARACTER: * SECOND CHARACTER: ? THIRD CHARACTER: # OUTPUT: # * * # ? # # ? ? # # ? # * * # Example 2 ENTER SIZE: 65 OUTPUT: SIZE OUT OF RANGE

Algorithm:

Step 1: Start.

Step 2: Accept matrix size n.

Step 3: If n is greater than 10, display SIZE OUT OF RANGE and stop.

Step 4: Accept three characters ch1, ch2 and ch3.

Step 5: Run row loop i from 0 to n - 1.

Step 6: Run column loop j from 0 to n - 1.

Step 7: If i equals j or i + j equals n - 1, store ch3 because the position lies on a diagonal.

Step 8: Else if i is less than j and i + j is less than n - 1, or i is greater than j and i + j is greater than n - 1, store ch1 for upper/lower regions.

Step 9: Otherwise store ch2 for left/right regions.

Step 10: Display the completed matrix.

Step 11: Stop.

Explanation:

The whole solution depends on row and column indexes. The main diagonal is identified by i == j, while the opposite diagonal is identified by i + j == n - 1.

Diagonal positions are tested first because they must always receive the third character, even though they also touch the four surrounding regions.

The upper and lower regions are found by comparing row and column positions along with the opposite diagonal condition. These index comparisons tell whether a cell lies above both diagonals or below both diagonals.

All remaining non-diagonal cells belong to the left and right regions, so they receive the second character. This avoids needing a separate condition for every part of the matrix.

After every cell is assigned, nested display loops print the matrix row by row. The storage array keeps the pattern clear before output begins.

The matrix is filled according to a repeated character pattern, so the program must control both position and sequence. Nested loops visit every cell row by row. A counter or condition decides which of the three characters should be placed at the current position. After the third character is used, the sequence begins again. The logic is therefore based on cyclic repetition. Using modulus with 3 or carefully updating a character counter keeps the pattern consistent across row boundaries.

Java Program:

Java
/**
* The class MatrixFill creates a matrix using 3 characters taken as inputs
* Upper and lower elements formed by the intersection of the diagonals are filled by character 1.
* Left and right elements formed by the intersection of the diagonals are filled by character 2.
* Both the diagonals are filled by character 3.
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
* @ISC Computer Science Practical Specimen Paper - Question 2
*/

import java.util.*;
class MatrixFill
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter size of the matrix : ");
        int n = sc.nextInt();

        if(n<2 || n>10)
        System.out.println("Size out of Range");
        else
        {
            char A[][]=new char[n][n];
            System.out.print("Enter the 1st character : ");
            char c1 = sc.next().charAt(0);
            System.out.print("Enter the 2nd character : ");
            char c2 = sc.next().charAt(0);
            System.out.print("Enter the 3rd character : ");
            char c3 = sc.next().charAt(0);

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

            for(int i=0; i<n/2; i++)
            {
                for(int j=i+1; j<n-1-i; j++)
                {
                    A[i][j] = c1; // Filling the upper positions formed by intersection of diagonals
                    A[n-1-i][j] = c1; // Filling the lower positions formed by intersection of diagonals
                }
            }

            // 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();
            }
        }
    }
}

Equivalent Python Program:

Python
# Read the matrix or array size and store the values for indexed processing.
# Nested loops are used because each row/column or array position must be checked.
# Print the processed array or matrix in the required output format.

n = int(input("Enter size of the matrix: "))
if n > 10:
    print("SIZE OUT OF RANGE")
else:
    ch1 = input("Enter the 1st character: ")
    ch2 = input("Enter the 2nd character: ")
    ch3 = input("Enter the 3rd character: ")
    A = []
    for i in range(n):
        row = []
        for j in range(n):
            if i == j or i + j == n - 1:
                row.append(ch3)
            elif (i < j and i + j < n - 1) or (i > j and i + j > n - 1):
                row.append(ch1)
            else:
                row.append(ch2)
        A.append(row)
    print("OUTPUT:")
    for i in range(n):
        for j in range(n):
            print(A[i][j], end=" ")
        print()

Output:

Example 1 ENTER SIZE: 4 FIRST CHARACTER: * SECOND CHARACTER: ? THIRD CHARACTER: # OUTPUT: # * * # ? # # ? ? # # ? # * * # Example 2 ENTER SIZE: 65 OUTPUT: SIZE OUT OF RANGE

Leave a Reply

Your email address will not be published. Comments are reviewed before appearing publicly.

Send a comment or correction

Study smarter

Everything you need for ICSE and ISC Computer

Programs, revision notes, solved papers and practical guidance—organized for quick study.

Browse all resources →