sequental search cin is not working

Write your question here.
why it's not working correct. cin is not working
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
#include <iostream>

using namespace std;

const int LEN = 10;

int arr[LEN] = {4, 40, 20, 17, 25, 445, 78, 23, 91, 20};


int main(){

    int key;

    cout << "Enter key please: ";
    //cout << arr[1];
    cin >> key;// = 40;
    
    int i = 0;

    while(i < LEN){

        if (arr[i]==key ){
           cout << "We got key into array arr.\n";
        }

    }

}
Where are you planning to change i? Or are you going to leave it with the value 0, so always indexing the beginning of the array.
Last edited on
You never change i inside the loop, so it loops forever with i==0. To fix it, add i++; at line 25. Better yet, use a for loop:

1
2
3
4
5
    for (int i = 0; i < LEN; ++i) {
        if (arr[i]==key ){
           cout << "We got key into array arr.\n";
        }
    }

Or best of all, use a range-based for loop:
1
2
3
4
5
for (int val : arr) {
    if (val == key) {
           cout << "We got key into array arr.\n";
   }
}


Note that all of these solutions will keep looking for a match, even after they find one. To stop looking after finding the first match, add break; right after the cout statement.
Topic archived. No new replies allowed.