Home > other >  Why am I getting this error while executing the C code
Why am I getting this error while executing the C code

Time:07-02

In the code below, the compiler is giving the error "does not name a type" for all the three variables, l, mid, and h. I am not sure why. Any help would be appreciated;

#include <stdio.h>
#include <iostream>
#include <vector>

using namespace std;

int Binary_search(vector<int> AA,int key);

    int l, mid, h;
    l = 0;
    h = AA.size()-1;
    mid = (l h)/2;
    
    while (l <= h) {
        
        //int mid = (l h)/2;

        if (key = AA.at(mid)) 
            return mid;
        
        else if (key > AA.at(mid)) {
            l = mid 1;
            mid = (l h)/2;
        }
    
        else {
            h = mid-1;
            mid = (l h)/2;
        }
    }
        
    return -1;
    }

int main(int argc, char **argv)
{
    vector<int> A= {4,8,10,15,18,21,24,27,29,33,34,37,39,41,43};
    
    int target_index = Binary_search(A, 15);
    
    cout << target_index;
    
    return 0;
}

enter image description here

CodePudding user response:

Function Binary_search() is not defind in your code. You have declared the function like mentioned below

int Binary_search(vector AA,int key); //this is function decleration not definition

instead you should put the below statement

int Binary_search(vector AA,int key) {

it will work

CodePudding user response:

An honest mistake. Replace the ; on line 7 with a { and your code should work fine.

  • Related