Recursive minimum function - c

#include<stdio.h>
#define SIZE 7
int recursiveMinimum( int a[], int size );
int main(void) {
int a[ SIZE ] = { 5, 7, 4, 3, 5, 1, 3 }; // Number 2 is not initialized.
printf( "The smallest number is %d", recursiveMinimum( a, SIZE ) );
return 0;
}
int recursiveMinimum( int a[], int size ) {
static int min ;
static int i = 0;
min = a[ i ];
if( a[ i + 1 ] < min ) {
min = a[ i + 1 ];
}
i++;
if( i == size ) {
return min;
} else {
return recursiveMinimum( a, size );
}
}
So why does it print 2?

You have an off-by-one access of your array: you are accessing the a[7] element but the last element of your array is a[6].
Look you have:
i++;
if( i == size ) {
but above you are accessing a[i + 1] which means at some point you will access a[size] (which is outside the array).
Change if (i == size) to if (i == size - 1) to fix your issue.

You don't initialize min correctly, it needs to be set to the smallest possible number it can have, for example the constant INT_MIN found in limits.h. Instead of doing this, you overwrite min in each recursive call with the line min = a[ i ];.
You access the array out-of-bounds, in the last function call when i is 6, you run the code [ i + 1 ] which invokes undefined behavior. Unfortunately your program didn't crash, but instead outputs some garbage value.
There is absolutely no reason to use recursion for this algorithm you are writing.

Show this code (I add integer variable static int initialize_min for initialization min as a[0] in first function call):
#include<stdio.h>
#define SIZE 7
int recursiveMinimum( int a[], int size );
int main(void) {
int a[ SIZE ] = { 5, 7, 4, 3, 5, 1, 3 }; // Number 2 is not initialized.
printf( "The smallest number is %d", recursiveMinimum( a, SIZE ) );
return 0;
}
int recursiveMinimum( int a[], int size ) {
static int min;
static int initialize_min = 1;
static int i = 0;
if(initialize_min )
{
min = a[0];
initialize_min = 0;
}
if( a[ i ] < min ) {
min = a[ i ];
}
i++;
if( i == size ) {
return min;
} else {
return recursiveMinimum( a, size );
}
}

I think this example is what is intended for a recursive minimum function:
#include <stdio.h>
#define SIZE 7
#define min(a, b) (((a) < (b)) ? (a) : (b))
/* assumes size != 0 */
int recursiveMinimum(int a[], size_t size){
int *beg; /* ptr to beginning */
int *mid; /* ptr to middle */
int *end; /* ptr to end */
if(size < 2) /* if size == 1 */
return a[0];
beg = &a[0]; /* else split array */
mid = &a[size/2]; /* and recurse */
end = &a[size];
return min(recursiveMinimum(beg, mid-beg),
recursiveMinimum(mid, end-mid));
}
int main(void)
{
int a[SIZE] = {5, 7, 4, 3, 5, 1, 3 };
printf( "The smallest number is %d", recursiveMinimum( a, SIZE ) );
return 0;
}

You could try this method:
double smaller(double a, double b){
return (a<b)?a:b;
}
double min(double *p_array, int idx_low, int idx_high){
if(idx_low==idx_high)
return p_array[idx_low];
int idx_mid=idx_low+(idx_high-idx_low)/2;
return smaller(min(p_array,idx_low,idx_mid), min(p_array,idx_mid+1, idx_high));
}
An analysis of the algorithm should give you an O(n*log(n)) running time - take it with a pinch of salt, though.

To use INT_MIN, we should include limits.h.
Also it must be unsafe, because we may want use unsigned, long, long long, __int8 etc.

Related

Im trying to find the max and min value and its respective index. However I cant get the indexmin

Find the minimum element of the array and its corresponding index.
I can't get the the minimum index to work. Do I add else statement under each if statement?
#include<stdio.h>
int main()
{
int array[10]={1,2,3,4,5,6,7,8,9,10} , i;
**//finding max and min, and its respective index**
int max = array[0] , min = array[0];
int indmin , indmax;
for( i = 0 ; i < 10 ; i++ )
{
if(array[i] > max)
{
max = array[i];
indmax = i;
}
if(array[i] < min)
{
min = array[i];
indmin = i;
}
}
//print the max and min value and its indexs
printf("\nMaximum element is %d\t index is %d", max , indmax);
printf("\nMinimum element is %d\t index is %d", min , indmin);
}
Initialize indmin and indmax. When defining the array leave out the size so it's derived from the data. When iterating over the array use sizeof(array) / sizeof(*array) to let compiler determine the size of the array instead of hard-coding it. Minimize scope of variable i. Use a function to print output for less duplication:
#include <stdio.h>
void print(const char *prompt, int value, int index) {
printf("%s element is %d\t index is %d\n", prompt, value, index);
}
int main() {
int array[]={1,2,3,4,5,6,7,8,9,10};
int min = array[0];
int indmin = 0;
int max = array[0];
int indmax = 0;
for(int i = 0; i < sizeof(array) / sizeof(*array); i++) {
if(array[i] > max) {
max = array[i];
indmax = i;
}
if(array[i] < min) {
min = array[i];
indmin = i;
}
}
print("Maximum", max, indmax);
print("Minimum", min, indmin);
}
You could refactor this by creating a struct to keep the value and index together:
#include <stdio.h>
struct value_index {
int value;
int index;
};
void print(const char *prompt, struct value_index *vi) {
printf("%s element is %d\t index is %d\n", prompt, vi->value, vi->index);
}
int main() {
int array[]={1,2,3,4,5,6,7,8,9,10};
struct value_index min = { array[0], 0 };
struct value_index max = { array[0], 0 };
for(int i = 0; i < sizeof(array) / sizeof(*array); i++) {
if(array[i] > max.value) {
max.value = array[i];
max.index = i;
}
if(array[i] < min.value) {
min.value = array[i];
min.index = i;
}
}
print("Maximum", &max);
print("Minimum", &min);
}
Or you could realize that you only need the original array along with the two indices. To make my version even better than #Fe2O3's answer, I used a macro to make mine smaller (and if bait works then I will claim mine is easier to read) :-)
#include <stdio.h>
void print(const char *prompt, int *arr, int index) {
printf("%s element is %d\t index is %d\n", prompt, arr[index], index);
}
int main() {
int array[]={1,2,3,4,5,6,7,8,9,10};
int indmin = 0;
int indmax = 0;
for(int i = 0; i < sizeof(array) / sizeof(*array); i++) {
#define CMP_AND_SET(OP, V) if(array[i] OP array[V]) V = i
CMP_AND_SET(<, indmin);
CMP_AND_SET(>, indmax);
#unset CMP_AND_SET
}
print("Maximum", array, indmax);
print("Minimum", array, indmin);
}
Building on #Fe2O3's branchless idea combined with an initialized array which I find to compact and quite readable:
indmin = (int[]) { indmin, i }[array[i] < array[indmin]];
indmax = (int[]) { indmax, i }[array[i] > array[indmax]];
By using (a < b) <=> -1 * (-a > -b) you can write the last one as (note: UB if array contains INT_MIN):
indmax = (int[]) { indmax, i }[-array[i] < -array[indmax]];
I would use a local macro to reduce code duplication by using macro to generate either the first version by passing in the operator (see above) or the 2nd version by passing in a factor F:
#define MINMAX(V, F) V = (int[]) { V, i }[F * array[i] < F * array[V]]
indmin = MINMAX(indmin, 1);
indmax = MINMAX(indmax, -1);
I am totally cheating but you can shuffle the min and max elements to fixed positions within the source array. No storage overhead. This would be the opposite of branchless.
#include <stdio.h>
void print(const char *prompt, int value) {
printf("%8s = %3d\n", prompt, value);
}
int swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
return 0;
}
int main(void) {
int arr[] = { 1, 2, 3, 4, 42, 5, -42, 6, 7, 8, 9, 10 };
const int min = 0;
const int max = sizeof arr/sizeof *arr - 1;
for(int i = 1; i < max + 1; i++ )
arr[i] < arr[min] && swap(arr + i, arr + min) ||
arr[i] > arr[max] && swap(arr + i, arr + max);
print("min", arr[min]);
print("max", arr[max]);
}
Leaving variables uninitialised is asking Demon of Hard-To-Find Bugs to co-author your code. Define variables close to where they are used to increase clarity. And, don't define more variables than you need. (Common beginner mistake to make another copy "just in case"...)
// use the spacebar to increase readability
#include <stdio.h>
int main() {
// let the compiler assign the size of an initialised array
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// use fewer variables
int indmin = 0, indmax = 0;
// don't compare an element (arr[0]) to itself
for( int i = 1 ; i < sizeof array/sizeof array[0]; i++ )
if( array[ i ] > array[ indmax ] )
indmax = i; // updated
else
if( array[ i ] < array[ indmin ] )
indmin = i; // updated
// don't add unnecessary braces (imho)
// this isn't the 17th century in need of needless filligree.
// use '\n' at the END of output. sometimes needed to 'flush' output buffer
printf("Maximum element is %d\t index is %d\n", array[ indmax ] , indmax);
printf("Minimum element is %d\t index is %d\n", array[ indmin ] , indmin);
return 0;
}
Maximum element is 10 index is 9
Minimum element is 1 index is 0
EDIT:
So, there's a friendly competition going on in this question... :-)
How's this:
#include <stdio.h>
int main() {
// let the compiler assign the size of an initialised array
// use shorter names to expose operations (not lengthy variable names)
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int iMin = 0, iMax = 0;
// don't compare an element to itself
for( int i = 1; i < sizeof arr/sizeof arr[0]; i++ ) {
// use "branchless" coding for speed.
int n = arr[i] > arr[iMax];
iMax = n*i + !n*iMax;
n = arr[i] < arr[iMin];
iMin = n*i + !n*iMin;
}
// reduce duplication of static data
char *fmt = "%s element is %d\t index is %d\n";
printf( fmt, "Maximum", arr[ iMax ], iMax );
printf( fmt, "Minimum", arr[ iMin ], iMin );
return 0;
}
Same output.
Ball's in your court #Allan :-)
EDIT:
There has been an advance on the last offering that needs to be addressed...
Here we go whole-hog, splurging-out with a third 'container' (mm[0]) to catch all those indexes that satisfy neither conditional ('<' & '>'). AND, a 4th 'container' (mm[3]) that doesn't change from being initialised to 0, the index of the 1st element. Besides being cryptic (not advised), this may-or-may-not be more expensive with its multiple array offset calculations... But, it's fun to look at...
#include <stdio.h>
int main() {
// added two elements to show 0 and nElem are not 'flukes'
// this really does find and report the min/max values
int arr[] = { 1, 2, 3, 4, 42, 5, -42, 6, 7, 8, 9, 10 };
int i, mm[1 + 2 + 1] = { 0 };
// assign 'i' to mm[ 0 or 1 or 2 ]. 0=latest, 1=max, 2=min, (3 unaffected)
for( i = 1; i < sizeof arr/sizeof arr[0]; i++ )
mm[ (arr[i] > arr[mm[1]]) + 2*(arr[i] < arr[mm[2]]) ] = i;
mm[ 0 ] = i-1; // always pick up the last index. Thanks #A Wind!
// now... this is getting silly!!
char *fmt = "%5s = %3d # arr[%d]\n";
char *type[] = { "last", "max", "min", "first" };
i = 3; do printf( fmt, type[i], arr[ mm[i] ], mm[i] ); while( --i >= 0 );
return 0;
}
first = 1 # arr[0]
min = -42 # arr[6]
max = 42 # arr[4]
last = 10 # arr[11]
Y'know... This might be interesting to try to apply to 3-way branching as is needed for binary searching; determining '<', '=' or '>'... Hmmm...
EDIT: (another variation on a theme at the suggestion of a worthy competitor :-)
#include <stdio.h>
int main() {
struct {
char *label;
int ind;
} mm[] = {
{ "last" },
{ "maximum" },
{ "minimum" },
{ "first" },
};
int i, arr[] = { 1, 2, 3, 4, 42, 5, -42, 6, 7, 8, 9, 10 };
for( i = 1; i < sizeof arr/sizeof arr[0]; i++ )
mm[ (arr[i] > arr[mm[1].ind]) + 2*(arr[i] < arr[mm[2].ind]) ].ind = i;
mm[ 0 ].ind = --i; // always pick up the last index. Thanks #A Wind!
for( i = sizeof mm/sizeof mm[0]; --i >= 0; /* space for rent */ )
printf( "%8s = %3d # arr[%d]\n", mm[i].label, arr[ mm[i].ind ], mm[i].ind );
return 0;
}
EDIT:
Trying to cover ALL the bases, here are three more ways to skin a cat
/* Minimalist */
#include <stdio.h>
int main() {
int mm[3] = { 0 },
arr[] = { 1, 2, 3, 4, 42, 5, 6, 7, 8, 9, 10 },
i = sizeof arr/sizeof arr[0];
while( --i )
mm[ 2*(arr[i] > arr[mm[2]]) + (arr[i] < arr[mm[1]]) ] = i;
char *fmt = "arr[%d] = %3d M%simum\n";
printf( fmt, mm[1], arr[mm[1]], "in" );
printf( fmt, mm[2], arr[mm[2]], "ax" );
return 0;
}
/* Recursive - for brevity, excluding the index; just reporting two values */
#include <stdio.h>
int amin( int a[], int i ) { // NB: "amin", not "main"
int j = --i ? amin( a, i ) : i;
return (a[j]<a[i])*j + (a[j] > a[i])*i;
}
int amax( int a[], int i ) {
int j = --i ? amax( a, i ) : i;
return (a[j]>a[i])*j + (a[j]<a[i])*i;
}
int main() {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, },
sz = sizeof arr/sizeof arr[0];
char *fmt = "M%simum: %3d\n";
printf( fmt, "in", arr[ amin(arr, sz) ] );
printf( fmt, "ax", arr[ amax(arr, sz) ] );
return 0;
}
/* And, simply brute force using a library function */
#include <stdio.h>
#include <stdlib.h>
int cmp( const void *a, const void *b ) { return *(int*)a - *(int*)b; }
int main() {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
sz = sizeof arr/sizeof arr[0];
qsort( arr, sz, sizeof arr[0], cmp );
char *fmt = "M%simum: %3d\n";
printf( fmt, "in", arr[ 0 ] );
printf( fmt, "ax", arr[ --sz ] ); // again, thanks to #A Wind
return 0;
}
Many ways to skin a cat.

