Octal to Decimal Conversion ISC 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.

import java.io.*;
class ToDecimal{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int a[][];
        int m;
        int n;
        System.out.print("M = ");
        m = Integer.parseInt(br.readLine());
        System.out.print("N = ");
        n = Integer.parseInt(br.readLine());
        if(m < 1 || m > 9 || n < 3 || n > 5){
            System.out.println("Out of range.");
            return;
        }
        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(br.readLine());
                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 Equivalent:");
        for(int i = 0; i < m; i++){
            int d = 0;
            int p = n - 1;
            for(int j = 0; j < n; j++){
                d += a[i][j] * (int)Math.pow(8, p);
                p--;
            }
            System.out.println(d);
        }
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.