2D Arrays Help

For this 2D array, I was asked to search for a number. Once found I needed to output its location. Could someone explain to me how would I find the number's index location.

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
58
59
60
61
#include <iostream>
using namespace std;

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

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

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

	cout << "What number do you want to search for? " << endl;
	int num;
	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[row][col] == search)
				count++;
			
		}
	}
	return count;
}
@besurk

1
2
3
4
5
6
7
8
9
10
11
12
for (int row = 0; row < size; row++) // May as well use the variable sent to the function
{
	for (int col = 0; col < size; col++)
	{
		if (ar[row][col] == search)
			{
                                count++;
			         cout << search << " found at array location [" << row << "]["<< col <<"]"<< endl;
                          }
	}
}
	return count;
Last edited on
Upon implementing this code, It outputted all locations for the 25 numbers in the array. Any ideas?
@besurk

Did you remember to add the parenthesis' around count++ and the cout statement?. If yes, then please post your countNums function
Awh, yes. I was missing the braces in the if statement. Thank you
Topic archived. No new replies allowed.