c++returnlinear-search

Return statement not working in the linear search algorithm


This is a linear search algorithm and I am a newbie programmer....Why is the "return i" statement not returning i (printing it on console)?? Is it because the computer considers this as "end the program successfully" because the value of i > 0 (I mean is it acting like "return 0" statement??) how to solve this issue??

#include <iostream>

int linearSearch(int n, int arr[], int num);

int main() {
    int n, num, arr[n];
    std::cout << "Enter Array Size: ";
    std::cin >> n;
    std::cout << "Enter Array: ";
    for(int i = 0; i < n; i++) {
        std::cin >> arr[i];
    }
    std::cout << "Enter Num to Search in Array: ";
    std::cin >> num;
    linearSearch(n, arr, num);
}


int linearSearch(int n, int arr[], int num) {
    for(int i = 0; i < n; i++) {
        if(arr[i] == num) {
            std::cout << "Found at Index: ";  
            return i; //this should return index i but program ends before printing i to console
        }
    }
    std::cout << "...Not Found...";
    return -1;
}

Solution

  • Why is the "return i" statement not returning i (printing it on console)??

    Thats a misunderstanding common among beginners. Returning something from a function and printing something to the console are two different things.

    Not every value you return from a function will be displayed on the console. If you use other languages with an interpreter you may be used that the result of all statements appears on the console. But you aren't running an interpreter.

    In your function

    return i;
    

    is completely fine to return the value. It does work!

    In your main

    linearSearch(n, arr, num);
    

    You call the function and ignore the returned value. If you want the value returned from the call to appear on the console you need to write code for that. For example:

    int x = linearSearch(n,arr,num);
    if (x != -1) std::cout << "index = " << x;