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

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

i want to know steps how working

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.