Wednesday, September 9, 2009

Power Using a for Loop

Soon it will be possible to compile and run Mint programs in
DrJava. I just haven't had time to finish this. In the meantime, here is a program that you can analyze. It is another program that calculates the power x^n.

import edu.rice.cs.mint.runtime.Code;


public class Power_For {
public static void main(String[] args) {
final double x = 2;
int n = 17;

Code<Double> c = <| 1.0 |>;
for(int i=0; i<n; ++i) {
c = <| `c * x |>;
}

System.out.println(c.run());
}
}


This time it uses a for loop. I don't know if you have seen for loops, but the part

for(int i=0; i<17; ++i) { /* something here */ }

sets a variable i to 0, and repeats the part /* something here */ as long as i<n. Each time the loop is done with /* something here */, it will execute ++i, which will increase i by 1. So eventually i will be 17, and since n is 17, i is not < n anymore, and the loop exits.

We have a Code<Double> c that starts out with the code for 1.0:

Code<Double> c = <| 1.0 |>;

Then we have the aforementioned for loop. The code that gets executed
over and over in the loop body is

c = <| `c * x |>;

We are creating a new code value, and inside the code value, we're splicing in c (initially 1.0) and multiplying it with x. Then we assign the new code value back to c. That means after the first
iteration of the loop, c will be the following:

<| 1.0 * x |>

After the second iteration, c will be

<| 1.0 * x * x |>

And so on. After the 17th iteration, it will contain the code

<| 1.0 * x * x * x * x * x * x * x * x * x * x * x * x * x
* x * x * x * x |>


When we run c with c.run() and print out the value, we will get 131072.0, which is 2 to the power of 17, as expected.

You can download the complete source code for the example here:

10 comments:

  1. Download Java in http://java.joydownload.com/

    ReplyDelete
  2. Most popular news web channel in the world...open this link
    http://newkhabar.in/

    ReplyDelete

  3. Very informative article.Thank you author for posting this kind of article .


    http://www.wikitechy.com/view-article/power-function-in-c-with-example-and-explanation



    Both are really good,
    Cheers,
    Venkat

    ReplyDelete