Using recursion in c find the largest element in an array





C code to get largest element of an array by recursion:

#include<stdio.h>
#define MAX 100

int getMaxElement(int []);
int size;

int main(){

    int arr[MAX],max,i;

    printf("Enter the size of the array: ");
    scanf("%d",&size);

    printf("Enter %d elements of an array: ", size);
    for(i=0;i<size;i++)
      scanf("%d",&arr[i]);

    max=getMaxElement(arr);

    printf("Largest element of an array is: %d",max);

    return 0;
}

int getMaxElement(int arr[]){

    static int i=0,max =-9999;

    if(i < size){
         if(max<arr[i])
           max=arr[i];
      i++;
      getMaxElement(arr);
    }

    return max;
}

Sample output:

Enter the size of the array: 5
Enter 5 elements of an array: 1 4 5 6 2
Largest element of an array is: 6

C code to get largest element of an array without recursion:

#include<stdio.h>
#define MAX 100

int getMaxElement(int []);
int size;

int main(){

    int arr[MAX],max,i;

    printf("Enter the size of the array: ");
    scanf("%d",&size);

    printf("Enter %d elements of an array: ", size);
    for(i=0;i<size;i++)
      scanf("%d",&arr[i]);

    max=getMaxElement(arr);

    printf("Largest element of an array is: %d",max);

    return 0;
}

int getMaxElement(int arr[]){

    int i=1,max;

    max=arr[0];

    while(i < size){
      if(max<arr[i])
           max=arr[i];
      i++;
    }

    return max;
}





Sum of n numbers using recursion in c
Matrix multiplication using recursion in c
Multiplication using recursion in c
Lcm using recursion in c
Using recursion in c find the largest element in an array
Prime number program in c using recursion
Decimal to binary conversion in c using recursion
C program for fibonacci series using recursion
Reverse a string using recursion
Write a program for palindrome using recursion
Find factorial of a number using recursion in c program
Find gcd of a number using recursion in c program
Find sum of digits of a number using recursion using cprogram
Find power of a number using recursion using c program
Binary search through recurssion using c program
Reverse a number using recursion in c program
Big list of c program examples

5 comments:

Anonymous said...

instead of while loop in de funcn a for loop wud've been more convenient

Unknown said...

nice logic

Unknown said...

Thanks it is really useful to me (^~^)

Unknown said...

thanks a lot :D ,,,this site is really helpfull :)

Unknown said...

thanks a lot :D ,,,this site is really helpfull :)