So I have to do an assignment for school and I am creating an arrays program. I am practicing how to convert for loops to while loops, but I cannot grasp the concept. If I have the for loop:
int [] list = new int [5];
for (int i = 0; i < 5; i++) {
list [i] = i + 2;
}
How would I make it a while loop?
also, sorry this is my first time using the site :)
edit: here's my attempt
int [] list = new int [5];
int i = 0;
while (i<5) {
list [i] = i + 2;
i++;
}
System.out.print(list[i] + " ");
This is what I think should be done, but it comes up as an error in my computer.
edit #2:
The error says: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Arrays2.main(Arrays2.java:21)
The print code:
System.out.print(list[i] + " ");
//this is line 21^^
解决方案
The general structure of a basic for statement is:
for ( ForInit ; Expression ; ForUpdate ) Statement
ForInit is the initializer. It is run first to set up variables etc.
Expression is a boolean condition to check to see if Statement should be run
Statement is the block of code to be run if Expression is true
ForUpdate is run after the Statement to e.g. update variables as necessary
After ForUpdate has been run, Expression is evaluated again. If it is still true, Statement is executed again, then ForUpdate; repeat this until Expression is false.
You can restructure this as a while loop as follows:
ForInit;
while (Expression) {
Statement;
ForUpdate;
}
In order to apply this pattern to a "real" for loop, just substitute your blocks as described above.
For your example above:
ForInit => int i = 0
Expression => i < 5
ForUpdate => i++
Statement => list [i] = i + 2;
Putting it together:
int i = 0;
while (i < 5) {
list[i] = i + 2;
i++;
}