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;
}
Related
CSS student here. I was given an exercise by my prof but I don't know how to solve this problem. A specific n is wanting to be accessed in printf but the given elements in the array are below the n that is asked.
This is the code I wrote but in this paticular test it's not giving me the right solution. Any tips?
#include <stdio.h>
int max(int arr[], int n) {
int numMax = 0, indexMax = 0;
for (int i = 0; i <= n; i++) {
if (arr[i] >= numMax) {
numMax = arr[i];
indexMax = i;
}
}
return indexMax;
}
int main () {
int arr[5]={-88, -91, -45, -90, -13};
printf("The index of the highest number is: %d\n", max(feld, 5));
// solution: 5
return 1;
}
Your array is called arr and not feld.
In your function you can initialize numMax with the first value of the array and then loop through it to test the following ones.
#include <stdio.h>
int max(int arr[], int n)
{
int numMax = arr[0], indexMax = 0;
for (int i = 1; i < n; i++)
{
if (arr[i] >= numMax)
{
numMax = arr[i];
indexMax = i;
}
}
return indexMax;
}
int main(void)
{
int arr[5] = {-88, -91, -45, -90, -13};
printf("The index of the highest number is: %d\n", max(arr, 5));
return 0;
}
With: for (int i = 0; i <= n; i++), the OP program is stepping out of the boundaries of the array. (zero based indexing is tricky for beginners.)
The array elements aren't going anywhere.
Simply pick the last element, and update that pick if a higher value is found during a scan toward the 0th element.
int maxVal( int arr[], int n ) {
int maxInd = --n;
while( --n >= 0 )
if( arr[n] > arr[MaxInd] ) maxInd = n;
return maxInd;
}
Fewer variables to keep track of is always an advantage.
The function returns the index, not the value.
printf("The index of the highest number is: %d\n", max(arr, 5) );
EDIT:
Let's visit main() to improve it a bit.
int main( void ) { // more conventional
// the compiler counts more accurately than most people:
int arr[] = { -88, -91, -45, -90, -13 };
size_t nElem = sizeof arr/sizeof arr[0];
// Notice that maxVal() should return a 'size_t', too.
// Use the appropriate format specifier
// The name "maxVal()" is misleading. Fix that...
printf("The index of the highest number is: %sz\n", maxValInd( arr, nElem ) );
return 0; // 0 means all good, non-zero indicates an error occurred.
}
Now, since that uses size_t (better for non-negative values like the number of elements in an array or bytes in a file), we should improve the function, too:
size_t maxValInd( int arr[], size_t n ) {
size_t maxInd = 0; // pick 0th as first pick...
while( --n > 0 ) // test all values down to, but not, arr[0].
if( arr[n] > arr[MaxInd] ) maxInd = n;
return maxInd;
}
NB: size_t is an unsigned datatype that will underflow if decremented below zero. Handle with care to avoid infinite-loops.
int arr[6] and passing 5 as argument to max should do the work.
I dont know how to get the code to print out the elements that are divisable with 3 and the print out the sum of those elements , can someone help me do it , thanks for your time!
Code:
#include <stdio.h>
int sum(int arr[]){
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
for (int y=0;y<n;y++){
sum += arr[y];
printf("%d",sum);
}
}
int main() {
int F[5] = {1,3,5,9,8};
int s = 0;
for (int i=0;i<5;i++){
if (F[i]%3 == 0) {
int diviz[] = {F[i]};
printf("%d\n",diviz[0]);
sum(diviz);
}
}
return 0;
}
Expected Output:
3
9
12
Actual Output:
3
349
910
Idk how to solve this issue
This function declaration
int sum(int arr[]){
is adjusted by the compiler to the declaration
int sum(int *arr){
That is within the function the variable arr has the pointer type int *.
Thus the declaration with sizeof expression
int n = sizeof(arr) / sizeof(arr[0]);
is equivalent to
int n = sizeof( int * ) / sizeof( int );
and yields either 2 or 1 depending on the size of the pointer.
On the other hand, this call of the function
int diviz[] = {F[i]};
printf("%d\n",diviz[0]);
sum(diviz);
in any case does not make a great sense because instead of passing the original array you are passing an array that contains only one element. And the for loop in main is redundant.
You need explicitly to pass the number of elements in the array.
So the function can look like
long long int sum( const int arr[], size_t n, int divisor )
{
long long int sum = 0;
for ( size_t i = 0; i < n; i++ )
{
if ( arr[i] % divisor == 0 ) sum += arr[i];
}
return sum;
}
And the function can be called like
int arr[] = {1,3,5,9,8};
const size_t N = sizeof( arr ) / sizeof( *arr );
int divisor = 3;
printf( "The sum of elements divisible by %d = %lld\n", divisor, sum( arr, N, divisor ) );
The function will be more safer if to add a check whether divisor is passed equal to 0 as for example
long long int sum( const int arr[], size_t n, int divisor )
{
long long int sum = 0;
if ( divisor != 0 )
{
for ( size_t i = 0; i < n; i++ )
{
if ( arr[i] % divisor == 0 ) sum += arr[i];
}
}
return sum;
}
int main() {
int F[5] = {1,3,5,9,8};
int s = 0;
for (int i=0;i<5;i++){
if (F[i]%3 == 0) {
s = s + F[i];
printf("%d",F[i]);
}
}
printf("%d",s); //print sum total
return 0;
}
I'm trying to find the index of the biggest number in array, by using a recursive function, but it doesn't work for me.
I wrote this code in "Online C Complier":
#include <stdio.h>
int max(int arr[], int n){
if (n==0) {
return 0;
}
int temp = max(arr, n-1);
if (arr[temp] > arr[n]) {
return temp;
}
else {
return n;
}
}
int main()
{
int arr[] = {20,2,44,6,1,15,25,40};
printf("The index is: %d\n", max(arr, 8));
return 0;
}
The out put is sometimes 8 which is wrong and sometimes 2 which is correct.
thanks u all!
For starters the first function parameter should have qualifier const because the passed array is not being changed within the function.
This part of the function
int temp = max(arr, n-1);
if (arr[temp] > arr[n]) {
return temp;
}
else {
return n;
}
is incorrect. For example n is not a valid index.
The function can look the following way as shown in the demonstration program below.
#include <stdio.h>
size_t max( const int arr[], size_t n )
{
if ( n > 1 )
{
size_t i = max( arr + 1, n - 1 ) + 1;
return arr[0] < arr[i] ? i : 0;
}
else
{
return 0;
}
}
int main( void )
{
int arr[] = { 20, 2, 44, 6, 1, 15, 25, 40 };
const size_t N = sizeof( arr ) / sizeof( *arr );
printf( "The index is: %zu\n", max( arr, N ) );
}
The program output is
The index is: 2
Or using your approach the function can look like
size_t max( const int arr[], size_t n )
{
if ( n > 1 )
{
size_t i = max( arr, n - 1 );
return !( arr[i] < arr[n-1] ) ? i : n - 1;
}
else
{
return 0;
}
}
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;
}
#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.