What's new

Direct and indirect recursion

_see-u_in-dark_-

Honorary Poster
Established
Joined
Jul 14, 2023
Posts
368
Reaction
78
Points
147
Age
23
pagawa naman po ng direct and indirect recursion yung sarili po talaga ninyo gamit dev c++
 
Sure! I can explain direct and indirect recursion and provide an example using C++.

Direct recursion occurs when a function calls itself directly. In other words, a function is defined in such a way that it can call itself during its execution.

Indirect recursion occurs when two or more functions call each other in a circular manner. In this case, one function calls another function, which in turn calls the first function, and so on.

Now, let's see an example of direct recursion using C++:

C++:
#include <iostream>

void countdown(int n) {
    if (n > 0) {
        std::cout << n << " ";
        countdown(n - 1); // Recursive call
    }
}

int main() {
    int num = 5;
    countdown(num);

    return 0;
}

In the above code, we define a function countdown(int n) that takes an integer n as a parameter. Inside the function, we check if n is greater than 0. If it is, we print the value of n and recursively call the countdown() function with n-1 as the argument.

When we run the main() function, we initialize num as 5 and pass it to the countdown() function. The function starts counting down from 5 and prints each value until n becomes 0. The function calls itself repeatedly until the base condition (n > 0) is met.

Now, let's see an example of indirect recursion using C++:

C++:
#include <iostream>

void evenNumbers(int n);

void oddNumbers(int n) {
    if (n > 0) {
        std::cout << n << " ";
        evenNumbers(n - 1); // Call to evenNumbers()
    }
}

void evenNumbers(int n) {
    if (n > 0) {
        std::cout << n << " ";
        oddNumbers(n - 1); // Call to oddNumbers()
    }
}

int main() {
    int num = 10;
    oddNumbers(num);

    return 0;
}

In this example, we have two functions: oddNumbers() and evenNumbers(). The oddNumbers() function prints odd numbers in descending order and calls the evenNumbers() function with n-1 as the argument. The evenNumbers() function, in turn, prints even numbers in descending order and calls the oddNumbers() function with n-1 as the argument. This creates a circular call between the two functions.

When we run the main() function and pass num as 10, the oddNumbers() function starts printing odd numbers from 10 to 1, and for each odd number, it calls the evenNumbers() function. The evenNumbers() function then prints even numbers from 9 to 1 and calls the oddNumbers() function. This circular calling continues until the base condition (n > 0) is met.

I hope this explanation and example help you understand direct and indirect recursion in C++. Let me know if you have any further questions!
 
Back
Top