Having trouble with for loops on java. How do I turn this while loop into a for loop?
public static void main(String[] args) {
int down;
down = 5;
while (down > 0) {
System.out.println(down);
down = down - 1;
I want to just countdown from 5 (5 4 3 2 1)
for (down = 5; down > 0 down-- );
This just outputs:
5
CodePudding user response:
You are reducing down
variable twice or more. You should remove down = down -1
line if you want to use for loop.
public static void main(String[] args) {
int down;
down = 5;
for (down=5;down>0;down--) {
System.out.println(down);
}
}
CodePudding user response:
You should revisit the Core Java concepts. That's not how we use for-loops. You need to specify the start of the loop, u need to specify the condition until when you want to stay inside the loop, and then iteration logic .. i.e forward or backward.
See below :
Code :
public static void main(String[] args) {
int down = 0;
for (down = 5; down > 0 ; down-- ){
System.out.println(down);
}
}
Output :
5 4 3 2 1