For - Part1 PDF
For - Part1 PDF
looping?
Why do we need
looping?
Put in video of
an Android timer
counting from
10 down to 1.
Unleash power of computer
... Time for human
out.println(10); to write one line
out.println(9); of code:
out.println(8);
out.println(7); ~2 seconds
out.println(6);
out.println(5); Time for computer
out.println(4); to execute one
out.println(3);
out.println(2); line of code:
out.println(1); ~0.001 seconds
...
Unleash power of computer
... Without loops…
out.println(10);
out.println(9);
out.println(8);
out.println(7); Humanity would
out.println(6);
out.println(5); spend more time
out.println(4);
out.println(3); writing code than the
out.println(2);
out.println(1); computer would
...
executing it!
Introduction to Java For Loops
Loops make repetition easier
Intuition:
"I want to print a line for each number from 1 to 5"
Loops make repetition easier
Java’s for loop: causes lines of code to be repeated
out.println(1 + " doubled = " + 2 * 1);
out.println(2 + " doubled = " + 2 * 2);
out.println(3 + " doubled = " + 2 * 3);
out.println(4 + " doubled = " + 2 * 4);
out.println(5 + " doubled = " + 2 * 5);
Does same as
for (int i = 1; i <= 5; i = i+1) {
out.println(i + " doubled = " + 2 * i);
}
Loops make repetition easier
Java’s for loop: causes lines of code to be repeated
out.println(1 + " doubled = " + 2 * 1);
out.println(2 + " doubled = " + 2 * 2);
out.println(3 + " doubled = " + 2 * 3);
out.println(4 + " doubled = " + 2 * 4);
out.println(5 + " doubled = " + 2 * 5);
Does same as
for (int i = 1; i <= 5; i = i+1) {
out.println(i + " doubled = " + 2 * i);
}
Read as: “for each integer i from 1 to 5, do…”
Execution of the Java
For Loop
Structure of the for loop