Java For Loop to iterate 100 64 36 16 4 0 4 16 36 64 100 using one variable
I want to write a for loop in the format below using only one variable e. White space (____) is the only thing I want to change. It should print 100 64 36 16 4 0 4 16 36 64 100. I'm not sure how to get it to repeat after reaching 0 .:
for(_____________________)
System.out.print(______________ + " ");
System.out.println();
This is what I have tried so far. Is there a way to only use one variable e and still use it to iterate through the numbers already in use ?:
for(int e = 10; e > 0; e -= 2)
System.out.print(e * e + " ");
System.out.println();
source to share
Take advantage of the fact that 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. And it's generally a good idea to add parentheses to:
for (int e = -10; e < 11; e += 2) {
System.out.print (e * e + " ");
}
System.out.println();
source to share
To take advantage of the fact that a negative number multiplied by a negative number gives a positive number, we can use your current solution. So, for example, e = 2 gives you 4 and e = -2 also gives you 4. So we can make a minor adjustment to your function:
for(e = 10; e >= -10; e -= 2)
System.out.print(e * e + " ");
System.out.println();
This should give 100 64 36 16 8 4 0 4 8 16 36 64 100.
source to share
The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the task of programming with complete humility, and among other things he avoids clever tricks such as the plague.
- Edser V. Dijkstra
for(int e : new int[]{ 100, 64, 36, 16, 4, 0, 4, 16, 36, 64, 100 }) {
System.out.print(e + " ");
}
System.out.println();
source to share