How will you terminate outer loop from the block of the inner loop?
Answers
In order to terminate the outer loop from the inner block , we need to use a break statement.
You also may use a flag variable for an advanced purpose :
Lets say for example :
for(int i=1;i<=4;i++)
{
for(int j=1;j<=6;j++)
{
System.out.print("Loser");
}
System.out.println("Lost");
}
_____________________________________________
if we want to terminate only the j-loop as soon as j=4 we should approach like
this :
for(int i=1;i<=4;i++)
{
for(int j=1;j<=6;j++)
{
if(j==4)
{
break;
}
else
{
System.out.print("Loser");
}
}
System.out.println("Lost");
}
_____________________________________________
This will help terminating the j-loop only when j=4.
If you still want to terminate the i-loop and the j-loop both when j=4 then code would be like this:
int flag=0;
for(int i=1;i<=4;i++)
{
for(int j=1;j<=6;j++)
{
if(j==4)
{
flag++;
break;
}
else
{
System.out.print("Loser");
}
if(flag==1)
{
break;
}
}
System.out.println("Lost");
}
____________________________________________
This time the system will exit both loops when j=4.
The i-loop and the j-loop will be exitted by the compiler .
That can be done by a flag variable only.
Hope it helps you ^__^
___________________________________________________________________