Reputation: 41
I want to write a for loop in the format below, using only a single variable e. The (____) blank spaces are the only things I want changed. It should print out 100 64 36 16 4 0 4 16 36 64 100. I'm not sure how get it to reiterate after it reaches 0.:
for(_____________________)
System.out.print(______________ + " ");
System.out.println();
This is what I tried so far. Is there a way to use only one variable e and still get it to reiterate through numbers it already used?:
for(int e = 10; e > 0; e -= 2)
System.out.print(e * e + " ");
System.out.println();
Upvotes: 3
Views: 835
Reputation: 10988
To take advantage of the fact that negative number multiplied to a negative number gives a positive number we can use your current solution. So as an example: e = 2 gives you 4 and e = -2 also gives you 4. Thus we can make a minor adjustment to your function:
for(e = 10; e >= -10; e -= 2)
System.out.print(e * e + " ");
System.out.println();
That should give 100 64 36 16 8 4 0 4 8 16 36 64 100.
Upvotes: 1
Reputation: 123480
The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague.
-- Edsger W. Dijkstra
for(int e : new int[]{ 100, 64, 36, 16, 4, 0, 4, 16, 36, 64, 100 }) {
System.out.print(e + " ");
}
System.out.println();
Upvotes: -1
Reputation: 12243
Use the fact the negative numbers multiplied by each other are positive and use e >= -10.
for (int e = 10; e > -11; e -= 2)
System.out.print(e * e + " ");
System.out.println();
I find it more readable to go negative to positive though. And it's generally a good idea to add the brackets in:
for (int e = -10; e < 11; e += 2) {
System.out.print (e * e + " ");
}
System.out.println();
Upvotes: 3
Reputation: 178263
Use the fact that e2 = (-e)2, and stop when e
is no longer greater than or equal to -10
.
Upvotes: 10