C++ Matrix Multiplication Sample Code

C++ Matrix Multiplication Sample Code

Created By: Debasis Das (6-Feb-2016)


//  main.cpp
//  MatrixMultiplications
//  Created by Debasis Das on 05/02/16.
//  Copyright © 2016 Knowstack. All rights reserved.

#include <iostream>
#include <stdlib.h>


using namespace std;

int main(int argc, const char * argv[]) {
   
    std::cout << "Hello, World!\n";


    int a[3][4] = {
        {0, 1, 2, 3} ,
        {4, 5, 6, 7} ,
        {8, 9, 10, 11}
    };
    
    int b[4][3] = {
        {0, 1, 2} ,
        {4, 5, 6} ,
        {4, 5, 6} ,
        {8, 9, 11}
    };
    
    int a_rows = sizeof(a)/sizeof(a[0]);
    int a_cols = sizeof(a[0])/sizeof(a[0][0]);
    cout << "Number of rows in array a = "<< a_rows << "\n";
    cout << "Number of cols in array a = "<<  a_cols<< "\n";
    
    
    int b_rows = sizeof(b)/sizeof(b[0]);
    int b_cols = sizeof(b[0])/sizeof(b[0][0]);
    cout << "Number of rows in array b = "<<  b_rows << "\n";
    cout << "Number of cols in array b = "<<  b_cols << "\n";
    
    if (a_cols == b_rows){
        cout << "\nThe number of cols in the first array is same as the number of rows in the second array, \nThe multiplication is possible\n";
        //initialize the final array
        int c[a_rows][b_cols];
        int i, j,k;
        for (i=0;i<a_rows; i++){
            for (j=0;j<b_cols;j++){
                c[i][j]=0;
                for (k=0;k<b_rows;k++){
                    c[i][j] = c[i][j]+a[i][k]*b[k][j];
                }
            }
        }
        cout << "\nthe final array has been created\n\n";
        cout << "time to see the results \n";
        
       for(i=0;i<a_rows;i++)
        {
            for(j=0;j<b_cols;j++)
            {
                cout<<"\t"<<c[i][j];
            }
            cout<<"\n\n";
        }
    }
    else{
        cout << "Multiplication of the two array is not possible";
    }
    return 0;
}

Output of the sample code

Hello, World!
Number of rows in array a = 3
Number of cols in array a = 4
Number of rows in array b = 4
Number of cols in array b = 3

The number of cols in the first array is same as the number of rows in the second array, 
The multiplication is possible

the final array has been created

time to see the results 
	36	42	51

	100	122	151

	164	202	251

Program ended with exit code: 0
Posted in C++ Tagged with: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news