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 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:

(Re-posted from The Java Mint Blog)

Share

About Mathias

Software development engineer. Principal developer of DrJava. Recent Ph.D. graduate from the Department of Computer Science at Rice University.
This entry was posted in DrJava, Mint. Bookmark the permalink.

Leave a Reply