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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago