[Solved] array 1D i need to ask the user to check index and print value


As a simple example you can declare a boolean variable so inside loop if the value at least found once then assign it true otherwise if the loop returns and the value not found then inform the user that search not found.

Also you do not need an inner loop only one loop and input the search value outside the loop.

Also if you need the string comment mark in your string text you must precede it with backslash: “Hello there \”how are you?” otherwise the compiler thinks the string ends at the first double-quoted comma: “Hello there” then how are you undeclared identifier.

The program can look like:

int x;
bool isFound  = false;
int array[31] = {13, 99, 6, 76, 11, 83, 27, 84, 28, 67, 66, 22, 96, 46, 63, 21, 65, 48, 8, 14 , 84, 22, 28, 11, 83, 87, 11, 76, 6, 83, 27};

cout << "enter the number to locate in array";
cin >> x;

for(int i = 0; i < 31; i++){ //here: don't write i <= 31
    if(array[i] == x){
        isFound = true;
        cout << x << " found at: " << i << endl;
    }
}

if(!isFound)
    cout << "The value doesn't exist in the array!" << endl;
  • Arrays are indexed from 0 to n - 1 not n so if you write array[n] is an Undefined behavior Because the memory doesn’t belong to it.

solved array 1D i need to ask the user to check index and print value