What it looks like:
How long it took: 30 min or so
What made it difficult: There are two loops in this problem. One says "From i being 0 to 10, print 2 to the i." The second loop is inside the private method, and it says "From i = 0 to the specified kth power, multiply the base by itself." Both loops use the same variable "i," and I can see a program like this getting confusing. However, it's unavoidable that you'll use the same variable name within a program; that I assume is because methods are built to be re-usable, so you'll never know which program you'll plunk them into.
I felt pretty comfortable with this re-use of "i" because both the book and Mehran's lecture went through tracing a program similar to this throughout multiple method calls and parameter passes. Going through strack frames in excruciating detail like this made me really aware of the "life cycle" of a program. Definitely a good foundation when learning about using private methods.
/*
/*
* File: RaisePowerWithMethod.java
* Name: Chu
* Section Leader:
* Description: This program asks us to write a program that writes out 2 to the nth power for
* n = 1 to n = 10. We accomplish this using the private method 'raiseIntToPower', which can take in
* any base and any raised power.
*/
package ch6_practice;
import acm.program.*;
public class RaisePowerWithMethod extends ConsoleProgram {
public void run() {
for(int i = 0; i < 10; i++) {
println (raiseIntToPower(2, i));
}
}
private int raiseIntToPower(int n, int k) {
int result = 1;
for (int i = 0; i < k; i++) {
result *=n;
}
return result;
}
}

No comments:
Post a Comment