Loops
Different Types of Loop
- For loop
- While loop
- Do-while loop
- For-each loop
For loop
For loop is a control structure in programming that allows you to repeat a block of code a specific number of times.
1 2 3 |
|
-
Condition: Before each iteration, this condition is evaluated. If it is true, the loop continues; if false, the loop ends.
-
Increment: This step updates the loop counter after each iteration.
EXAMPLE
For Loop Example: Printing Numbers from 1 to 10
1 2 3 4 |
|
Explanation of above code
-
Initialization:
int i = 1
Starts the counter at 1. -
Condition:
i <= 10
Continues the loop whilei
is less than or equal to 10. -
Increment:
i = i + 1
Increasesi
by 1 after each iteration. -
Loop Body:
ExecutesSystem.out.println(i);
to print the current value ofi
to the console, outputting numbers from 1 to 10.
While loop
The while loop loops through a block of code as long as a specified condition is true
1 2 3 |
|
While Loop Example: Printing Numbers from 1 to 10
1 2 3 4 5 6 |
|
Explanation
- Initialization:
-
int i = 1;
Initializes the counter variablei
to1
. -
Condition:
-
while (i <= 10)
Checks ifi
is less than or equal to10
. The loop executes while this condition istrue
. -
Loop Body:
-
System.out.println(i);
Prints the current value ofi
to the console. -
Increment:
i++;
Incrementsi
by1
after each iteration.
For loop and while loop are similar
When we dont know the stop value,we can prefer while loop instead