What's wrong with this function that reverses arrays using recursivity? ( code and outcome included )

So this is the code I wrote, trying to reverse that array t using recursivity
#include <stdio.h>
#include <stdlib.h>
void rev(int n, float *t)
{
float x;
if(n==0)
{
return 0 ;
}
else
{
x=*t;
*t=*(t+(n-1));
*(t+(n-1))=x;
return rev(n-1, t+1);
}
}
void main()
{
int i;
float t[]={1,2,3,4,5,6,7,8,9};
int n=sizeof t /sizeof *t;
rev (n,t);
for(i=0;i<n;i++) printf("%f",t[i]);
}
I'd like to understand why this solution does not work, I'm not that interested in the solution overall but I want to understand what mistakes I made in this one for it not to work.
For starters a function that has the return type void shall return nothing value. So this statement
return 0 ;
is invalid.
The function swaps two elements so the size of the array must be decremented by 2.
The function can look like
void rev( float a[], size_t n )
{
if ( !( n < 2 ) )
{
float tmp = *a;
*a = *( a + n - 1 );
*( a + n - 1 ) = tmp;
rev( a + 1, n - 2 );
}
}
and be called like
size_t n = sizeof t /sizeof *t;
rev( t, n);
Here is a demonstrative program.
#include <stdio.h>
void rev( float a[], size_t n )
{
if ( !( n < 2 ) )
{
float tmp = *a;
*a = *( a + n - 1 );
*( a + n - 1 ) = tmp;
rev( a + 1, n - 2 );
}
}
int main(void)
{
float a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
size_t n = sizeof a /sizeof *a;
for ( size_t i = 0; i < n; i++ )
{
printf( "%.0f ", a[i] );
}
putchar( '\n' );
rev( a, n );
for ( size_t i = 0; i < n; i++ )
{
printf( "%.0f ", a[i] );
}
putchar( '\n' );
return 0;
}
The program output is
1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1
Pay attention to that according to the C Standard the function main shall be declared like
int main( void )
instead of
void main()
There are small easy to fix problems like return 0; and return rev(n-1, t+1);. The first one should be just
return;
because you can't return anything from a function returning void.
The other should be a call to rev() itself
rev(n-1, t+1);
because that's what recursive functions do (and also because you can't return anything)
Then you should use int main( void ) or at least int main() Difference between int main() and int main(void)?
Finally, you have a logic error here
x=*t;
*t=*(t+(n-1));
*(t+(n-1))=x;
rev(n-1, t+1);
*(t+(n-1)) will always be the value of the last element of the array: yes you pass n-1 so you expect that if *(t+(n-1)) was 8th element, in the next call it will be 7th, however you are also passing t+1 so *(t+(n-1)) will always be the 8th element of the array.
And even this one is an easy-to-fix problem. You just pass n-2.
Here's your recursive function
void rev(int n, float *t)
{
float x;
if(n > 0) {
x=*t;
*t=*(t+(n-1));
*(t+(n-1))=x;
rev(n-2, t+1);
}
return;
}
Doing
if(n != 0) {
.... something....
}
return;
Is the same of doing
if(n == 0) {
return;
}
else {
... something...
}
I put n > 0 instead of n != 0 because since n is always initially positive the two conditions are equivalent, however since you pass n-2 if n is an odd number you are going to have negative values of n without passing for 0.

