Loop Theory
Loop Theory
Exit Controlled loop which is also known as Post Tested Loop the condition is
checked at the end of the loop body, which means even if the condition is false the loop
gets executed at least for once.
E.g. do…while LOOP
do…while loop : This loop is similar to the while loop except the test expression
occurs at the bottom of the loop. this ensures that the body executes at least one time.
Syntax
do
{
...
} while (condition);
Always remember that a do…while statement has a semi-colon at its end.
If the body of a loop has more than one statement, you must put the statements inside
braces { }. If there is only one statement, it is not necessary to use braces { }.
Distinguish between:
(a) for and while loop
State one difference and one similarity between while and do-while loop.
Similarity: Both while and do-while loops are used when the number of iterations is not
fixed.
Dissimilarity: The while loop is entry-controlled, but the do-while loop is exit-controlled.
State one similarity and one difference between while and for loop.
Similarity: Both while and for loops are entry-controlled loops.
Dissimilarity: The for loop is a suitable choice when the number of iterations is fixed. The while
loop is a suitable choice when the number of iterations is not fixed.
break statement: when a break statement is used to terminates the current loop and
program control resumes at the next statement following the loop.
for(int i=1;i<=5;i++)
{
if(i==3)
break;
System.out.print(i+” “);
}
System.out.print(“loop is over“);
for(int i=1;i<=5;i++)
{
if(i==3)
continue;
System.out.print(i+” “);
}
System.out.print(“loop is over“);
We can initialize and update multiple variables in a for loop. These variables are separated
by comma (,).
for(i=1, j=10 ; i<=10 ; j-- , i++)
{
System.out.println("i=" +i+" "+"j="+j);
}
(b) Infinite loop : Infinite loop is a loop which executes indefinitely i.e. the given test-
expression is forever evaluated to true. For example,
for(int i=1;i>0;i++)
{
System.out.println(i);
}
The loop executes infinitely because the value of i is always greater than 0.
(c) Empty loop : Loop that is used to create a delay in the execution by creating a null
loop. If the loop doesn’t contain a body, it is called an empty loop. For example,
for(int i=1;i<=100;i++);
Notice the semicolon at the end of the parenthesis, indicating that the for loop
does not have body and therefore no statement is repeatedly executed again and
again.
Nested Loop : A loop within a loop is called a nested loop. The following example
shows how nested for loop works:
for(i=1;i<=3;i++)
{
for(j=1;j<=4;j++)
{
System.out.print(j);
}
System.out.println( );
}