Passing Array to a function and Adding it through Recursion - c

What em trying to do is pass the array to a function which will add all the array elements and return the output. Please help me. i dont know what i am doing wrong in this :/
#include <stdio.h>
#define MAX 5
int arraySum(int *dArr,int lim);
int main()
{
int array[MAX] = {9,7,4,2,10};
printf("%d", arraySum(array, MAX));
return 0;
}
int arraySum(int *dArr,int lim)
{
int Ans;
if(lim>0)
Ans = dArr[lim] + arraySum(*dArr, lim--);
return Ans;
}

There are several problems with your code:
You're accessing array[MAX], which is undefined behaviour.
Your function returns the uninitialized Ans when lim is zero.
The first argument to arraySum in the recursive call is wrong.
The use of lim-- is wrong.
Since this looks like homework, I'll let you figure out how to fix these problems. If this isn't homework, you might want to consider whether recursion is the right tool for the job.

You run into undefined behavior on dArr[lim], because lim is 5 and the array has elements 0...4.
You also get undefined behavior when lim==0, because you return an un-initialized Ans. When you declare it, initialize it to dArr[0].
After you fix this, you'll want to pass dArr itself further in the recursion, as dArr only returns an int.

Remember that computers treat 0 as the first number, so your array will number from element[0] to element[4]. your code starts from five and counts down to one, which means elements[5] in this case will return garbage, because the index does not exist. pass Lim - 1 into the function or manually changed the value in your function.
ArraySum(Array, MAX - 1);
OR
ArraySum(//....)
{
lim--;
//code here....
}
EDIT: you also need to initialize ans to some value, so if an array of zero elements is passed the function wont return an uninitialized variable.

int arraySum(int *dArr,int lim)
{
int Ans;
if(lim>=0) // note the change here
Ans = dArr[lim] + arraySum(dArr, --lim); // note the --lim change here
return Ans;
}
You should invoke this with lim as 4 and not 5. Because the array has 5 integers starting from index 0 to index 4. 5th index is out of bounds.
--lim instead of lim-- because lim-- is post decrement. That means the value is first passed and then decremented. Hence everytime your arraySum function gets the value as 4 instead of 3, 2, 1 and 0 (as per your expectation). --lim is pre-decrement.

Change MAX to 4 and change the if(lim>0) condition as if(lim>=0)
This will make your recursion to add as dArr[4]+dArr[3]+dArr[2]+dArr[1]+dArr[0] i.e. all 5 elements of the array.
EDIT: Corrected program:
int main()
{
int array[MAX] = {9,7,4,2,10};
printf("%d", arraySum(array, MAX-1));
return 0;
}
int Ans = 0;
int arraySum(int *dArr,int lim)
{
if(lim>=0){
Ans = dArr[lim] + arraySum(dArr, lim-1);
}
return Ans;
}

Related

What's wrong with the C code below?(A trivial one)

When you run the C code below, you get a different results almost everytime(None of them are altogether correct).
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;
int s[10][4]={{202201,90,13,21},{202202,32,24,12},{202203,23,53,76},{202204,21,43,64},{202205,12,45,89},{202206,98,99,100},{202207,12,0,0},{202208,0,0,0},{202209,98,12,34},{202210,23,65,34}};
int ave[10],sum[10];
printf("No. MA EN CN\n");
for(i=0;i<10;i++)
{
for(j=0;j<4;j++)
printf("%4d",s[i][j]);
printf("\n");
}
for(i=0;i<10;i++)
{
for(j=1;j<4;j++)
sum[i]=s[i][j]+sum[i];
printf("%d\n",sum[i]);
}
return 0;
}
What's happening? What's the mechanics behind it? How can I fix it?
Both sum and ave are uninitialized arrays. That means that when you cumulative add to s[i] your first add to an uninitialized value which invokes Undefined Behaviour. Here you were just getting a random but valid value.
You need to ensure that s[i][j] is initialized to 0 before it is first used:
int ave[10],sum[10] = {0}; // initialize the full sum array to 0
or:
for(i=0;i<10;i++)
{
sum[i] = 0; // ensure an initial value of 0
for(j=1;j<4;j++)
sum[i]=s[i][j]+sum[i];
printf("%d\n",sum[i]);
}
The issue most likely is in this statement.
sum[i]=s[i][j]+sum[i];
The "sum" integer array hasn't been initialized prior to this statement, so the value "sum[i]" on the right-hand side of the statement probably holds undefined data. Either initialize your sum array or revise the statement if some other type of evaluation should occur.

