// Exercises:

1.    What’s the screen output of running the following program?

2.    Rewrite the recursively defined function algorithm( ) using iteration. Click this link to see a sample solution.

 

//======================================================
import java.util.*;
 

public class RecurExample {

 

   public static void main(String [ ] args) {

 

       int j=21;

       int k=5;

       System.out.println("-------OUTPUT------");

       algorithm(j,k);

   }

 

       static public int algorithm(int j, int k) {

            int temp;

            System.out.println(j + "\t"+ k);

            if (j < k) return j+k;

            else {

                  temp = algorithm(j/2, k) + j + k;

                  System.out.println (j + "\t" + k + "\t" + temp);

                  return temp;

            }

     }

}

//======================================

 

A sample solution of converting from recursion to iteration:

 

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

 

import java.util.*;

 

/**

 *

 * @author Junior

 */

public class NewClass {

 

    public static void main(String[] args) {

 

        int j;

        int k;

 

        Scanner in = new Scanner(System.in);

 

        System.out.println("what is J?");

        j = in.nextInt();

        System.out.println("what is K?");

        k = in.nextInt();

 

        System.out.println("-------OUTPUT------");

 

        if (j > k && k > 0 && j > 0) {

            algorithm(j, k);

        } else {

            System.out.println(j + k);

        }

 

    }

 

    static public void algorithm(int j, int k) {

 

        int denominator;

        int i;

        int tempj = j;

 

        for (i = 0; tempj >= k; i++) {

            denominator = (int) java.lang.Math.pow(2, i);

            tempj = (j / denominator);

 

            System.out.println(tempj + " " + k);

        }

 

        int total = tempj + k;

 

        for (int h = i - 2; h >= 0; h--) {

            denominator = (int) java.lang.Math.pow(2, h);

            tempj = (j / denominator);

 

            total = total + k + tempj;

 

            System.out.println(tempj + " " + k + " " + total);

        }

    }

}