Write a C program which fills a matrix of size NxM with random integers between
ID: 3912840 • Letter: W
Question
Write a C program which fills a matrix of size NxM with random integers between 0and 100 and sorts the matrix in descending order. N and M are the numbers of rows and columns
entered by the user. The maximum number of rows and columns can be 100.Your program should implement the following functions:
void fillMatrix(int A[][],int N, int M): To generates NxM random numbers between 1 and 100 and stores them in array A.
int sortMatrix(int A[][],int rowsize, int colsize): To sort the input array
void displayMatrix(int A[][],int N, int M): To display the array elements
(N rows and M columns).
Sample Interaction:
Enter number of rows: 100
!
Enter number of rows: 3
Enter number of columns: 3
Before Sorting:
182 456 379
After Sorting:
987 654 321
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
int rows,cols;
//method to fill matrix with random number between 0-100
void fillMatrix(int A[][cols],int N, int M)
{
int i,j,r;
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
r=rand()%101;//generating random number between 0-100
if(r<0)r=r*-1;
A[i][j]=r;
}
}
}
//method to sort matrix in descending order
int sortMatrix(int A[][cols],int rowsize, int colsize)
{
int i,j,k,l,temp;//variable declaration
//sorting the matrix in descending order
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
for(k=0;k<rowsize;k++)
{
for(l=0;l<colsize;l++)
{
if(A[i][j]>A[k][l])
{
temp = A[i][j];
A[i][j]=A[k][l];
A[k][l] = temp;
}
}
}
}
}
return 0;
}
//method to display matrix
void displayMatrix(int A[][cols],int N, int M)
{
int i,j,r;
//printing matrix
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
printf("%d ",A[i][j]);
}
printf(" ");
}
}
int main()
{
//reading input
while(1)
{
printf("Enter number of rows:");
scanf("%d",&rows);
if(rows>=100)//if num greater than 100 is entered
{
printf("! ");
continue;
}
else
{
printf("Enter number of cols:");
scanf("%d",&cols);
if(cols>=100)//if num greater than 100 is entered
{
printf("! ");
continue;
}
break;
}
}
printf("Rows:%d Cols:%d ",rows,cols);
//creating matrix variable
int A[rows][cols];
//filling matrix with random numbers
fillMatrix(A,rows,cols);
printf("Before sorting: ");
displayMatrix(A,rows,cols);
sortMatrix(A,rows,cols);
printf("After sorting: ");
displayMatrix(A,rows,cols);
return 0;
}
output:
Enter number of rows:100
!
Enter number of rows:3
Enter number of cols:100
!
Enter number of rows:3
Enter number of cols:3
Rows:3
Cols:3
Before sorting:
41 85 72
38 80 69
65 68 96
After sorting:
96 85 80
72 69 68
65 41 38
Process exited normally.
Press any key to continue . . .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.