Reputation: 17
I am tyring to write a program that reads an integer n from the keyboard, and prints n, n-1, ... n, using a recursive function. The code below works, but I don't completely understand why or the steps involving the recursive function. Could someone please explain?
void countingdown(int n){
if (n == 1){
printf("%d\n", n);
return;
}
else {
printf("%d\n", n);
countingdown(n - 1);
return;
}
}
int main(){
int n;
printf("Enter an integer: ");
scanf("%d", &n);
countingdown(n);
printf("\n");
return 0;
}
Upvotes: 0
Views: 2330
Reputation: 24726
If, for example, the user enters the value 3, then the following will happen:
main
will call countingdown
with the parameter 3
.countingdown
will then compare this parameter 3
with the value 1
, and, since that comparison evaluates to false, it will print the number 3
and then call countingdown
(i.e. the function will call itself) with the parameter 2
.countingdown
will now compare this parameter 2
with the value 1
, and, since that comparison evaluates to false, it will print the number 2
and call countingdown
with the parameter 1
.countingdown
will now compare the parameter 1
with the value 1
, and since that comparison now evaluates to true, it will print the number 1
and will not call itself again.The recursive function treats the parameter 1
as special, since that is the value at which it should abort. When it encounters this value, it will stop calling itself recursively. If the function did not check for this special value, it would continue counting down forever and would also print 0
, -1
, -2
, etc.
Upvotes: 1
Reputation: 2658
You can rewrite the recursive function countdown()
Similar to this
int countingdown(int n){
if (n == 0){//return exit from recursion
return;
}
else {
printf("%d\n", n);
countingdown(n - 1);
}
}
Suppose we call it with countdown(5)
.
Until we reach to 0
printing n, i.e 5, 4, 3, 2, 1 will continue. In last step that variable n reach to 0 as we express in if section function returns and its execution ends.
[Edit]
Better one
void countingdown(unsigned int n){
if (n){
printf("%d\n", n);
countingdown(n - 1);
}
}
Upvotes: 1