recursive function in c
#include <stdio.h>
void recursiveFunction(int n) {
if (n > 0) {
recursiveFunction(n - 1);
printf("%d ", n);
}
}
int main() {
int x = 5;
recursiveFunction(x);
return 0;
}
Explanation:
#include <stdio.h>
: Including the standard input-output library for using functions likeprintf
.void recursiveFunction(int n)
: Definition of a recursive function namedrecursiveFunction
that takes an integern
as an argument and returns void (i.e., doesn't return a value).if (n > 0) { recursiveFunction(n - 1); printf("%d ", n); }
: Inside therecursiveFunction
, thisif
statement checks if the value ofn
is greater than 0. If true, it calls itself recursively withn - 1
and then prints the value ofn
.int main() { ... }
: The main function where the program execution begins.int x = 5;
: Declares an integer variablex
and initializes it with the value5
.recursiveFunction(x);
: Calls therecursiveFunction
with the value ofx
(which is 5) as an argument.
When executed, this program will output:
1 2 3 4 5
This happens because the recursiveFunction
is called with 5
as an argument, and it recursively calls itself with decremented values until n
becomes 0
. At each recursive call, it prints the value of n
after the recursive call returns.