Multiple initialization and update Expression:
A for loop may contain multiple initialization and/or multiple update expression.
for(i=1,sum=0;i<=n;sum+=i,++i)
System.out.println(i);
Optional Expression:
All the three expressions of the for loop are optional.
for(;test-expression;update-expression(s))
OR
for(initailization;test-expression;)
OR
for(;test-expression;)
Infinite Loop:
An infinite loop is an endless loop which can be created by omitting the test-expression.
for(j=25; ;--i)
System.out println("coderzpy!");
Empty Loop:
This is also known as a time delay loop, which is often used in programs
for(j=20;k>=0;--i)
Nested Loop:
A loop may contain another loop inside its body. This form of a loop is known as nested loop
Note: The inner loop must terminate before the outer loop.
class Demo {
public static void main(String[] args) {int i,j;
for(i=1;i<=5;i++){
for(j=1;j<=i;j++){
System.out.print("*");
}
System.out.println(" ");
}
}
}
Output:
*
**
***
****
*****
Comparison of Loops:
Though Java loops can be used in almost all situations, yet there are some situations where one loop fits better than the other.
- The for loop is appropriate when you know in advance how many times the loop will be executed.
- The while and do-while loops are more suitable in the situations where it is not known beforehand when the loop will terminate.
- The while should be preferred when you may not want to execute the loop body even once.
- do-while is preferred when you’re sure you want to execute the loop body at least once.
Note: also read about the Iteration Statements(Loops)
Follow Me
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment