Array

Hi, quick question. How do you output its location? Like row 1 column 2. It's a 5 x 5 grid, random numbers from 1 - 10, user asked for what number they're searching for and prints out how many times it appeared. Then print outs the location. Thanks for any inputs

1
2
3
4
5
6
7
8
9
10
11
12
13
int countNums(int ar[][5], int size, int search) 
{
	int count = 0;
	for (int row = 0; row < 5; row++)
	{
		for (int col = 0; col < 5; col++)
		{
 			if (ar[row][col] == search)
				count++;
		}
	}
	return count;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
when looking for it..
cout << row << " "<<col;  //+ fancy printing with words and end of lines and things. 

here, 

for (int col = 0; col < 5; col++)
		{
 			if (ar[row][col] == search)
                             {
                                cout << row << " "<<col;
				count++;
                             }
		}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <random>
#include <vector>
#include <chrono>
#include <algorithm>


constexpr auto SIZE = 5;
constexpr auto low_bound = 1;
constexpr auto up_bound = 10;

int main()
{
    auto seed = std::chrono::system_clock::now().time_since_epoch().count();//seed
    std::default_random_engine dre(seed);//engine
    std::uniform_int_distribution<int> di(low_bound,up_bound);//distribution

    int data[SIZE][SIZE];
    for (size_t i = 0; i < SIZE; ++i)
    {
        std::generate(std::begin(data[i]), std::end(data[i]), [&dre, &di]{ return di(dre);});
    }

    //http://en.cppreference.com/w/cpp/algorithm/generate

    /*std::cout << "Original array: \n";
    for (const auto& elemO : data)
    {
        for (const auto& elemI : elemO)
        {
            std::cout << elemI << " ";
        }
        std::cout << "\n";
    }*/
    std::cout << "What number would you like to search by \n";
    int target{};
    std::cin >> target;
    size_t counter{};

    for (size_t i = 0; i < SIZE; ++i)
    {
        for (size_t j = 0; j < SIZE; ++j)
        {
            if (data[i][j] == target)
            {
                std::cout << "Target at location: [" << i << "," << j << "] \n";
                ++counter;
            }
        }
    }
    if(counter)std::cout << "Number of target matches: " << counter << "\n";
    if (!counter)std::cout << "Target not found \n";

}
Awesome thanks Jonnin!
Topic archived. No new replies allowed.