Most long series of element in array

I've prepared a code that should found the longer series of elements in growing order .for example ,in arrays exists following elements : 1 2 3 4 5 2 7 6 7 9,output will 5 (the series from 1 to 5) ,function will return integer tempcount that include numbers of element and print it.but get an error ,the function
isn't working:
#include "stdafx.h"
#include <stdio.h>
int find_maximum(int[], int);
int main() {
int c, array[100], size, location, maximum,found;
scanf_s("%d", &size);
for (c = 0; c < size; c++)
scanf_s("%d", &array[c]);
location = find_maximum(array, size);
maximum = found;
printf("Maximum elements = %d ", maximum);
return 0;
}
int find_maximum(int a[], int n) {
int c, index = 0,count =1,tempCount=1;
for (c = 1; c < n; c++)
if (a[c] > a[index])
count +=1;
else
{
if (count > tempCount)
{
tempCount=count;
}
}
return tempCount;
}
The variables maximum and found are not initialized and are used nowhere except this statement that does not make sense
maximum = found;
You are storing the length of the maximum subsequence in the variable location
location = find_maximum(array, size);
It is the variable value which you need to output.
The function find_maximum also does not make sense. For example you are comparing elements of the array with the same element at position 0.
int c, index = 0,count =1,tempCount=1;
^^^^^^^^^
for (c = 1; c < n; c++)
if (a[c] > a[index])
count +=1;
//…
The function can be declared and implemented as it is shown in the demonstrative program below.
#include <stdio.h>
size_t max_ascending_seq( const int a[], size_t n )
{
size_t max_n = 0;
for ( size_t i = 0; i < n; )
{
size_t current_n = 1;
while ( ++i < n && a[i-1] < a[i] ) ++current_n;
if ( max_n < current_n ) max_n = current_n;
}
return max_n;
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 2, 7, 6, 7, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t max_n = max_ascending_seq( a, N );
printf( "%zu\n", max_n );
return 0;
}
The program output is
5
A more generic function can be written the following way.
#include <stdio.h>
size_t max_ascending_seq( const int a[], size_t n, int predicate( int, int ) )
{
size_t max_n = 0;
for ( size_t i = 0; i < n; )
{
size_t current_n = 1;
while ( ++i < n && predicate( a[i-1], a[i] ) ) ++current_n;
if ( max_n < current_n ) max_n = current_n;
}
return max_n;
}
int less_than( int x, int y )
{
return x < y;
}
int greater_than( int x, int y )
{
return y < x;
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 2, 7, 6, 7, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t max_n = max_ascending_seq( a, N, less_than );
printf( "%zu\n", max_n );
max_n = max_ascending_seq( a, N, greater_than );
printf( "%zu\n", max_n );
return 0;
}
The program output is
5
2