My function will give correct answers on only one call but not on multiple

I'm making a code for converting Decimal numbers to Binary(university assignment). If I only do DecToBinary(5) it gives me 101, and if I only do DecToBinary(6) it gives me 110, but when i do both of these statements in main() it gives me 101110101 when it should just give me 101110(joining the two answers above). I don't understand what is going on since it should just call DecToBinary(5) and print 101 then (without adding a newline character) call DecToBinary(6) and print 110.
void DecToBinary(int dec){
int temp[64]; //64 is just a max value
int i,j;
while(dec>0){
temp[i]=dec%2;
dec=dec/2;
i++;
}
for(j=0;j<i;j++){
printf("%d",temp[i-1-j]);
}
}
You haven't initialized the variable i. This means that the behaviour of your program is undefined, as the value of i may be different of 0 which is what you want.
To correct it, you just have to initialize i when declaring it, meaning int i = 0
The variable i is not initialized
int i,j;
so the function has undefined behavior.
You need to initialize it before the while loop.
Also the while loop should be substituted for a do-while loop. Otherwise the value 0 will not be processed correctly. For example
i = 0;
do
{
temp[i++] = dec % 2;
} while( dec /= 2 );
Also as the function does not process negative numbers then its parameter should have the type unsigned int
void DecToBinary( unsigned int dec )
Always initliaze variable. Check i and j in your case.

Why we can't compare a int variable with int return type function in c?

I tried to compare int variable with the function in two ways:
storing the int function return value in a variable then comparing with another
in value.
Directly comparing the int variable and the function call.
Here I got the answer for the first one but not for the second one.
Why does this happen?
My code:
#include < stdio.h >
int count = 0;
int countDigits(int);
int main() {
int i;
int result = countDigits(435);
for (i = 0; i < result; i++) {
printf("id %d\n", 3);
}
for (i = 0; i < countDigits(435); i++) {
printf("i =%d\n", i);
}
}
int countDigits(int n) {
if (n == 0) {
return count;
} else {
countDigits(n / 10);
count++;
}
}
We can.
It's just that your function has a logical error. Debug it, and you will be fine.
Enabling compiler warnings would have helped you. For example with GCC and Wall flag, you get:
prog.c: In function 'countDigits':
prog.c:32:1: warning: control reaches end of non-void
function [-Wreturn-type]
}
^
Tip: Think of what your function does if n us different than zero.
count is a global variable.
The function countDigits(n) adds the number of decimal digits in n to count and
If n is zero it returns 1.
If n is non-zero the return value is undefined.
Since countDigits(435) has an undefined value, anything can happen and no further analysis is necessary.
Let's assume that this obvious error is corrected by inserting return count; after count++;. In this case, the function returns the incremented count.
So we have this nice sequence:
Set result to countDigits(435).
countDigits(435) adds 3 to count and returns 3.
Set i to 0 and compare to countDigits(435).
countDigits(435) adds 3 to count and returns 6. 0 is less than 6, so the for loop continues.
Now i is 1, and we compare it to countDigits(435).
countDigits(435) adds 3 to count and returns 9. 1 is less than 9, so the for loop continues.
Now i is 2, and we compare it to countDigits(435).
countDigits(435) adds 3 to count and returns 12. 2 is less than 12, so the for loop continues.
... And so on.
Morality:
Beware of side effects. Never use and modify global variables unless you have a good reason to.
When you must use side effects, keep them prominent in your mind.
It is possible to compare a variable directly with the output of a function. However, your function countDigits has several problems.
Not all code paths return a value - you're missing a return statement in the else block. This alone makes the output of the function undefined.
It's not algorithmically correct. Have you tried debugging it? Just start with printing the output for different inputs and you'll see.
Modifying and returning a global variable count inside that function is a really bad practice - it should be local to the function. When it's global, every call to the function modifies a [possibly] already modified variable.
Others have already addressed the problem here with globals, so I will not go into details about that. Instead, here is a solution without globals:
int countDigits(int n) {
int count = 0;
while(n>0) {
n/=10;
count++;
}
return count;
}
I guess you could be philosophical about whether 0 has 0 or 1 digit, but your code implied that you wanted it to be 0. If you want it to be 1 instead, just change the first row to int count = 1.

