10 Java Fundamentals | For Loop in Java | By Dummy for Dummies
10 Java Fundamentals | For Loop in Java | By Dummy for Dummies
INTRODUCTION
Remember what we learned in English? "Since" is used for a specific point of time. "For" is used for a period of time.
Similarly in coding, While Loop is used for a specific point like "did the child get candy?" The For Loop is used for a specific period of time like "run the loop for 10 times, for 5 times, etc." That's how they are different and become useful for different purposes.
FOR LOOP
For Loop has a few more things though. It's like a time bomb, so you have to set a few things before it becomes functional: when to start, when to stop, and how to count from start to stop.
- Counter = It will keep track of how many times the loop ran
- Condition = It will check the condition i.e., did the counter reach the set time?
- Update = Instead of inside the loop code, for loop has a specific area for updating code. It updates the code after one iteration (running the loop for a single time is called iteration).
for (counter ; condition ; update) { // write the code here to repeat }
You set a counter, then set a condition, then it'll update, then the loop code will run.
public class ForLoopDemo { public static void main(String[] args) { // Print numbers 1 to 5 for (int i = 1; i < 6; i++) { System.out.println("Number: " + i); } System.out.println("Loop exited!"); } }
- The code sets
ito be 1, then checks if it's smaller than 6, then updates it by INCREMENTING for the next iteration. - The loop code runs, the
iwhich was equal to 1 is now equal to 2. - It will keep running. On the 5th iteration, the update will set i to be 6, the code will run that time. On the next start,
iwill not be less than 6, so the loop will end right there.
REVERSE FOR LOOP
For loop is not always ascending like from 0 to 10 or 0 to 5. You can actually code a for loop that starts from 10 and comes down to 0, just like a time bomb.
public class ReverseForLoop { public static void main(String[] args) { // Print numbers 5 to 1 for (int i = 5; i > 0; i--) { System.out.println("Number: " + i); } System.out.println("Loop exited!"); } }
- The code sets
ito be 5, then checks if it's greater than 0, then updates it by DECREMENTING for the next iteration. - The loop code runs, the
iwhich was equal to 5 is now equal to 4. - It will keep running. On the 5th iteration, the update will set i to be 0, the code will run that time. On the next start,
iwill not be greater than 0, so the loop will end right there.
POINTS TO REMEMBER
< or the loop will not start. In update, i must increase or the loop will become infinite.> or the loop will not start. In update, i must decrease or the loop will become infinite.i++ → For update by 1i = i + 2 → For update by 2i = i + 3 → For update by 3public class EvenNumbers { public static void main(String[] args) { // Print even numbers from 2 to 10 for (int i = 2; i <= 10; i += 2) { System.out.println("Even: " + i); } System.out.println("Done printing evens!"); } }
It prints up to 10, because the condition is i <= 10. Therefore, as long as i is less than or equal to 10, the loop will run.
EXERCISE
Let's do an exercise for what we studied in this post. Study this code, break it down, analyze it and identify the concepts used here. It would be even better if you write down your observations and make a mini report on it.
import java.util.Scanner; public class ForLoopExercise { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println(" For Loop Practice "); System.out.print("Enter a small positive integer (n): "); int n = sc.nextInt(); System.out.print("Enter a number for multiplication table (m): "); int m = sc.nextInt(); // 1) Count from 1 to n System.out.println("\n-- 1) Count from 1 to n --"); for (int i = 1; i <= n; i++) { System.out.println("Number: " + i); } // 2) Even numbers from 2 to n (step update) System.out.println("\n-- 2) Even numbers from 2 to n (i += 2) --"); for (int i = 2; i <= n; i += 2) { System.out.println("Even: " + i); } // 3) Reverse count from n to 1 System.out.println("\n-- 3) Reverse count from n to 1 --"); for (int i = n; i >= 1; i--) { System.out.println("Rev: " + i); } // 4) Sum and average of 1..n System.out.println("\n-- 4) Sum and average of 1..n --"); int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } System.out.println("Sum: " + sum); System.out.printf("Average: %.2f\n", (n > 0) ? (double) sum / n : 0.0); // 5) Multiplication table for m (1..10) System.out.println("\n-- 5) Multiplication table of " + m + " --"); for (int i = 1; i <= 10; i++) { System.out.println(m + " x " + i + " = " + (m * i)); } sc.close(); } }
MINI PROJECT: For Loop Multiplication Table
Your project is to create a simple Java program that prints the multiplication table of any number using a for loop. The program should ask the user to enter a number. Then it should use a for loop to print the table of that number from 1 to 10.
Example: If the user enters 6, the output should be:
- 6 x 1 = 6
- 6 x 2 = 12
- 6 x 3 = 18
- ...
- 6 x 10 = 60
While writing the program, make sure you use:
- Scanner for input
- A for loop that runs from 1 to 10
- printf or println to format the output properly
EXAMPLE OUTPUT
CLOSING
That's it for For Loop in Java. With For Loop you have control over where to start, when to stop, and how to count, whether you're counting up, counting down, or skipping numbers.