Multiply Arrays using Dynamic Allocation

To understand this code problem you many need to study.

  • Matrices Multiplication
  • Pointers
  • Dynamic Memory Allocation

Multiply Arrays using Dynamic Allocation Problem

Multiply arrays of multi-dimension. Array dimension will be specify at run time(hint: use dynamic allocation concept).

CODE

//Lab Task 2 Multiplication of arrays at runtime

#include<iostream>
using namespace std;
void main()
{
	//Array 1 Initilizing
	int x,y; 
	int **a;
	cout<<"Array 1 Rows = ";
	cin>>x;
	cout<<"Array 1 Columns = ";
	cin>>y;
	a= new int *[x];
    for(int i=0;i<x;i++)
				a[i] = new int [y];

	cout<<"Enter the Elements of Array 1"<<endl;
	//Input Array 1
	for(int j=0;j<x; j++)
	{
		for(int k=0; k<y;k++)
		{
			cout<<"Array 1 Element = ";
			cin>>a[j][k];
		}
	}

	//Array 2 Intializing
	int q,p; 
	int **b;
	cout<<"Array 2 Rows = ";
	cin>>q;
	cout<<"Array 2 Columns = ";
	cin>>p;
	b= new int *[q];
	int **c;  // array 3 double pointer
	c = new int * [];
    for(int i=0;i<x;i++)
	{
		b[i] = new int [p];
		c[i] = new int [p]; //array 3 coulumn index	
	}
	cout<<"Enter the Elements of Array 2"<<endl;
	//Input Array 2
	for(int j=0;j<x; j++)
	{
		for(int k=0; k<y;k++)
		{
			cout<<"Array 2 Element = ";
			cin>>b[j][k];
		}
	}

	if(y != q){
		    cout<<"Matrix lenth is not good multiplication not possible";
	}else
	{

		for(int i=0;i<x;i++)
		{
		for(int j=0;j<y;j++)
		{
			c[i][j]=0;
			for(int k=0;k<2;k++)
			{
			c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
			}
		}
	}
	
   //output
	for(int i=0;i<x;i++)
	{
		cout<<"[ ";
		for(int j=0;j<p;j++)
	{
		cout<<c[i][j]<<" ";
	}
		cout<<"]"<<endl;
	}

	}//else end
	system("pause");
}

Let's Discuss