This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Wednesday, March 15, 2023

Write a program to read a matrix of size m x n from the keyboard and display the same on the screen using functions.

  here's a program that reads a matrix of size m x n from the keyboard and displays it on the screen using functions:

#include <iostream>
using namespace std;
// Function to read matrix of size m x n from the keyboard
void read_matrix(int m, int n, int matrix[][]) {
    cout << "Enter the elements of the matrix:" << endl;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cin >> matrix[i][j];
        }
    }
}
// Function to display matrix of size m x n on the screen
void display_matrix(int m, int n, int matrix[][]) {
    cout << "The matrix is:" << endl;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
}
int main() {
    int m, n, matrix[100][100];
    cout << "Enter the size of the matrix (m x n): ";
    cin >> m >> n;
    read_matrix(m, n, matrix);
    display_matrix(m, n, matrix);
    return 0;
}

In this program, we first define two functions read_matrix() and display_matrix() which take in the size of the matrix (m and n) and the matrix itself (matrix) as arguments.

The read_matrix() function prompts the user to enter the elements of the matrix, and then reads them in using nested for-loops.

The display_matrix() function prints the matrix on the screen, again using nested for-loops.

In the main() function, we first prompt the user to enter the size of the matrix, and then call the read_matrix() and display_matrix() functions to read in and display the matrix, respectively.

Here's an example output of the program:

Enter the size of the matrix (m x n): 3 4
Enter the elements of the matrix:
1 2 3 4
5 6 7 8
9 10 11 12
The matrix is:
1       2       3       4
5       6       7       8
9       10      11      12

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget