I I usually say that recursion is abused . They do where it is simpler to make a tie. But if it is to do recursion it has to be in functional style. recursive functions with more than one line are often philosophically wrong, even if the result is right:
#include <stdio.h>
int quant(int num1, int num2) {
return num1 < num2 ? quant(num1 + 1, num2) + (num1 % 2 == 0) : 0;
}
int main(int argc, char** argv) {
int n1,n2;
printf("Digite o primeiro numero: ");
scanf("%d", &n1);
printf("Digite o segundo numero, maior que o primeiro: ");
scanf("%d", &n2);
printf("A quantidade de pares entre %d e %d e' %d", n1, n2, quant(n1, n2));
return 0;
}
See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .
Now the function is recursive. It was difficult to see so because this is not a problem so clearly suitable for recursion.
Every recursive function must have a branch , that is, a decision that indicates when to terminate recursion, just as every loop has an exit condition. If you do not do this or enter loop infinity or give a default value if you do something that prevents infinite recursion.
What I have done is to establish which is the condition that ends the recursion and it is one:
num1 < num2
This is the condition that would end the loop and this is what I used to decide the end, and only in the end is that the value should be 0. In your code it is worth 0 in all cases, so it gives 0.
But it has a condition that determines whether to add 1 or not. This in more imperative code would be if
and could not be close to the exit condition of the recursion. Joining both was another mistake. This would be the check whether it is even or not:
num1 % 2 == 0
Actually in C it's common to just do:
num1 & 1
I did not use if
because it is a bit expensive and in this case it is not necessary, after all the result of this account will be 0 or 1, which is the same result as if
generates, so better not to use it since the cost will be lower (if the compiler fails to optimize).
Use the conditional operator to stay on a line. In functional style code, the imperative style with if
is weird.