Java Notes: Using Loops with for and for-each
What is a Loop?
A loop repeats code multiple times.
Loops are useful when you want to:
- print something many times
- count numbers
- go through an array
- add values together
- process a list of data
Two important Java loops are:
1. The for Loop
A for loop is used when you know how many times you want the loop to run.
Basic Syntax
for (initialization; condition; update)
{
// code to repeat
}
Parts of the for Loop
- Initialization - This creates and starts the loop variable.
- Condition - The loop runs while this is true.
- Update - This changes the loop variable after each loop.
Example parts:
Initialization: int i = 0
Condition: i < 5
Update: i++
Example: Print numbers 1 to 5
for (int i = 1; i <= 5; i++)
{
System.out.println(i);
}
1
2
3
4
5
2. Commands Commonly Used with a for Loop
System.out.println()
Prints output to the screen.
System.out.println("Hello");
Example with a loop
for (int i = 0; i < 3; i++)
{
System.out.println("Hello");
}
Hello
Hello
Hello
i++
Adds 1 to the variable.
i++;
Same as:
i = i + 1;
i--
Subtracts 1 from the variable.
i--;
Example: Count backward
for (int i = 5; i >= 1; i--)
{
System.out.println(i);
}
+=
Adds a value other than 1.
i += 2;
Example: Count by 2s
for (int i = 0; i <= 10; i += 2)
{
System.out.println(i);
}
0
2
4
6
8
10
3. Using a for Loop with Arrays
An array stores multiple values in one variable.
Example array
int[] nums = {10, 20, 30, 40};
Use a for loop to visit each element
for (int i = 0; i < nums.length; i++)
{
System.out.println(nums[i]);
}
Important command: .length
.length tells how many items are in an array.
nums.length
In this example, nums.length is 4.
4. The for-each Loop
A for-each loop is used to go through every item in an array or collection.
It is simpler than a regular for loop when you do not need the index.
Basic Syntax
for (dataType variableName : arrayName)
{
// code to repeat
}
Example: Print each number in an array
int[] nums = {10, 20, 30, 40};
for (int num : nums)
{
System.out.println(num);
}
10
20
30
40
Example: Print each name in a String array
String[] names = {"Joe", "Ana", "Luis", "Mia"};
for (String name : names)
{
System.out.println(name);
}
5. Commands Commonly Used with a for-each Loop
System.out.println()
Used to print each item.
for (String name : names)
{
System.out.println(name);
}
Adding values with a loop
You can use a for-each loop to total numbers.
int[] nums = {5, 10, 15, 20};
int sum = 0;
for (int num : nums)
{
sum = sum + num;
}
System.out.println(sum);
50
6. for Loop vs for-each Loop
Use a for loop when... |
Use a for-each loop when... |
| you need the index |
you want every item in an array |
| you want to count up or down |
you do not need the index |
| you want to skip by 2s, 5s, etc. |
you want simpler code |
| you want more control |
you are mainly reading each value |
Regular for loop
int[] scores = {90, 85, 100, 70};
for (int i = 0; i < scores.length; i++)
{
System.out.println(scores[i]);
}
for-each loop
int[] scores = {90, 85, 100, 70};
for (int score : scores)
{
System.out.println(score);
}
Both print the same values, but the for-each loop is shorter.
7. Common Mistakes
Mistake 1: Missing semicolons in a for loop
Wrong:
for (int i = 0 i < 5 i++)
Correct:
for (int i = 0; i < 5; i++)
Mistake 2: Going past the end of an array
Wrong:
for (int i = 0; i <= nums.length; i++)
Correct:
for (int i = 0; i < nums.length; i++)
Why? Because the last index is length - 1.
Mistake 3: Using for-each when you need the index
A for-each loop gives the value, not the position.
for (int num : nums)
{
System.out.println(num);
}
You get the value, but not the index number.
8. Example Programs
Example A: Using a for loop
public class ForExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
System.out.println("Number: " + i);
}
}
}
Example B: Using a for-each loop
public class ForEachExample
{
public static void main(String[] args)
{
String[] colors = {"Red", "Blue", "Green"};
for (String color : colors)
{
System.out.println(color);
}
}
}
Example C: Add numbers in an array
public class SumExample
{
public static void main(String[] args)
{
int[] nums = {2, 4, 6, 8};
int total = 0;
for (int num : nums)
{
total = total + num;
}
System.out.println("Total = " + total);
}
}
9. Quick Summary
for loop - repeats code a certain number of times
for loop - uses initialization, condition, and update
for loop - best when you need the index
for-each loop - goes through every item in an array
for-each loop - easier to read
for-each loop - best when you do not need the index
10. Practice Questions
- What are the 3 parts of a
for loop?
- What does
i++ mean?
- What does
.length do?
- When should you use a
for-each loop?
- Why is this wrong?
for (int i = 0; i <= nums.length; i++)
11. Mini Practice
- Write a
for loop that prints numbers 1 through 10.
- Write a
for loop that prints even numbers from 2 to 20.
- Write a
for-each loop that prints each value in this array:
int[] data = {4, 8, 12, 16};
- Write a loop that adds all numbers in an array.