-4

My Code is this will this find max number from array using recursion but it is not finding biggest Number

#include <stdio.h>

int maximum(int ar[], int n)
{

    if (n == 1) {
        return ar[0];

    } else {
        int max = maximum(ar, n-1);
        printf("Largest element : %d\n", max);
        return 5; // return ar[n-1] > max ? ar[n-1] : max;
    }
}

int main()
{
    int array[5] = {5, 23, 28, 7, 1};
    printf("Maximum element of the array is: %d", maximum(array, 5));
    return 0;
}
5
  • 6
    Where are you comparing numbers from the array? Hint: You're not. Commented May 29, 2013 at 14:01
  • 2
    Why you commented out return ar[n-1] > max ? ar[n-1] : max;? Commented May 29, 2013 at 14:01
  • You don't need recursion for this, just start out with the first element as your "max" and compare each element with the max. If the element you are comparing is bigger than the previous, then that becomes the max until the end. Use a for-loop starting at 1 and go to the end of the array. Commented May 29, 2013 at 14:03
  • There is no need for recursion here. The iterative solution is simpler and more efficient. Commented May 29, 2013 at 14:03
  • This program has bugs that we can't fix for you.. for instance, if you add another number to the array and increase n to 6, you read beyond the array. Commented May 29, 2013 at 14:19

2 Answers 2

6

With this particular line

return 5; // return ar[n-1] > max ? ar[n-1] : max;

in

if (n == 1) {
        return ar[0];

    } else {
        int max = maximum(ar, n-1);
        printf("Largest element : %d\n", max);
        return 5; // return ar[n-1] > max ? ar[n-1] : max;
    }
}

it will always return 5!

Sign up to request clarification or add additional context in comments.

3 Comments

No, it won't... He is passing 5 as second parameter. And 5 != 1 ! In the end, it will hit n == 1 eventually, that is true!
there's another small bug.. it will call maximum twice at the end, so that 28 is printed twice... if he comments in that line again
I think the printf in the maximum function was just for debugging purposes.
-4
#include<stdio.h>
void main()
{
    int pin[10]={2,4,6,34,56,54,34,23,1,10},i,max,k;

    max=pin[0];
    for(i=0;i<10;i++)
    {
        if(pin[i]>=max)
        {
            max=pin[i];
            k=i;
        }
    }
    printf("The max number of the array is: %d and it is in  %d position of the array\n",max,k+1);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.