Introduction
The for
loop in Java is a control flow statement that allows code to be executed repeatedly based on a condition. It is commonly used when the number of iterations is known beforehand.
Syntax of the For Loop
for (initialization; condition; increment/decrement) { // Code to be executed }
Key Points:
- The
initialization
step is executed once at the start of the loop. - The
condition
is evaluated before each iteration. If it evaluates tofalse
, the loop terminates. - The
increment/decrement
step is executed at the end of each iteration. - A
for
loop can be used with arrays, lists, and other collections.
Examples of the For Loop
1. Basic Example
for (int i = 1; i <= 5; i++) { System.out.println("Value of i: " + i); }
Output:
Value of i: 1 Value of i: 2 Value of i: 3 Value of i: 4 Value of i: 5
2. Using a For Loop with an Array
int[] numbers = {10, 20, 30, 40, 50}; for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); }
Output:
Element at index 0: 10 Element at index 1: 20 Element at index 2: 30 Element at index 3: 40 Element at index 4: 50
3. Enhanced For Loop (For-Each)
int[] numbers = {10, 20, 30, 40, 50}; for (int num : numbers) { System.out.println("Number: " + num); }
Output:
Number: 10 Number: 20 Number: 30 Number: 40 Number: 50
4. Nested For Loop
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.print("(" + i + ", " + j + ") "); } System.out.println(); }
Output:
(1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3)
Unsolved Problems
- Write a program to print 1,2,3,4,5,6,7,8,9,10 using
for
loop. - Write a program to find the sum of all even numbers between 1 and 100 using a
for
loop. - Write a program to print 2,4,6,8,10 using
for
loop. - Write a program to print 1,3,5,7,9 using
for
loop. - Write a program to print 1,4,9,16,,,,81,100 using
for
loop. - Write a program to print 2,6,12,20,,,,90 using
for
loop. - Write a program to print 1/1,1/2,1/3,1/4, 1/10 using
for
loop. - Write a program to print Print the Fibonacci Sequence using
for
loop. - Write a program to generate a multiplication table for a given number using a
for
loop. - Change a given number to its reverse form. 123 will become 321 using
for
loops.