循环条件的顺序搜索数组

时间:2019-01-02 04:47:13

标签: c++ arrays

如果未给出顺序搜索中的数组长度,并且存在很多乱序索引,则

  1. 我们应该执行for循环多少次?
  2. for循环的条件是什么?

我一遍又一遍地数了索引。

name

用于顺序搜索中未知长度数组的循环条件

1 个答案:

答案 0 :(得分:0)

使用sizeof(array)/sizeof(array[0])将为您提供数组中元素的数量,

#include <iostream>
using namespace std;
int main() {
    int array[] = {10,  20, 30, 40, 50, 60, 70, 80, 90, 100, 200,
                   300, 400, 5006, 110, 550, 440, 330, 331, 41};

    // length of array is not provided

    int i, n, loc = -1;
    cout << "Enter value to find" << endl;
    cin >> n;
    for (i = 0; i < sizeof(array) / sizeof(array[0]); i++) {
        if (array[i] == n) {
            loc = i;
        }
    }
    if (loc == -1)
    cout << "Number is not found in array" << endl;
    else
    cout << "the number is found at position " << loc << " and is " << n;
    return 0;
}

请注意,using namespace std; is considered bad practice`