0

hello friends.
i have i simple c/c++ function that return the min of the array to the main function, in the body of the function i'm using an iterative loop so i would like to do it recursivly and i don't know from where to start! all reply are usefull thank you all Danifriends!

#include<stdio.h>
int minarr(int n, int *arr){
 int i,min;
 for(i=0; i<n; i++){
   if(min > *(arr+i)){
     min = *(arr+i);
   }
 }
 return min;
}
int main(int argc, char const *argv[]) {
 int n=10;
   int tab[10]={7,5,6,8,7,4,8,9,2,3};
 int min=minarr(n, tab);
 printf("%d", min);
 return 0;
}
4
Contributors
6
Replies
36
Views
8 Months
Discussion Span
Last Post by AssertNull
0

How about this? We try not to give complete answers, but it's so short...

int minarr(int n, int *arr)
{
    if(n == 1)
        return *arr;
    int minAllButFirst = minarr(n - 1, arr+1);
    return (*arr < minAllButFirst ? *arr : minAllButFirst);
}
0

I suggest this code

#include<stdio.h>

int minoffset(int n, int* arr){
    return n == 1 ? 0 : (*arr <= *(arr + (n = 1 + minoffset(n-1, arr+1))))? 0 : n;
}

int main(int argc, char const *argv[]) {
    int n=10;
    int tab[10] = {7,5,6,8,7,4,8,9,2,3};
    int min = *(tab + minoffset(n, tab));
    printf("%d\n", min);
    return 0;
}
0

i know this an if condition but i don't know to use it "return n == 1 ? 0 : (arr <= *(arr + (n = 1 + minoffset(n-1, arr+1))))? 0 : n;"
"return (
arr < minAllButFirst ? *arr : minAllButFirst);"

0
return (*arr < minAllButFirst ? *arr : minAllButFirst);

is equivalent to:

if(*arr < minAllButFirst)
    return *arr;
else
    return minAllButFirst;

*arr represents the array element at index 0.minAllButFirst represents the minimum element of indexes 1 through n-1, which is the recursive call. Return whichever is smaller. The base condition in my code is if the array size is 1, return the one and only element.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.