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;
}

Recommended Answers

All 6 Replies

yeah i know but would like to know how to loop thrught array using recurtion

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);
}

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;
}

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);"

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.