C program that creates an identity matrix. write a C program that fills creates
ID: 3745865 • Letter: C
Question
C program that creates an identity matrix.
write a C program that fills creates an identity matrix. (An identity matrix is a square matrix that has all l's on the diagonal.) l. Example of a 5 by 5 identity matrix: 10000 01000 00100 00010 0000 1 a. b. Use conventional array accessing methods to create a 5 by 5 identity matrix. Use the pointer/addressing methods discussed in the chapter to display the matrix 1. Display it two ways: 1. 2. Row by row - just like we did in class Column by column - When you do this, you will have to skip an entire row each time you display a number. Use pointer/addressing methods to the first and last rows of the identity matrix c. 1. Make sure and use an array of pointers here, i.e. int *myRows[5] Make the exchange similar to what we did in class d. Write out the result; it should appear as below: 00001 01000 00100 00010 10000Explanation / Answer
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define N 5
int main()
{
// declaration of 2-D array
int identity_matrix[N][N];
// now part (a) use conventional array accessing method to create a 5*5 identity matrix
// run two loops to create identity matrix
// creation
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
if(i==j)
identity_matrix[i][j] = 1; // diagonal elements
else
identity_matrix[i][j] = (i+2*j); //non-diagonal elements
}
}
// now part (b) : using pointer/addressing method to display the matrix
//dispaly
// row by row
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
printf("%d ",*(*(identity_matrix+i)+j)); // *arr gives base address of 1st row, (arr+i) gives base address of ith row, *(*(arr+i)+j) - gives jth element in ith row;
}
printf(" ");
}
// column by column
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
printf("%d ",*(*(identity_matrix+j)+i)); // *arr gives base address of 1st row, *(*(arr+j)+i) - gives ith element in jth column;
}
printf(" ");
}
// now part (c) : using pointer/addressing method exchange 1st and 5th row of matrix
// swapping 1st and 5th row
for(int i=0; i<N; i++){
int temp = *(*(identity_matrix+0)+i); // value at 1st row and ith column
*(*(identity_matrix+0)+i) = *(*(identity_matrix+4)+i); //assigned value at 5th row and ith column at 1st row and ith column
*(*(identity_matrix+4)+i) = temp;
}
printf(" ");
// now part (d) : display the changes;
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
printf("%d ",*(*(identity_matrix+i)+j)); // *arr gives base address of 1st row, (arr+i) gives base address of ith row, *(*(arr+i)+j) - gives jth element in ith row;
}
printf(" ");
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.