Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# – repeat for loop without using goto

Recently, when developing a calculator program, I found myself using goto multiple times to restart a for loop.
Example:

StartLoop:

for (int i = 0; i < length; i++)
{
    if (items[i] == condition)
    {
        //Do something
        goto StartLoop:
    }
}

I know that goto should be avoided but what other way would I have to restart the loop?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just set the value of i:

int length = 9;
for (int i = 0; i < length; i++)
{
    Console.WriteLine(i);
    if (i == 7)
    {
        i = -1;
    }
}
0
1
2
3
4
5
6
7
0
1
2
3
4
5
6
7
0
1
2
3
4
5
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading