2D Arrays

Hi there. I am having trouble with the function countNums. I need to make it so when the user enters a specific number, not only will it output how many numbers there are in the array but also it should output how many numbers the user input there are in the row and column. For instance, if the user enters 3 and there are total of 4 numbers in the array, it should output something like this: col: 2, row: 2.

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
55
56
57
#include <iostream>

using namespace std;

void fillArray(int ar[][5], int size);
void printArray(int ar[][5], int size);
int countNums(int ar[][5], int size, int search);

int main()
{
	int ar[5][5];

	fillArray(ar, 5);
	printArray(ar, 5);

	int num;
	cout << "What number do you want to search for?" << endl;
	cin >> num;
	int count = countNums(ar, 5, num);
	cout << "Your number appears " << count << " times in the array" << endl;

	return 0;
}
void fillArray(int a[][5], int size)
{
	for (int row = 0; row < 5; row++)
	{
		for (int col = 0; col < 5; col++)
		{
			a[row][col] = rand() % 10 + 1;
		}
	} 
}
void printArray(int a[][5], int size)
{
	for (int row = 0; row < 5; row++)
	{
		for (int col = 0; col < 5; col++)
		{
			cout << a[row][col] << "\t";
		}
		cout << endl;
	}
}
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[col][row] == search)
				count++;
		}
	}
}
Declare 2 additional arrays:
1
2
int rowCounter[5]{};//array elements initialized to 0
int colCounter[5]{};


then within the check and count loop update these arrays as well:
1
2
3
4
5
6
7
8
9
10
11
12
for (int row = 0; row < 5; row++)
	{
		for (int col = 0; col < 5; col++)
		{
			if (ar[col][row] == search)
			{
				count++;
				++rowCounter[row];
				++colCounter[col];
			}
		}
	}

countNums() currently returns int, edit the function accordingly to return all the required information

ps: as you are not seeding the random number generator, the program will return the same sequence of 'random' numbers every time it's run. For non-repeated sequences:
1
2
3
4
5
6
7
8
#include <ctime>
//...
int main()
{
//....
srand (time(NULL));//before calling fillArray() && only once in the program
//...
}

pps: using the random header file (C++11) gives better quality random numbers
Last edited on
Topic archived. No new replies allowed.