Looping:-
To repeat a statement number of times
1.while - entry control
2.for
3.do while – execution control
4.for each
1.Entry control/while
while(condition)
{
}
2.
do
{
}
while(condition);
Note:-
We want to run infinite loop then use
While(true)
{
}
3.For loop
For(initialise;condition,increment)
{
}
Eg.
for(i=1;i<=10;i++)
{
}
System.out.print(“i=”+i);
Result:-
i=11
for(i=10;i>=0;i--)
{
}
System.out.print(“i=”+i);
Result:-
i=-1
Note:-If we skip the bracket then only one statement will be included in the loop
i.e.
for;
means
for
;
Eg.for(i=10;i>0;i--);
System.out.print(“i”+i);
Result:-
i=0
Unlabelled Statements:-
While(condition)
{
If(condition)
break;
}
Then this will break from while loop.
Note:- break will break from inner most loop.
Eg.
for(i=1;i<=10;i++)
{
System.out.print(“i=”+i);
if(i==5)
break;
}
Result:-
12345
Eg.
for(j=1;j<=10;j++)
{
for(i=1;i<=10;i++)
{
System.out.print(“i=”+i);
if(i==j)
break;
}
Result:-
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
Continue:-skip the current iteration
Eg.
for(i=1;i<=10;i++)
{
if(i==5)
continue;
System.out.print(“i=”+i);
}
Result:-
1234678910
Eg.
for(j=1;j<=10;j++)
{
for(i=1;i<=10;i++)
{
if(i=j)
continue;
System.out.print(“i=”+i);
}
}
Result:-
2345678910
1345678910
1245678910
1235678910
1234678910
1234578910
1234568910
1234567910
123456789
Eg.
while(true)
{
for(i=1;i<=10;i++)
{
if(i==5)
break;
System.out.print(“i=”+i);
}
}
Result:-
1234
1234
1234
-----
upto infinity
Labelled Statements:-
eg.
start:
for(j=1;j<=10;j++)
{
for(i=1;i<=10;i++)
{
if(i==j)
break start;
System.out.print(“i=”+i);
}
}
It will break from label i.e start.


No comments:
Post a Comment