How to create a C++ program that searches the value of an array? Using sequential search.

This is a binary search and I want it to change it into sequential search of an array. So how can I change it?

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace std;
int main()
{
  const int arraySize = 5;
  int target;
  // Array size and values already known.
  int array[arraySize] = {1, 2, 3, 4, 5};
  int first, mid, last;
  cout << "Enter a target to be found: ";
  cin >> target;
  
  // Initialize first and last variables.
  first = 0;
  last = 2;
  while(first <= last)
  {
    mid = (first + last)/2;
    
    if(target > array[mid])
    {
      first = mid + 1;
    }
    else if(target < array[mid])
    {
      last = mid + 1;
    }
    else
    {
      first = last + 1;
    }
  }
  // When dividing can no longer proceed you are left with the
  // middle term. If the target equal that term you are
  // successful.
  if(target == array[mid])
  {
    cout << "Target found." << endl;
  }
  else
  {
    cout << "Target not found." << endl;
  }
  return 0;
}
Last edited on

Just loop through the array index 1 by 1 checking against the target value.
Topic archived. No new replies allowed.