Solved programming problem

Find the 2nd Large Element from an Array with Recursion in C.

Source code

#include<stdio.h>

void input(int array[],int n, int i) ///input an array element with recursion

{

    if(i==n)

    {

        return array;

    }

    else

    {

        scanf("%d",&array[i]);

        return input(array,n,i+1);

    }

}

void second_highest(int array[],int n,int i,int first, int second)

{

    if(n==i) ///base case

    {

        printf("2nd Highest Number : %d
",second);

        return ;

    }

    else

    {

        if(first < array[i]) ///if larger number found

        {

            second = first; ///save the large to second large

            first = array[i];

        }

        else if(second < array[i]) ///if the number smaller the first but grater then second

        {

            second = array[i];

        }

        return second_highest(array,n,i+1,first,second);

    }

}

int main()

{

    int n;

    int array[100],first,second;

    printf("Please Enter Array Size: ");

    scanf("%d",&n);

    printf("Enter Array Element: ");

    input(array,n,0);

    first = array[0];

    second = array[0];

    printf("Your Result : 
");

    second_highest(array,n,0,first,second);

    printf("
");

    return 0;

}

Output

Please Enter Array Size: 5
Enter Array Element: 5 8 7 9 3
Your Result :
2nd Highest Number : 8

Join the discussion

Add your comment