KnowledgeBoat Logo

Computer Science

Write a program to create a double dimensional array of size n x m. Input the numbers in first (n-1) x (m-1) cells. Find and place the sum of each row and each column in corresponding cells of last column and last row respectively. Finally, display the array elements along with the sum of rows and columns.

Sample Input

10151618 
15141211 
11121617 
12101416 
     

Sample Output

1015161859
1514121152
1112161756
1210141652
48515862 

Java

Java Arrays

8 Likes

Answer

import java.util.Scanner;

public class KboatDDASum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number of rows (n): ");
        int n = in.nextInt();
        System.out.print("Enter number of columns (m): ");
        int m = in.nextInt();

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

        System.out.println("Enter array elements");
        for (int i = 0; i < n - 1; i++) {
            System.out.println("Enter Row "+ (i+1) + " :");
            for (int j = 0; j < m - 1; j++) {
                arr[i][j] = in.nextInt();
            }
        }

        System.out.println("Input Array:");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }

        //Row-wise & Column-wise Sum
        for (int i = 0; i < n - 1; i++) {
            int rSum = 0, cSum = 0;
            for (int j = 0; j < m - 1; j++) {
                rSum += arr[i][j];
                cSum += arr[j][i];
            }
            arr[i][m - 1] = rSum;
            arr[n - 1][i] = cSum;
        }

        System.out.println("Array with Sum:");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Output

BlueJ output of Write a program to create a double dimensional array of size n x m. Input the numbers in first (n-1) x (m-1) cells. Find and place the sum of each row and each column in corresponding cells of last column and last row respectively. Finally, display the array elements along with the sum of rows and columns. Sample Input Sample Output

Answered By

4 Likes


Related Questions