Finding minimum with a recursive function

182 views Asked by At

Whatever the input, the result is always 0. Why is that ?

#include <stdio.h>
#include <conio.h>

int rekursiv( int v[], int i, int n, int *min );

int main( void )
{
    int v[ 100 ];
    int n, i, min;

    printf( "Shkruanni n: " );
    scanf( "%d", &n );
    printf( "Shkruani elementet e vektorit.\n" );
    for( i = 0; i < n; i++ ){
         scanf( "%d", &v[ i ] );

         }//end for
    min = v[ 0 ];
    i = 1;
    printf( "Minimumi eshte %d.", rekursiv( v, i, n, &min ) );

    getche();
    return 0;
}//end main

int rekursiv( int v[], int i, int n, int *min )
{
    if( i == n - 1 ) {
        return *min;
    }//end if
    else {
        if( *min < v[ i ] ) {
            *min = v[ i ];
        }//end if
        rekursiv( v, i + 1, n, min );
    }//end else

}//end rekursiv
2

There are 2 answers

1
The Dark On BEST ANSWER

You should compile with warnings switched on. rekursiv does not always return a value.

Change

rekursiv( v, i + 1, n, min );

to

return rekursiv( v, i + 1, n, min );
0
Khamill On

In function (int rekursiv( int v[], int i, int n, int *min ) ), must be return integer so your last condition does not return anything. You should check last condition ELSE

else {
         if( *min < v[ i ] ){
             *min = v[ i ];

             }//end if
         rekursiv( v, i + 1, n, min );

         }