Header Ads

Header ADS

a.2: linear search in array

 #include <iostream> 


int main() {

    int arr[10], num, n, c = 0, pos;

    std::cout << "Enter the array size: ";

    std::cin >> n;


    if (n > 10) {

        std::cout << "Array size should be less than or equal to 10." << std::endl;

        return 1; // Exit with an error code

    }


    std::cout << "Enter array elements: ";

    for (int i = 0; i < n; i++) {

        std::cin >> arr[i];

    }


    std::cout << "Enter the number to be searched: ";

    std::cin >> num;


    for (int i = 0; i < n; i++) {

        if (arr[i] == num) {

            c = 1;

            pos = i + 1;

            break;

        }

    }


    if (c == 0) {

        std::cout << "Number not found." << std::endl;

    } else {

        std::cout << num << " found at position " << pos << std::endl;

    }


    return 0; // Exit successfully

}


No comments

Powered by Blogger.