M
M
Mag1str2021-06-18 16:33:56
C++ / C#
Mag1str, 2021-06-18 16:33:56

How to find a specific number in a matrix?

I have a code that is looking for the maximum number, and I need it to display the number X, which I recognize myself.

#include <iostream>
#include <ctime>
using namespace std;
 
void main()
{
    srand((unsigned)time(0));
    setlocale(LC_ALL, "rus");
    int n, m;
    cout << "Введите кол-во строк, столбцов: ";
    cin >> n >> m;
    int **arr = new int*[n]();
    for (int i = 0; i < n; i++)
    {
        arr[i] = new int[m]();
    }
    //--
    int max = arr[0][0],
        maxi = 0, maxj = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            arr[i][j] = rand() % 50 + 1;
            if (arr[i][j] > max)
            {
                max = arr[i][j];
                maxi = i;
                maxj = j;
            }
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl << "Максимальный элемент - " << max << "[" << maxi+1 << "][" << maxj+1 << "]" << endl;
    //--
    for (int i = 0; i < n; i++)
    {
        delete[] arr[i];
    }
    delete[] arr;
    system("pause");
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mag1str, 2021-06-18
@Mag1str

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
    srand(time(NULL));
    setlocale(LC_ALL, "rus");
    int n, m;
    cout << "Введите кол-во строк, столбцов: ";
    cin >> n >> m;
    int **arr = new int*[n];
    for (int i = 0; i < n; i++){
        arr[i] = new int[m];
    }
    bool flag = false;
    int number, maxi = 0, maxj = 0;
    for (int i = 0; i < n; i++){
        for (int j = 0; j < m; j++){
            arr[i][j] = rand() % 50 + 1;
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    cout <<"Введте число которое ищете: ";
    cin >> number;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            if (number == arr[i][j]){
                flag = true;
                number = arr[i][j];
                maxi = i;
                maxj = j;
            }
        }
    }
    cout << endl << "Запрашиваемый вами элемент - " << number << "[" << maxi+1 << "][" << maxj+1 << "]" << endl;
    for (int i = 0; i < n; i++){
        delete[] arr[i];
    }
    delete[] arr;
    return 0;
}

L
LoliDeveloper, 2021-06-18
@LoliDeveloper

Something like this
std::cout << *(*(arr + i)+j);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question