recursive find number in between in C

I want to find the number within a range in an array and must be in a recursive way. The function variables couldn't be modified.
Let's say in the range of 2 and 3
The input is : int a[] = {4, 1, 3, 1, 3, 2};
and the output will be = {3,3,2} , 3 found
Not sure how to code the recursive function in this case. The below I have tried not working.
int within(int a[], int N, int lower, int upper, int result[])
{
if(N == 1 && N <= upper && N>= lower)
return a[0];
return within(&a[1], N-1, lower, upper, result);
}
int main()
{
int a[] = {4, 1, 3, 1, 3, 2};
int result[6] = {0};
int i, nResult;
nResult = within(a, 6, 2, 3, result);
printf("%d data passed the bounds\n", nResult);
for (i = 0; i < nResult; i++){
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
I want to find the number within a range in an array
Let's say in the range of 2 and 3
Normally a for loop or similar would be so much easier here
If it has to be recursive....
// need to have another number - r - number in range
// r starts at zero
//
// normally lower case for variable and capitals for things you #define
// N starts at the number of elements of a less one
//
int within(int a[], int N, int lower, int upper, int r, int result[])
{
if(a[0] <= upper && a[0]>= lower) {
result[r]= a[0];
r++;
}
if(N==0) {
return r;
} else {
r = within(&a[1], N-1, lower, upper, r, result);
return r;
}
}
the function will give a return value of the number of values found within the range.
The code above is recursive, but so much more complicated and fragile than a simple loop... such as the fragment below
for (i=0;i<N;i++) {
if(a[i] <= upper && a[i]>= lower) {
result[r]= a[i];
r++;
}
}
If it has to be recursive wihtout r...
// need to have another number - result[0] - number in range
// result[0] starts at zero
//
// normally lower case for variable and capitals for things you #define
// N starts at the number of elements of a less one
//
int within(int a[], int N, int lower, int upper, int result[])
{
if(a[0] <= upper && a[0]>= lower) {
result[0]++;
result[result[0]]= a[0];
}
if(N==0) {
return result[0];
} else {
result[0] = within(&a[1], N-1, lower, upper, result);
return result[0];
}
}
now result conatins
{number in range, first number in range, second number in range....}
Something like this. If you want to implement a recursive function, try to do it in the way that the recursive call happens at the end.
#include <stdio.h>
int find_in_range(int* out, int const *in, int length, int from, int to)
{
if (length == 0)
{
return 0;
}
int addon;
if (*in >= from && *in <= to)
{
*out = *in;
++out;
addon = 1;
}
else
{
addon = 0;
}
return find_in_range(out, in + 1, length - 1, from, to) + addon;
}
#define N 6
int main()
{
int in[N] = {4, 1, 3, 1, 3, 2};
int out[N] = {0};
int num_found = find_in_range(out, in, N, 2, 3);
for (int i = 0; i < num_found; ++i)
{
printf("%d ", out[i]);
}
printf("\n");
return 0;
}
You can modify the following code as per your requirements. This is just a proof of concept code:
#include <stdio.h>
#include <stdlib.h>
static int result[4];
static int ctr1 = 0;
static int ctr2 = 0;
void recFind(int* arr, int* key){
if(ctr2 == 8)
return;
if(*arr >= key[0] && *arr <= key[1])
result[ctr1++] = *arr;
arr++;
ctr2++;
recFind(arr, key);
}
int main(){
int arr[] = {1,3,3,6,4,6,7,8};
int key[] = {1,4};
recFind(arr, key);
printf(" { ");
for(int i = 0; i < 4; i++){
printf("%d ", result[i]);
}
printf("}\n");
}
As it follows from the description of the assignment the function should provide two values: the number of elements that satisfy the condition and an array that contains the elements themselves.
It is evident that the array should be allocated dynamically. And it is logically consistent when the function itself returns the number of elements while the pointer to the generated array is passed by reference as an argument.
The recursive function can look the following way
#include <stdio.h>
#include <stdlib.h>
size_t get_range( const int a[], size_t n, int lower, int upper, int **out )
{
size_t m;
if ( n )
{
m = get_range( a, n - 1, lower, upper, out );
if ( lower <= a[n-1] && a[n-1] <= upper )
{
int *tmp = realloc( *out, ( m + 1 ) * sizeof( int ) );
if ( tmp )
{
tmp[m] = a[n-1];
*out = tmp;
++m;
}
}
}
else
{
*out = NULL;
m = 0;
}
return m;
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 4, 3, 2, 1 };
const size_t N = sizeof( a ) / sizeof( *a );
int lower = 2, high = 3;
int *out;
size_t n = get_range( a, N, lower, high, &out );
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", out[i] );
}
putchar( '\n' );
free( out );
return 0;
}
The program output is
2 3 3 2
Below codes will work for you in recursive way. If you don't want to print the numbers just comment out printf statement inside function printfRange. Hope you can understand the logic :-
int within(int *a, int rngH, int rngL, int length)
{
int len = length;
static int i = 0;
static int found = 0;
if(len <=0 )
{
return i;
}
if (*a == rngH)
{
printf("%d,",*a);
i++;
found = 1;
within(++a,rngH, rngL,--len);
}
else if(*a == rngL && found > 0)
{
printf("%d,",*a);
i++;
within(++a,rngH, rngL,--len);
}
else
{
within(++a,rngH, rngL,--len);
}
return i;
}
int main() {
int a[] = {4, 1, 3, 1, 3, 2};
int total = within(a,3,2,6);
printf("\n");
printf("Total :%d\n",total);
return 0;
}

