0

Whenever I define the parameter i in the function exam as an integer it always prints Sum = 0.00.

I would like to know why it is doing that...

#include <stdio.h>
#include <stdlib.h>

float exam(float i) {
    if (i == 0) {
        return 0;
    } else {
        return (i / (i + 1)) + exam(i - 1);
    }
}

int main() {
    int i;
    printf("Enter an integer: ");
    scanf("%d", &i);
    printf("Sum = %.3f", exam(i));
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Rix
  • 19
  • 4

1 Answers1

1

If you define i as an int, the first part of the expression (i / (i + 1)) + exam(i - 1) is evaluated using integer arithmetics, hence i / (i + 1) has the value 0 and every recursive call adds 0 until i reaches 0, so the final result is 0.

Note also that the code would have undefined behavior for negative inputs as one of the calls would pass -1 and i / (i + 1) would cause a division by zero which has undefined behavior and usually causes program termination.

Another invalid input is INT_MAX for which i + 1 causes a arithmetic overflow.

Defining i as a float removes these shortcomings and computes the expected result. Using double instead of float for both the argument and return type would increase the precision of the computation.

chqrlie
  • 131,814
  • 10
  • 121
  • 189