Write a program to add two matrices.
Example:
Input:arr[3][3]={{6,2,3},{4,3,2},{4,5,7}},brr[3][3]={{4,6,2},{2,6,1},{1,5,1}}
Output:arr[3][3]={{10,8,5},{6,9,3},{5,10,8}}
Approach:
C
#include <stdio.h>//function to add two given matrixvoid addMatrix(int arr[][3], int brr[][3], int n, int m){for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){//store the final result//in first matrixarr[i][j] = arr[i][j] + brr[i][j];}}}int main(){//first matrixint arr[][3] = {{6, 2, 3}, {4, 3, 2}, {4, 5, 7}};//second matrixint brr[][3] = {{4, 6, 2}, {2, 6, 1}, {1, 5, 1}};int n = 3, m = 3;addMatrix(arr, brr, n, m);printf("Result after add is\n");for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){printf("%d ", arr[i][j]);}printf("\n");}return 0;}//Time Complexity:O(n^2)
Java
public class MatrixAddition {public static void main(String[] args) {int matrixA[][] = { { 6, 2, 3 }, { 4, 3, 2 }, { 4, 5, 7 } };int matrixB[][] = { { 4, 6, 2 }, { 2, 6, 1 }, { 1, 5, 1 } };matrixAddition(matrixA, matrixB);printMatrix(matrixA);}private static void printMatrix(int[][] matrixA) {for (int i = 0; i < matrixA.length; i++) {for (int j = 0; j < matrixA.length; j++) {System.out.print(matrixA[i][j] + " ");}System.out.println();}}private static void matrixAddition(int[][] matrixA, int[][] matrixB) {for (int i = 0; i < matrixB.length; i++) {for (int j = 0; j < matrixB.length; j++) {matrixA[i][j] = matrixA[i][j] + matrixB[i][j];}}}}// Time complexity : O(n^2)// Space Complexity : O(1)
C++
#include <bits/stdc++.h>using namespace std;//function to add two given matrixvoid addMatrix(int arr[][3],int brr[][3],int n,int m){for(int i=0;i<n;i++){for(int j=0;j<m;j++){//store the final result//in first matrixarr[i][j]=arr[i][j]+brr[i][j];}}}int main(){//first matrixint arr[][3]={{6,2,3},{4,3,2},{4,5,7}};//second matrixint brr[][3]={{4,6,2},{2,6,1},{1,5,1}};int n=3,m=3;addMatrix(arr,brr,n,m);cout<<"Result after add is\n";for(int i=0;i<n;i++){for(int j=0;j<m;j++)cout<<arr[i][j]<<" ";cout<<"\n";}return 0;}//Time Complexity:O(n^2)
No comments:
Post a Comment