You are on page 1of 6

DAA LAB ASSIGNMENT

LAB EXPERIMENT – 4
Name:- Mugdha

Registration Number :- 20BPS1095

Questions for In-lab Practice Session (IPS)

1.Translate the naive (brute force) algorithm for multiplying two matrices into
a C++ program. Assume the first matrix X has dimensions p x q and the second
matrix Y has dimensions q x r. Compute the product matrix Z = X* Y.

CODE:-

#include <iostream>
using namespace std;
int main(){
int p,q,r;
cout<<"Enter the dimensions of matrix A: "<<" ";
cin>>p>>q;
cout<<"Enter the dimensions of matrix B: "<<" ";
cin>>q>>r;
int A[p][q], B[q][r], C[p][r];
cout<<"Enter elements for matrix A: "<<endl;
for(int i = 0; i < p ;i++){
for(int j = 0; j < q ;j++){
cin>>A[i][j];
}
}
cout<<"Enter elements for matrix B: "<<endl;
for(int i = 0; i < p ;i++)
{
for(int j = 0; j < q ;j++){
cin>>B[i][j];
}
}
for(int i = 0; i < p; i++){
for(int j = 0; j < q ;j++){
C[i][j] = 0;
for(int k = 0; k < r ;k++){
C[i][j] += A[i][j] * B[j][k];
}
}
}
cout<<"After Multiplication, The elements for matrix C: "<<endl;
for(int i = 0; i < p ;i++){
for(int j = 0; j < r ;j++){
cout<<C[i][j]<<" ";
}
cout<<"\n";
}
}
OUTPUT:-
Questions for Lab Practice Sheet (LPS)

1. For the program in question 1 assume that both the matrices are of same
dimension, having n rows and n columns. Compute the running time T1(P) of
the brute force program for matrix multiplication for different values of n and
record it in a table. Here T1(n) is the complexity of the naive (brute force)
matrix multiplication algorithm. T1(n)=n^3

CODE:-
#include <iostream>
#include <bits/stdc++.h>
#include <cstdlib>
#include <sys/time.h>
using namespace std;
void multiplicationbfp(int n){
int Q[n][n], W[n][n], C[n][n];
for(int i = 0; i < n ;i++){
for(int j = 0; j < n ;j++){
Q[i][j] = 1;
}
}
for(int i = 0; i < n ;i++)
{ for(int j = 0; j < n ;j+
+){ W[i][j] = 1;
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n ;j++){
C[i][j] = 0;
for(int k = 0; k < n ;k++){
C[i][j] += Q[i][j] * W[j][k];
}
}
}
}
int main(){
srand((unsigned) time(NULL));
int n = 1, count;
int size[5];
int tn[5];
float tp[5];
for(count = 1; count <= 5 ; count++){
n = 10 * count;
size[count-1] = n;
tn[count-1] = n * n * n;
//naive problem
struct timeval start1, end1;
// start timer.
gettimeofday(&start1, NULL);
// unsync the I/O of C++.
ios_base::sync_with_stdio(false);
multiplicationbfp(n);
// stop timer.
gettimeofday(&end1, NULL);
// Calculating total time taken by the program.
double time_taken1;
time_taken1 = (end1.tv_sec - start1.tv_sec) * 1e6;
time_taken1 = (time_taken1 + (end1.tv_usec - start1.tv_usec)) * 1e-6;
tp[count-1] = time_taken1;
}

cout<<"S.No."<<"\t"<<"Size(n)"<<"\t\t"<<"T1(n)"<<"\t\t"<<"T1(p)"<<endl;
for(int i = 0 ; i < 5 ;i++){ printf("%d\t%d\t\t%d\t\t%f\n",
(i+1),size[i], tn[i], tp[i]);
}
}

You might also like