0% found this document useful (0 votes)
28 views

Java Recursion

The document contains examples of different types of recursion in Java code - tail recursion, indirect recursion, tree recursion, and an example converting tail recursion to a loop. It includes code snippets showing recursive functions for each type with explanations and driver code to call the functions.

Uploaded by

mayang kyut
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java Recursion

The document contains examples of different types of recursion in Java code - tail recursion, indirect recursion, tree recursion, and an example converting tail recursion to a loop. It includes code snippets showing recursive functions for each type with explanations and driver code to call the functions.

Uploaded by

mayang kyut
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

// Java code Showing Tail Recursion

class Tail{

// Recursion function
static void fun(int n)
{
if (n > 0)
{
System.out.print(n + " ");

// Last statement in the function


fun(n - 1);
}
}

// Driver Code
public static void main(String[] args)
{
int x = 3;
fun(x);
}
}

// Java program to show Indirect Recursion


import java.io.*;

class Indirect {

static void funA(int n)


{
if (n > 0) {
System.out.print(" " +n);

// Fun(A) is calling fun(B)


funB(n - 1);
}
}

static void funB(int n)


{
if (n > 1) {
System.out.print(" " +n);
// Fun(B) is calling fun(A)
funA(n / 2);
}
}

// Driver code
public static void main (String[] args)
{
funA(20);
}
}

import java.util.*;
class TimeComplexity
{
// Recursive function
static void fun(int n)
{
int i = 1;
while (i <= n) {
System.out.print(" "+ i);
i++;
}
}

// Driver code
public static void main(String[] args)
{
int x = 3;
fun(x);
}
}

// Java program to show Tree Recursion


class Tree
{

// Recursive function
static void fun(int n)
{
if (n > 0) {
System.out.print(" "+ n);
// Calling once
fun(n - 1);

// Calling twice
fun(n - 1);
}
}

// Driver code
public static void main(String[] args)
{

fun(3);
}
}

// Converting Tail Recursion into Loop


import java.io.*;
class TailRecursionintoLoop {
static void fun(int y)
{
while (y > 0) {
System.out.print(" "+ y);
y--;
}
}

// Driver code
public static void main(String[] args)
{
int x = 3;
fun(x);

}
}

You might also like