Find max in array with recursion

I want to find the max number in array by recursion,
What wrong with this code.
#include<stdio.h>
int find_max(int *a,int n){
int m_max;
if(n==1){
return a[0];
}
m_max=find_max(a,n-1);
if(a[n-1]>m_max)
m_max=a[n-1];
}
As #moffeltje comments, "There isn't a return when n != 1"
if(a[n-1]>m_max)
m_max=a[n-1];
return m_max; // add
}
This linear approach gives recursion a bad name. If there are n numbers, the maximum recursive depth is n. Much better to divide in 2 for a max depth of log2(n)
int find_max(const int *a, int n) {
if (n <= 1) {
return a[0];
}
int left = find_max(a, n/2);
int right = find_max(&a[n/2], n - n/2);
return left > right ? left : right;
}
--- Minor stuff follows
Cope with corner cases where n < 1 or a == NULL.
int find_max(const int *a, int n) {
if (n <= 1 || a == NULL) {
if (n <= 0 || a == NULL) return INT_MIN; // or throw error
return a[0];
}
...
Changing int find_max(int *a, int n) --> int find_max(const int *a, int n) allows constant arrays to be passed also.
Array sizes are best typed as size_t rather than int.
int find_max(const int *a, size_t n) {
...
}
#include<stdio.h>
int find_max(int *a,int n){
int m_max;
if(n==1){
return a[0];
}
m_max=find_max(a,n-1);
if(a[n-1]>m_max)
m_max=a[n-1];
return m_max;
}
you have not returned anything when n!=1.
Look when designing these things you should always check the -
The base case. Here in this case it is achieved when n=1.(one element left and it is the largest one)
The recursive case. Here you will use the computed values to smaller cases and now you will build the solution thinking that the previous cases are calcualted already.
Combine Combine the calculate results. The last if condition that you have provided. But you forgot to put a return that is not giving the result to one stage to others. That's where there is this problem.
Alternatively, you could simplify the function.
int max_array_val( int* a_Array, int a_Size )
{
int max = a_Array[ 0 ];
for( int i = 1; i < a_Size; i++ )
if( a_Array[ i ] > max )
max = a_Array[ i ];
return max;
}
int main()
{
int int_array[ 6 ] = { 3, 2, 6, 5, 5, 2 };
printf( "Maximum number is: %i\n\n", max_array_val( int_array, sizeof( int_array ) / sizeof( int ) ) );
system( "pause" );
return 0;
}
int getMax(int const * arr, int size) {
if (size == 1)
return *arr;
int ans = getMax(arr + 1, size - 1);
return *arr > ans ? *arr : ans;
}

Resources