Hello all... I want the multiplication of the same matrix but in third, forth, fifth... degree. I have made the C++ program and this is the code:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

#define WIDTH 3
#define HEIGHT 3

void main(){

        int a[HEIGHT][WIDTH];
        int b[HEIGHT][WIDTH];
        int n;
        for (int i = 0; i <= HEIGHT - 1; i++) {
            for (int j = 0; j <= WIDTH - 1; j++) {
                //cout << "\n Intput a[" << i << "][" << j << "]: ";
                //cin >> a[i][j];
                a[i][j]= rand()%100 + 1;
            }
            cout << "\n";
        }

        cout << "\n Before Multiplication: \n";
        for (int i = 0; i <= HEIGHT - 1; i++) {
            for (int j = 0; j <= WIDTH - 1; j++) {
                cout << a[i][j] << " ";
            }
            cout << "\n";
        }
        cout << "\n\n After multiplication: \n\n";
        int sum=0;

           for (int i = 0; i <= HEIGHT - 1; i++) {
               for (int j = 0; j <= WIDTH - 1; j++) {
                   sum=0;
                   for (int k = 0; k <= WIDTH - 1; k++) {
                       //System.out.print("a["+i+"]["+k+"] * a["+k+"]["+j+"] \n");
                       sum += a[i][k]*a[k][j];
                   }
                  b[i][j]=sum;
               }
           }


        for (int i = 0; i <= HEIGHT - 1; i++) {
            for (int j = 0; j <= WIDTH - 1; j++) {
                cout << b[i][j] << " ";
            }
            cout << "\n";
        }
}

First of all, is better to use the standard of main as an int returning function, don't use void. Second, you must read this, you are not using well the rand function (it is always showing the same numbers). And third, the way you are multiplying the matrix is ok for any size of a square matrix. If you want your matrix in the 3rd power or the 5th power do the following:

  1. Add a label to your code (#define POWER 4).
  2. Add a loop to this block:

code:

for (int i = 0; i <= HEIGHT - 1; i++) {
    for (int j = 0; j <= WIDTH - 1; j++) {
        sum=0;
        for (int k = 0; k <= WIDTH - 1; k++) {
            //printf("a[%d][%d] * a[%d][%d] = %d * %d\n",i,k,k,j,a[i][k],a[k][j]);
            sum += a[i][k]*a[k][j];
        }
        b[i][j]=sum;
    }
}

This loop must be repeated the power amount minus one times.

TIP: use srand function to initialize the random seed.

Edited 3 Years Ago by mike_2000_17: fixed format

This article has been dead for over six months. Start a new discussion instead.