I am currently writing a program for an assignment in data structures class. The assignment says "Write a program that
fills a 5 x 5 matrix of integers. The matrix must be a static matrix; its size must be fixed at
compile-time. Display the contents of the matrix. Query the user for an integer. Pass the matrix
and the integer to a bool function that searches for the first occurrence of the integer in the
matrix. If the integer is found, the function returns true (and passes back the row and column
coordinates of the first occurrence of the integer); if not, the function returns false. Main then
displays whether the integer was found in the matrix and if so, the coordinates of the first
occurrence. The use of break to exit a loop or a function should be avoid and will be penalized." Here is the code I have written so far.
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
|
#include <iostream>
#include <stdlib.h>
#include <ctime>
using namespace std;
int main(int argc, char const *argv[])
{
//Seed random function to generate numbers for matrix
srand(time(0));
int a[5][5], i , j, n, found = 0;
//Generates random numbers for matrix
for (i = 0; i < 5; i++)
{
for ( j = 0; j < 5; j++)
{
a[i][j]= rand() % 100 + 1;
}
} //Loop that prints numbers until it reaches 5 columns and 5 rows
for ( i = 0; i < 5; i++)
{
for ( j = 0; j < 5; j++)
{
cout << a[i][j]<< '\t';
}
cout << '\n';
}
//Boolean function to find number in matrix
bool search;
{
cout << "Enter the integer you want to search: ";
cin >> n;
if (a[i][j] == n)
{
found = 1;
}
if (found == 1)
{
cout << "Integer found at (" << i << "," << j << ")";
}
else
{
cout << "Integer could not be found";
}
}
return 0;
}
| |
The program runs fine except when searching for a value in the matrix. When I input a number even if it's in the matrix. It gives me a integer not found. Any ideas what I could have done wrong? I am still new to C++