What does this function do ?

When executed the program outputs :

The result is 55.

I'm not sure how that result was processed any help or hints would be much appreciated. Thank you for your time in advanced.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<stdio.h>
#define SIZE 10

int whatIsThis(const int b[], size_t p);//function prototype

//function main begins program execution
int main (void)
{
    int x; //holds return value of function whatIsThis
    //initialize array a
    int a[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    x = whatIsThis(a, SIZE);
    printf("Result is %d\n", x);
}
// what does this function do?
int whatIsThis(const int b[], size_t p)
{
    //base case
    if (1 == p){
        return b[0];
    }
    else{//recursion step
        return b[p-1]+whatIsThis(b, p-1);
    }
    }
Last edited on
If the condition at line 20 is false - which it is, in the call on line 13, then you don't have a return statement, so you have undefined behaviour. That's why you're getting a weird number.

Surely your compiler warned you about this when you compiled your code?
Realized the full code didn't copy over, its fixed now. It now returns 55.
Realized the full code didn't copy over, its fixed now. It now returns 55.

What is the problem with 55?
Just write out what it's doing at each step. If you don't understand what some code is doing just by looking at it going to paper is always a good way to analyze it. You can also work backwards and look at the input vs the output and try and figure out the relationship, then see how the code creates that relationship.
lFoxiel wrote:
I'm not sure how that result was processed any help or hints would be much appreciated.
Maybe this will help you work out what is going on...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<stdio.h>
#define SIZE 10

int whatIsThis(const int b[], size_t p);//function prototype

//function main begins program execution
int main (void)
{
    int x; //holds return value of function whatIsThis
    //initialize array a
    int a[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    x = whatIsThis(a, SIZE);
    printf("Result is %d\n", x);
}
// what does this function do?
int whatIsThis(const int b[], size_t p)
{
    //base case
    if (1 == p){
        printf("%d \n ", b[0]);
        return b[0];
    }
    else{//recursion step
        printf("%d + ", b[p-1]);
        return b[p-1]+whatIsThis(b, p-1);
    }
}
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 
 Result is 55
Topic archived. No new replies allowed.