Reputation: 1516
I am trying to produce this output without multiplication:
81 100 121 144 169 196 225 256 289
I produced that with this for loop:
for (int k = 9; k <=17; k++){
System.out.print( k * k +" ");
}
But again, I am trying to create a for loop or nested for loops producing the same output without multiplication.
Pseudocode:
Start with value 81
Increment by 19
On the second loop add ++3 to the 19 value
I have not been able to get to the second for loop stage I am confused. Any feedback or push in the right direction is appreciated.
/**
* Created on 8/28/15.
* Following Reges, Stuart, and Martin Stepp. Building Java Programs: A Back to Basics Approach. 3rd Edition.
* Chapter 2 Self-Check Problems & Exercises
*/
public class Ch2_SelfCheckProblems {
public static void main(String[] args) {
ex2();
}
public static void ex2(){
for (int i = 81; i <= 289; i=i+19){
/*for (int j = 1; j >=( i - 81 );j++){
// System.out.print(j+" ");
// System.out.print(i + " ");
}*/
// System.out.print(i + " ");
}
// System.out.println();
/* for (int k = 9; k <=17; k++){
System.out.print( k * k +" ");
}*/
for (int k = 81; k <=289; k++){
for (int j = 1; j <= 1; j++){
k = k + 8;
}
System.out.print( k +" ");
}
}
Upvotes: 0
Views: 928
Reputation: 201527
If I understand your question, you could use addition instead of multiplication. Something like
public static void main(String[] args) {
for (int k = 9; k <= 17; k++) {
int t = 0;
for (int j = 0; j < k; j++) {
t += k;
}
System.out.print(t + " ");
}
System.out.println();
}
Output is (the requested)
81 100 121 144 169 196 225 256 289
Another option would be Math.pow(double, double)
public static void main(String[] args) {
for (int k = 9; k <= 17; k++) {
System.out.print((int) Math.pow(k, 2) + " ");
}
System.out.println();
}
for the same output. Finally, from @mschauer's comments below, you could also use something like
public static void main(String[] args) {
for (int r = 64, k = 9; k < 18; k++) {
r += k + k - 1;
System.out.printf("%d ", r);
}
System.out.println();
}
Upvotes: 3