ADVERTISEMENT
ADVERTISEMENT

C program to search an item in an array using recursion

Here, we are going to learn how to search an item in an array using recursion in C language?
Submitted by Nidhi, on August 26, 2021

Problem Solution:

Create an array of integers, then search an array element using recursion and print the index of the item.

Program:

The source code to search an item in an array using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to search an item in array
// using the recursion

#include <stdio.h>

int searchItem(int arr[], int len, int item)
{
    if (arr[len] == item)
        return len;
    else if (len == -1)
        return -1;
    else
        return searchItem(arr, len - 1, item);
}

int main()
{
    int arr[] = { 23, 10, 46, 21, 75 };
    int index = 0;
    int item = 0;

    printf("Enter item to search: ");
    scanf("%d", &item);

    index = searchItem(arr, 5, item);
    if (index == -1)
        printf("Item not found in array\n");
    else
        printf("Item found at index %d\n", index);

    return 0;
}

Output:

Enter item to search: 46
Item found at index 2

Explanation:

Here, we created two functions searchItem() and main(). The searchItem() is a recursive function, which is used to search an item in the array and return the index of the item to the calling function.

In the main() function, we created an array of integers arr with 5 elements. Then we searched the item in the array and printed the index of the item in the array.

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.