Fourth: Matrix Exponentiation This program will test your ability to manage memo
ID: 3872539 • Letter: F
Question
Fourth: Matrix Exponentiation
This program will test your ability to manage memory using malloc() and provide some experience dealing with 2D arrays in C. (program in C)
Your task is to create a program that computes Mn where M is a square matrix M (the dimensions of the matrix will be k x k where k is the number of rows) and a number n 0. In summary, you need to multiply the matrix with itself n times.
Input-Output Format
The program will take the file name as input. The first line in the file will provide the number of rows in the matrix. The subsequent lines will provide the contents of the matrix. The numbers are tab separated. The last line in the file after the contents of the matrix will contain the exponent n. For example, a sample input file “file.txt”:
3
1 2 3
4 5 6
7 8 9
2
The first number (3) refers to the number of rows in the square matrix. The dimensions of the matrix will be 3x3. The exponent is 2. Hence, the program is required to compute M2 . You can assume that the input will be properly formatted. The output on executing the program with the above input is shown below.
The output numbers should be tab separated. There should not be extra tabs or spaces at the end of the line or the end of the file.
$./fourth file1.txt
30 36 42
66 81 96
102 126 150
Explanation / Answer
Here is the code for you:
#include <stdio.h>
#include <stdlib.h>
void matrixMultiplication(int **matrix, int **result, int size)
{
int temp[size][size];
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
{
temp[i][j] = 0;
for(int k = 0; k < size; k++)
temp[i][j] += matrix[i][k] * result[k][j];
}
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
result[i][j] = temp[i][j];
}
int **malloc2d(int size)
{
int i;
int **t=malloc(size*sizeof(int));
for(i=0;i<size;i++)
t[i]=malloc(size*sizeof(int));
return t;
}
int main(int argc, char* argv[]) //Pass the parameter file.txt
{
//string fileName;
if(argc != 2)
{
printf("Invalid number of arguments. ");
return 0;
}
FILE* fp = fopen(argv[1], "r");
if(fp == NULL)
{
printf("Unable to open the input file. ");
return 0;
}
int size, exp;
fscanf(fp, "%i", &size);
int **matrix = malloc2d(size);
int **result = malloc2d(size);
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
{
fscanf(fp, "%i", &matrix[i][j]);
result[i][j] = matrix[i][j];
}
fscanf(fp, "%i", &exp);
for(int i = 0; i < exp-1; i++)
matrixMultiplication(matrix, result, size);
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size-1; j++)
printf("%i ", result[i][j]);
printf("%i ", result[i][size-1]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.