Write a program to declare a matrix A[][] of order (M × N) where ‘M’ is the number of rows and ‘N’ is the number of columns such that both M and N must be greater than 2 and less than 10. Allow the user to input integers into this matrix. Display appropriate error message for an invalid input.
Perform the following tasks on the matrix:
(a) Display the input matrix.
(b) Rotate the matrix by 270° anticlockwise and display the resultant matrix.
(c) Calculate the sum of the odd elements of the matrix and display.
Test your program for the following data and some random data:
Example 1
INPUT:
M = 3
N = 4
ENTER ELEMENTS: 8, 7, 9, 3, -2, 0, 4, 5, 1, 3, 6, -4
OUTPUT:
ORIGINAL MATRIX
8 | 7 | 9 | 3 |
-2 | 0 | 4 | 5 |
1 | 3 | 6 | -4 |
ROTATED MATRIX (270° ANTICLOCKWISE)
1 | -2 | 8 |
3 | 0 | 7 |
6 | 4 | 9 |
-4 | 5 | 3 |
SUM OF THE ODD ELEMENTS = 28
Example 2
INPUT:
M = 3
N = 2
OUTPUT: INVALID INPUT
Example 3
INPUT:
M = 2
N = 10
OUTPUT: INVALID INPUT
import java.util.Scanner;
class Rotate{
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.print("M = ");
int m=Integer.parseInt(in.nextLine());
System.out.print("N = ");
int n=Integer.parseInt(in.nextLine());
if(m<3 || n<3 || m>9 || n>9){
System.out.println("Invalid Input");
return;
}
int a[][]=new int[m][n];
int b[][]= new int[n][m];
int sum=0;
System.out.println("ENTER ELEMENTS:");
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
a[i][j]=Integer.parseInt(in.nextLine());
if(a[i][j]%2!=0)
sum+=a[i][j];
}
}
System.out.println("ORIGINAL MATRIX :");
display(a,m,n);
int q=0;
for(int i=m-1;i>=0;i--){
int p=0;
for(int j=0;j<n;j++){
b[p][q]=a[i][j];
p++;
}
q++;
}
System.out.println("ROTATED MATRIX BY 270 DEGREES ANTICLOCKWISE");
display(b,n,m);
System.out.println("SUM OF THE ODD ELEMENTS = " + sum);
}
public static void display(int a[][], int m, int n){
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
System.out.print(a[i][j]+ "\t");
}
System.out.println();
}
}
}
we can use simply if suppose vector of res [i][j]=matrix(a[j][n-i-1]) for 270