• There are many examples in the textbook of matrices printed out in a neat form
ID: 3677478 • Letter: #
Question
• There are many examples in the textbook of matrices printed out in a neat format with rows and columns. Write a function which takes one argument, a matrix, and prints it out neatly in rows and columns. Note that this function returns nothing. Hint: use loop statement(s) and fprintf with a specified field width* that works for the test cases; Use the rand function to generate test cases of relatively small size, with one being square and one being non-square. (* For the function to be really useful it would be necessary to make it work for very large and small numbers, and to handle matrices with more columns than fit across the width of the screen, but these issues will be ignored in this problem.)
Explanation / Answer
#include<iostream>
#include<stdlib.h>
#include<cstdio>
#define R 4
#define C 3
using namespace std;
void printMatrix(int matrix[R][C]){
for(int i=0; i<R; i++){
for(int j=0; j<C; j++)
fprintf(stdout, "%.2d ", matrix[i][j]);
fprintf(stdout," ");
}
}
int main(){
int matrix[R][C];
for(int i=0; i<R; i++){
for(int j=0; j<C; j++)
matrix[i][j] = rand()%20 +1; // random number in range [1-20]
}
printMatrix(matrix);
return 0;
}
/*
I have defined value of R and C, you can change value of R and C, and test for different cases.
output:
04 07 18
16 14 16
07 13 10
02 03 08
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.