finding elements in an array using a function c++

13,696

Your function always returns in the first loop iteration. If the first element is not the one to be searched, 0 is returned immediately. The loop never enters the second iteration.

Share:
13,696
Aswin Anil
Author by

Aswin Anil

Updated on June 04, 2022

Comments

  • Aswin Anil
    Aswin Anil almost 2 years

    I am new to C++ and have just started learning functions. I have made a program to search an element in a 1-d array using a function search. But there is a logical error I can't comprehend! Is it because of the way the function is declared ?

    int pos;    
    using namespace std;
    
    int search(int *a, int size, int num);
    
    int search(int *a, int size, int num)  
    {      
        int i;    
        for(i=0; i<size; i++)    
        {    
            if(a[i]==num)    
            {
                pos=i; return 1;
            }
            else
                return 0;
        }
    }
    
    int main()
    {  
        int a[5], size, num, i;    
        system("cls");    
        cout<<"Enter size(<5) \n";
        cin>>size;
        cout<<"Enter the elements of the array \n";
        for(i=0; i<size; i++)
            cin>>a[i];
        cout<<"Enter the number to be searched \n";
        cin>>num;
        int b = search( a, size, num);
        if(b==0)
        {
            cout<<"Element not found!"; exit(0);
        }
        else
            cout<<"Element found at position "<<(pos+1);
        system("pause");
        return 0;
    }
    

    Output:

    Enter size(<5)
    
    4
    
    Enter the elements of the array
    
    4
    
    3
    
    2
    
    1
    
    Enter element to be searched
    
    4
    
    Element not found!