hi can someone explain this small code how its work :

/**
 * @(#)Output.java
 *
 *
 * @author
 * @version 1.00 2011/12/24
 */


public class Output {


    public static int rec(int x, int n)
    {
        if (n < 0)
        {
            System.out.println("Illegal argument");
            System.exit(0);
        }

        if (n > 0)
            return ( rec(x, n - 1)*x );
        else
             return 1;
    }
public static void main(String[] args) {
        for (int n = 1; n < 3; n++)
            System.out.println("3^" +n+ " is " + rec(3, n));
    }
	}

output:
3^1 is 3
3^2 is 9

---
and the other is

public class Q3E {
	public static void main(String[] args) {
		System.out.println(recursive(158));
	}
	public static int recursive(int n) {
		if (n > 0)
			return recursive(n/10) + 1;
		else
			return 0;
	}
}

output= 3

Edited 4 Years Ago by programing: n/a

First program recursively calculates n to the power of x.
Second program recursively calculates the number of digits of n.

Edited 4 Years Ago by predator5047: n/a

First program given values x=2 , n= 4:

rec(x=2,n=4)
n is grater then 0 returns rec(x=2,n=3)*2;

rec(x=2,n=3)
n is grater then 0 returns rec(x=2,n=2)*2;

rec(x=2,n=2)
n is grater then 0 returns rec(x=2,n=1)*2;

rec(x=2,n=1)
n is grater then 0 returns rec(x=2,n=0)*2;

rec(x=2,n=0)
n is equal to 0 return 1;

rec(x=2,n=1) is equal to rec(x=2,n=0) * 2 witch is 1 * 2 = 2

rec(x=2,n=2) is equal to the value of rec(x=2,n=1) * 2 witch is 2 * 2 = 4

rec(x=2,n=3) is equal to the value of rec(x=2,n=2) * 2 witch is 4 * 2 = 8

rec(x=2,n=4) is equal to the value of rec(x=2,n=3) * 2 witch is 8 * 2 = 16

This article has been dead for over six months. Start a new discussion instead.