Array. How to find the location of a searched number?
I have to modify my countNums where after it searches for the number, it lists the row and column that it is included in.
I do not know how to start it.
Thanks for the help.
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
|
#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, 10, 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;
}
|
Hello piratekingluffy,
The quick solution would be to change the if statement at line 55 and add a cout to print "row" and "col".
You may also need something at the end of main to keep the window open to see what you have printed out.
http://www.cplusplus.com/forum/beginner/1988/
And BTW what is "size" used for in the "countNums" function? And why does it need t be there?
Hope that helps,
Andy
Last edited on
Why do you pass the parameter size to your functions if you don't use them?
Same in your last thread.
@Thomas1965, that was how my instructor showed it to us.
@Handy Andy, so I should just change to if statement on line 55 to a cout print?
To print the location of the found number just change
1 2
|
if (ar[row][col] == search)
count++;
|
to
1 2 3 4 5
|
if (ar[row][col] == search)
{
count++;
cout << "found " << search << " at " << "row " << row << " col " << col << "\n";
}
|
Thanks Thomas. It was such a simple solution. Thank you.
Topic archived. No new replies allowed.