-
Notifications
You must be signed in to change notification settings - Fork 1
Loops
Chris Ward edited this page Oct 7, 2022
·
1 revision
Here is the code from the code example.
package examples.b_loop;
public class BasicLoop {
public static void main(String[] args) throws Exception {
for (int i=0; i < 5; i++) {
System.out.println("Hello, World! " + i);
}
}
}
Remember how we did loops in python? for i in range(0, 5)
Does that look familiar? What would this do?
Hello World! 0
Hello World! 1
Hello World! 2
Hello World! 3
Hello World! 4
Lets break this down.
-
int i=0;
this creates a variable of type int called i, and starts it at 0 -
i < 5;
like in the last part of range, this is the condition for how much we loop -
i++;
is a bit of math. It is like i = i + 1; We are incrementing the variable i by one;
Try and make some different loops.
- Can you start at 5 and stop at 10?
- Can you start at 10 and stop at 0?
- Can you start at 0 and stop at 10 but count by 2?
Time to make some decisions