Octal Matrix ISC Computer Science 2020 Practical
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 the value of 'M' must be greater than 0 and less than 10 and the value of 'N' must be greater than 2 and less than 6. Allow the user to input digits (0 - 7) only at each location, such that each row represents an octal number.
Example:
2 3 1 (decimal equivalent of 1st row = 153 i.e. 2 ✕ 82 + 3 ✕ 81 + 1 ✕ 80)
4 0 5 (decimal equivalent of 2nd row = 261 i.e. 4 ✕ 82 + 0 ✕ 81 + 5 ✕ 80)
1 5 6 (decimal equivalent of 3rd row = 110 i.e. 1 ✕ 82 + 5 ✕ 81 + 6 ✕ 80)
Perform the following tasks on the matrix:
(a) Display the original matrix
(b) Calculate the decimal equivalent for each row and display as per the format given below.
Test your program for the following data and some random data:
Example 1:
INPUT:
M = 1
N = 3
ENTER ELEMENTS FOR ROW 1: 1 4 4
OUTPUT:
FILLED MATRIX
1 4 4
DECIMAL EQUIVALENT
100
Example 2:
INPUT:
M = 3
N = 4
ENTER ELEMENTS FOR ROW 1: 1 1 3 7
ENTER ELEMENTS FOR ROW 2: 2 1 0 6
ENTER ELEMENTS FOR ROW 3: 0 2 4 5
OUTPUT:
FILLED MATRIX
1 1 3 7
2 1 0 6
0 2 4 5
DECIMAL EQUIVALENT
607
1094
165
Example 3:
INPUT:
M = 3
N = 3
ENTER ELEMENTS FOR ROW 1: 2 4 8
OUTPUT:
INVALID INPUT
Example 4:
INPUT:
M = 4
N = 6
OUTPUT:
OUT OF RANGE
class Octal{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int m;
int n;
System.out.print("M = ");
m = Integer.parseInt(in.nextLine());
System.out.print("N = ");
n = Integer.parseInt(in.nextLine());
if(m < 1 || m > 9 || n < 3 || n > 5){
System.out.println("OUT OF RANGE");
return;
}
int a[][] = new int[m][n];
for(int i = 0; i < m; i++){
System.out.println("ENTER ELEMENTS FOR ROW " + (i + 1) + ": ");
for(int j = 0; j < n; j++){
a[i][j] = Integer.parseInt(in.nextLine());
if(a[i][j] < 0 || a[i][j] > 7){
System.out.println("INVALID INPUT");
return;
}
}
}
System.out.println("FILLED MATRIX");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
System.out.println("DECIMAL MATRIX");
for(int i = 0; i < m; i++){
String s = "";
for(int j = 0; j < n; j++)
s += a[i][j];
int num = Integer.parseInt(s);
int oct = 0;
int p = 0;
while(num != 0){
oct += (num % 10) * (int)Math.pow(8, p);
p++;
num /= 10;
}
System.out.println(oct);
}
}
}
Comments
Post a Comment