Search code examples
c++variablesreturn

How to assign return value of a function into a variable in c++?


i want to assign a returned value of a function into a Variable in C++, but the program is exit without any output.

int numberPosition = binarySearch(arr, num, searchNumber);

program output screenshot

Full code---

#include <iostream>
using namespace std;


int binarySearch(int arr[], int num, int searchNumber){
    int start=0, end=num;

    while(start<=end){
        int mid = (start+end) / 2;
        if(arr[mid] == searchNumber){
            return mid;
        }else if(arr[mid] <= searchNumber){
            start = mid+1;
        }else{
            end = mid-1;
        }
    }
    
    return -1;
}

int main(){
    
    int num, arr[num], searchNumber;
    cout<<"How many Elements u want to insert? \n";
    
    cin>>num;
    
    cout<<"\n Enter ut Numbers:- \n";
    for(int i=0; i<num; i++){
        cin>>arr[i];
    }
    
    cout<<"\n Enter the Number u want to search:- ";
    cin>>searchNumber;
    
    int numberPosition = binarySearch(arr, num, searchNumber);
    
    if(numberPosition){
        cout<<searchNumber<<" is founded at position: "<<numberPosition;
    }else{
        cout<<searchNumber<<" is Not Founded";
    }
    
    return 0;
}   

Solution

  • Here This code works. You need to declare the length of array with variable num after you have taken the input value of num.

    #include <iostream>
    using namespace std;
    
    
    int binarySearch(int arr[], int num, int searchNumber){
    int start=0, end=num;
    
    while(start<=end){
        int mid = (start+end) / 2;
        if(arr[mid] == searchNumber){
            return mid;
        }else if(arr[mid] <= searchNumber){
            start = mid+1;
        }else{
            end = mid-1;
        }
    }
    
    return -1;
    }
    
    int main(){
    
    int num, searchNumber;
    cout<<"How many Elements u want to insert? \n";
    
    cin>>num;
    int arr[num];
    cout<<"\n Enter ut Numbers:- \n";
    for(int i=0; i<num; i++){
        cin>>arr[i];
    }
    
    cout<<"\n Enter the Number u want to search:- ";
    cin>>searchNumber;
    
    int numberPosition = binarySearch(arr, num, searchNumber);
    
    if(numberPosition!=-1){
        cout<<searchNumber<<" is founded at position: "<<numberPosition;
    }else{
        cout<<searchNumber<<" is Not Founded";
    }
    
    return 0;
    }