3. nested for loop
- Nested for loop means, one for loop holds another for loop
Syntax:
for(outer loop initialization; outer loop expression; outer loop increment/decrement)
{
for(inner loop initialization; inner loop expression; inner loop increment/ decrement )
{
statements;
}
}
You are under Outer loop section :
- outer loop initialization is as assignment operation, a variable assigns with initial value.
- outer for loop holds an outer loop expression.
- outer loop expression gives the result either true or false.
- If the outer loop expression result is true then,
- Control enters into nested for loop means, inner for loop.
You are under inner loop section :
- Inner loop initialization is as assignment operation, a variable assigns with initial value.
- Inner for loop holds an inner loop expression.
- Inner loop expression gives the result either true or false
- Inner for loop holds an inner loop expression.
- If the inner loop expression result is true then it executes the inner loop statements.
- Once the inner loop statements execution done then inner loop initialized value will be increments / decrements to one.
- Again inner loop expression produces either true or false result.
- If true it executes the inner loop statements.
- If result is false, then control will enter into Outer loop increment/decrement section and outer loop initialized value increments/decrements to one
- Now outer loop expression will evaluates with incremented/decremented value and produces the either true or false.
- Based on the result its takes decision for next step.
- Thank God Nested loop explanation Done.
--------------------------------------------------------------------------------
Program : A program to print triangle starts
Program name : NestedForDemo1.java
Output :
*
**
***
****
*****
class NestedForDemo1
{
public static void main(String args[])
{
int r = 5;
for(int i = 1; i<=r; i++)
{
for(int st = 1; st<=i; st ++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Compile : javac NestedForDemo1.java
Run : java NestedForDemo1
Output :
*
**
***
****
*****
--------------------------------------------------------------------------------
Thanks for your time.
- Nireekshan