0% found this document useful (0 votes)
220 views3 pages

Quetion 19

Uploaded by

thanushree77777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
220 views3 pages

Quetion 19

Uploaded by

thanushree77777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Quetion 19:

Write a program to declare a Square Matrixx a[][] of order m*n where M is the number of rows
and N is the number of columns such that ‘m’ and ‘n’ both must be greater than 2 and less than
10, Accept the values of m and n as user input.
Fill a Matrixx of size M into in in a spiral (or circular) fashion (clockwise) with natural numbers
from 1 to m*n.
Input: m=4, n=4
Output:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

Input: m=3 ,n=4


Output:
1 2 3 4
10 11 12 5
9 8 7 6

Program 19: Code:


import java.util.Scanner;
class r19
{
public static void main()
{
Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of rows (3-9): ");


int m = sc.nextInt();

System.out.print("Enter the number of columns (3-9): ");


int n = sc.nextInt();

if (m < 3 || m > 9 || n < 3 || n > 9) {


System.out.println("Invalid input. The number of rows and columns must be between 3
and 9.");
return;
}

int[][] a = new int[m][n];


int value = 1; // Initialize the value to be filled in the matrix
int top = 0, bottom = m - 1, left = 0, right = n - 1;

while (value <= m * n)


{
// Fill top row
for (int i = left; i <= right && value <= m * n; i++)
{
a[top][i] = value++;
}
top++;// Move the top boundary down
// Fill right column
for (int i = top; i <= bottom && value <= m * n; i++)
{ a[i][right] = value++;
}
right--; // Move the right boundary left
// Fill bottom row
for (int i = right; i >= left && value <= m * n; i--)
{
a[bottom][i] = value++;
}
bottom--;// Move the bottom boundary up
// Fill left column
for (int i = bottom; i >= top && value <= m * n; i--)
{
a[i][left] = value++;
}
left++;// Move the left boundary right
}

System.out.println("Spiral Matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
}
Program 19: Variable Description:
Variable Data type Purpose
a[] int Array variBLE
m int Number of rows
n int Number of columns
value int Value to be filled in the matrix
top int To fill top row
bottom int To fill bottom row
rigth int To fill ritgh column
left int To fill left column
i,j int Loop variables

Program 19: Output:

You might also like