Loops in JavaIn programming languages, loops are used to execute a set of instructions/functions repeatedly when some conditions become true. There are three types of loops in Java.
Java For Loop vs While Loop vs Do While Loop
Java For LoopThe Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop. There are three types of for loops in java.
Java Simple For LoopA simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value. It consists of four parts:
Syntax: Flowchart: Example: Output: 1 2 3 4 5 6 7 8 9 10 Java Nested For LoopIf we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes. Example: Output: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 Pyramid Example 1: Output: * * * * * * * * * * * * * * * Pyramid Example 2: Output: * * * * * * * * * * * * * * * * * * * * * Java for-each LoopThe for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation. It works on elements basis not index. It returns element one by one in the defined variable. Syntax: Example: Output: 12 23 44 56 78 Java Labeled For LoopWe can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop. Usually, break and continue keywords breaks/continues the innermost for loop only. Syntax: Example: Output: 1 1 1 2 1 3 2 1 If you use break bb;, it will break inner loop only which is the default behavior of any loop. Output: 1 1 1 2 1 3 2 1 3 1 3 2 3 3 Java Infinitive For LoopIf you use two semicolons ;; in the for loop, it will be infinitive for loop. Syntax: Example: Output: infinitive loop infinitive loop infinitive loop infinitive loop infinitive loop ctrl+c Now, you need to press ctrl+c to exit from the program. Next TopicJava While Loop
|