Follow This Blog For more... 😊

A recursive function that returns the maximum among the first n elements of an array |Using C Language|

👨‍💻Write a recursive function that returns the maximum among the first n elements of an array.

CODE:

   
    //A recursive function that returns the maximum among the first n elements of an array.
    #include <stdio.h>
    int rec_for_max(int array[], int length);
    main()
    {
            int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; /*Here, declared arrey elements at compile time */
        int length = (sizeof(array)) / (sizeof(array[0])); /* Here, find length of array by length = ( total array size ) / ( size of one element in the array )  */
        printf("=> Maximum among elements of an array is %d", rec_for_max(array, length));
    }
    int rec_for_max(int array[], int length)
    {
            int maximum;
        if (length == 1)
        {
                maximum = array[0];
            return maximum;
        }
        else
        {
                if (array[length] > rec_for_max(array, length - 1))
            {
                    return array[length];
            }
            else
            {
                    return rec_for_max(array, length - 1);
            }
        }
    }

OUTPUT:



Comments

Popular Posts