Search code examples
c++visual-c++

For each row of the matrix, find the minimum element and write them into a one-dimensional array


I wrote a code to find "each row of a matrix find the minimum element and write them into a one-dimensional array". But the problem is that I call the "search_min" function, it swears "too few arguments in the function" and "the type argument (int ) is incompatible with the type parameter (int*)" What am I doing wrong?

#include <iostream>

using namespace std;

int search_min(int* arr, int size) {
    int min = arr[0];
    for (size_t i = 1; i < size; ++i) {
        if (arr[i] < min) {
            min = arr[i]; 
        }  
    }
    return min;
}

int main()
{
    setlocale(0, "rus");

    int n, m, z[100][100];
    cout << " Enter the size of the matrix: ""\n";
    cin >> n >> m;

    cout << " Fill in the matrix: ""\n";
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> z[i][j];
        }
    }

    cout << "The introduced matrix:" << endl;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cout << z[i][j] << " "; 
           
        } 
         cout << endl;
       
    }

    cout << "The minimum element of each row of the matrix:" << endl;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cout << search_min(z[i][j]);
        }
        cout << endl;
    }

    cin.get();
    return 0;
}

Solution

  • the proposed fix. You need also to make a simple loop. for testing on godbolt I removed the cin. You can add them back.

    #include <iostream>
    
    using namespace std;
    
    int search_min(int* arr, int size) {
        int min = arr[0];
        for (size_t i = 1; i < size; ++i) {
            if (arr[i] < min) {
                min = arr[i];
            }
        }
        return min;
    }
    
    int main() {
        setlocale(0, "rus");
    
        int n = 10;
        int m = 10;
        int z[100][100];
        cout << " Enter the size of the matrix: "
                "\n";
        // cin >> n >> m;
    
        cout << " Fill in the matrix: "
                "\n";
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                z[i][j] = i - j;  // just to test
            }
        }
    
        cout << "The introduced matrix:" << endl;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cout << z[i][j] << " ";
            }
            cout << endl;
        }
    
        cout << "The minimum element of each row of the matrix:" << endl;
        for (int i = 0; i < n; i++) {
            cout << search_min(z[i], m);
            cout << endl;
        }
    
        return 0;
    }
    

    Live demo