0

how to search a specific number within array

Hi guys, please take a look at my code and tell me whats wrong, i wanna give the user input to search weather that number is available inside the random numbers or not. #include <iostream> #include <cstdlib> #include <time.h> //included for srand(time(NULL)) using namespace std; int main() { int input; int number; int row = 0; int col = 0; int Array[12]; srand(time(NULL)); //PrintArray for (row = 0; row < 12; row++) { { Array[row] = rand() % (100 - 0) + 0; } cout << Array[row] << "\t"; } cout << "" << endl << endl; cout << "--------------------------------------------------------------------------------" << endl << endl; int numberSearch,numbersToEnter; cout << "Enter Number Between 0-99 To Search In The Array: "; cin >> numberSearch; for(int i=0; i<numberSearch; i++) { if (numberSearch == Array[12]) { cout << "The number you searched is: " << numberSearch << endl; cout << "The number is in the array\n"; } } }

18th Jul 2018, 10:11 AM
AMANULLAH
AMANULLAH - avatar
4 Answers
0
If I understood correctly, you want to let the user enter a number and look if that number is in a randomly filled array. In that case you should loop over the entire array, but your condition is to loop over the array by the number the user entered. E.g. if a user entered 0, you wouldn't even search for it. Instead, you can use the size of the array. Next, the if-condition is weird. Array[12] is out of the array's bounds, why compare it to the user input? Instead compare to the current element. As for next time, please provide a link to your code instead of copying the text, that is easier ;) Corrected version: https://code.sololearn.com/cp3avgOrO9qr/?ref=app
18th Jul 2018, 10:40 AM
Shadow
Shadow - avatar
+ 1
thank you sir, yes this is what i want, In code that you given if i put a number which isn't among those numbers then program stops working why ?. thank you and i will provide link after this...
18th Jul 2018, 10:48 AM
AMANULLAH
AMANULLAH - avatar
+ 1
ok problem solved. thanks alot Naitomea :)
18th Jul 2018, 10:58 AM
AMANULLAH
AMANULLAH - avatar
+ 1
No problem, Amanullah, glad I could help. If you want the code to go on, you could wrap it inside a do-while-loop or something.
18th Jul 2018, 11:00 AM
Shadow
Shadow - avatar