Understanding the following code

Give this code:
int solution(int X, int A[], int N) {
int *jumps = calloc(X+1, sizeof(int));
int counter = 0;
int i;
for(i=0; i<N; i++) {
if(A[i]<=X && *(jumps+A[i])!=1) {
*(jumps+A[i])=1;
if(++counter==X) {
return i;
}
}
}
free(jumps);
return -1;
}
Here is what I think I know:
1) int *jumps = calloc(X+1, sizeof(int));
This is making an array storing X+1 elements of an int type. Since it's
calloc they are all initialized as 0.
2) if(A[i]<=X && *(jumps+A[i])!=1)
This if statement's condition is that the element of A at index i is less than or equal to X and the second part I am confused with. I am totally confused what *(jumps+A[i])!=1) means. I know that whatever *(jumps+A[i]) is cannot equal 1.
3) if(++counter==X)
This also confuses me. I'm not sure what ++ does in front of counter. I thought ++ was used as adding an increment of 1 to something. Also, how does counter change? If given the example (5,[1,3,1,4,2,3,5,4]) it changes to 5 but I don't understand why.
So here is what i understand :
every value in A that is superior to X are ignored. (A[i] <= X)
every duplicate value in A are ignored : this is the purpose of (jumps+A[i]) statements.
lastly it will return the index of the current loop if your A array contains at least X unique values inferior to X.
Conclusion : if X is 10. Then it will return the index of A when the function will have found every value from 0 to 9 once whatever their order is. If not found return -1. The ++counter make it so it will stop a 9 and not 10.

give me a hand to understand this code

i have to write a c code that finds minimum of an array using recursion.i found this in the internet, but i don't understand it very well, can someone help me understand it?
#include <stdio.h>
int a[100],i;
void read(int i,int n)
{
if(i>=n)
return;
printf("element %d",i);
scanf("%d",&a[i]);
read(i+1,n);
}
int rec(int a[],int n)
{
int min;
if(n==1)
return a[0];
else {
min=rec(a,n-1);
if(min<a[n-1])
return min;
else
return a[n-1];
}
}
void main()
{
int i,j,n,a[100];
printf("enter n :");
scanf("%d",&n);
read(0,n);
printf("\n%d",rec(a,n));
getch();
}
if n=1, then min. is a[0] as there is only one element.
if n>1, then it is calling rec with the array and n-1 as the length each time. So, there will be a time when n=1 and returns a[0]. Then it will compare a[0] with a[1]. And return the minimum. Then it will compare the returned value minimum with a[2] and return the smaller value....and so on.
It calculates the minimal value in the array. Look at it that way:
Suppose you're given an array with 10 numbers. A magician tells you the the minimal value of that last 9 elements is 5. You now take the first element and compare it to 5. if it's smaller you return it, otherwise you return 5. The magician is the recursive call to the array with the last n-1 numbers.
rec(a, n) return the minimum value in {a[0], ..., a[n-1]}
Now we discuss two cases:
If n = 1, then rec(a,n) should be a[0], since there is only one value
Otherwise, rec(a,n) should be the minimum value of rec(a,n-1) (that is, the minimum value in {a[0],..,a[n-2]}) and a[n-1], which is what the following code do:
min=rec(a,n-1);
if(min<a[n-1])
return min;
else
return a[n-1];
int rec(int a[],int n)
{
int min;
if(n==1)
return a[0];
else {
min=rec(a,n-1);
if(min<a[n-1])
return min;
else
return a[n-1];
}
}
This function will go through all of your array elements, then compare them one by one, and each time return the smaller one, giving you the minimum of your array :
example : for a = {10,2,4,5}
rec will start from 5 and just calls itself with the previous elem until he's at the first : 10
then will return 10
will compare 10 with 2 and return 2 because 2 < 10
will compare 2 with 4 and return 2 because 2 < 4
will compare 2 with 5 and return 2 because 2 < 5
This program reads a size of an array the user wants to input, next it calls "read" which reads array elements of the given size recursively and fills in global array "a". Next it tries to find a minimal value of the local "a" array using recursive function "rec", that is initialized with garbage by the fact of being of "auto" variable type and types this value to the terminal screen. Next it waits for the user to type any character.

Resources