Categories: Java

More about loops

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

Share
Published by
Rabecca Fatima

Recent Posts

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

5 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

5 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

11 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

11 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

11 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

12 months ago