Monday, April 6, 2009

C Sharp goto statement for breaking the nested loop

Two days back, while discussing
with a friend came a small interesting (programming) situation where he wanted
to stop (break) a loop which was inside another loop.



You can think of the situation as
he was first looping through all the rows in a grid view and then in the entire
column in the grid view. Now he was trying to look into the text of each cell,
and if the text matched a given value, he needed to break from both the loop and
execute the statement after the loop.



His first idea was to use a flag
which will be checked in the outer loop every time to see if the value has been
found in the inner loop. The code would be something like below.



bool flag = false;


for(int i =
0;i<grd.Rows.count;i++)
{
if(flag==true)
{ break; }

for(int j= 0;j<grd.Columns.count;j++)
{

if(grd.Rows[i][j].ToString() == “someValue”;
flag = true;

Break;
}
}


// Statement to executed after
loop.



I am sure most of us have faced
some or other situation where we had some requirement like this and the solution
provided was also similar.



The code does the work that we
want it to do, but if you look deeply it has a problem. I have to check the
value of the flag for each time there is a loop for the row and also to maintain
a tedious flag for a just breaking the loop.



The same work can be easily done
without using a flag, by using a goto statement like this.



for(int i =
0;i<grd.Rows.count;i++)
{
for(int j=
0;j<grd.Columns.count;j++)
{
if(grd.Rows[i][j].ToString()
== “someValue”;
{
goto foundcell;

}
}
foundcell:


// Statement to executed after
loop.



This way, I could break from both
(if required even more than 2 loops) the loops easily without maintaining any
flag with the help of a goto statement.



Remember the goto statement
should only be used when we have nested loops. If you have only one loop than
its best to use the break keyword to stop, break the loop.

No comments:

Post a Comment