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

Efficient Order Log Storage

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

2 weeks ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 weeks ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

1 month ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

1 month ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

1 month ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

1 month ago