1

If length of array in sequential search is not given and there is a lot of out of order indexing,

  1. how many times we should execute the for loop?
  2. what should be the condition of for loop?

I counted indexing again and again.

#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 < 5; 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;
}

For loop Condition for unknown length array in sequential search

William Miller
  • 9,839
  • 3
  • 25
  • 46
Sami Ullah
  • 13
  • 3
  • 1
    `for (i = 0; i < sizeof array / sizeof *array; i++)` – Sid S Jan 02 '19 at 04:50
  • 5
    Possible duplicate of [How do I find the length of an array?](https://stackoverflow.com/questions/4108313/how-do-i-find-the-length-of-an-array) –  Jan 02 '19 at 04:50
  • Arrays *never* have an unknown length, all arrays will have their size fixed at compilation time. There is a (relatively) easy "trick" to get the size of an array (a *proper* array, not one that has decayed to a pointer): Dividing the size of the whole array with the size of a single element. Like (in your case) `sizeof array / sizeof array[0]`. – Some programmer dude Jan 02 '19 at 04:51
  • `main` must have a return type and it must be `int`. –  Jan 02 '19 at 04:51

1 Answers1

0

You can extract the size of an array using std::size()

int array[] = {10,  20, 30, 40, 50, 60, 70, 80, 90, 100, 200,
               300, 400, 5006, 110, 550, 440, 330, 331, 41};
int arraySize = std::size(array);

// Now you can iterate over the array with:

for (int loop = 0; loop < arraySize; ++loop) {
    if (array[loop] == n) {
        loc = loop;
    }
}
Martin York
  • 257,169
  • 86
  • 333
  • 562