none
C#, simple for loop

    Question

  • Hi!

     

    Just out of curiosity, I'd like to know if there any way that in a single 'for loop', one statement can loop after the other completes the loop. Not that I know of.

     

    Code Snippet:

     

    using System;

    class MainClass
    {
        static void Main()
        {       
            for(int i=0; i<5; i++)
            {
                Console.WriteLine("Statement 1");
                Console.WriteLine("Statement 2");     
            }
        }
    }

     

    The output for the code snippet would be:

    Statement 1
    Statement 2
    Statement 1
    Statement 2

     

    Is there any way that the Statement 2 can loop after the Statement 1 completes the loop like:

    Statement 1
    Statement 1

    Statement 2

    Statement 2

     

    Thanks

    Wednesday, September 26, 2007 3:49 AM

Answers

  • No. Use two loops, or buffer up the output of statement 2 and write it after the loop completes.

    Wednesday, September 26, 2007 7:20 AM
  • Hi,

      you can check this out:

     

    bool blnLoop = false;

    for (int intI = 0; intI < 5; intI++)

    {

    if (!blnLoop)

    {

    Console.WriteLine("Statement 1");

    }

    else

    {

    Console.WriteLine("Statement 2");

    }

    if (!blnLoop && intI == 4)

    {

    intI = 0;

    blnLoop = true;

    }

    if (blnLoop && intI == 4)

    {

    break;

    }

    }

     

    You can achieve it in a single loop

    Wednesday, September 26, 2007 9:50 AM

All replies

  • No. Use two loops, or buffer up the output of statement 2 and write it after the loop completes.

    Wednesday, September 26, 2007 7:20 AM
  • Hi,

      you can check this out:

     

    bool blnLoop = false;

    for (int intI = 0; intI < 5; intI++)

    {

    if (!blnLoop)

    {

    Console.WriteLine("Statement 1");

    }

    else

    {

    Console.WriteLine("Statement 2");

    }

    if (!blnLoop && intI == 4)

    {

    intI = 0;

    blnLoop = true;

    }

    if (blnLoop && intI == 4)

    {

    break;

    }

    }

     

    You can achieve it in a single loop

    Wednesday, September 26, 2007 9:50 AM
  • int x, y;
    
    for(x=1; x<=2; x++){       
         for(y=1; y<=2; y++){                 
              Console.WriteLine("Statement {0}", x);       
         }
    }

    Outputs:

    Statement 1

    Statement 1

    Statement 2

    Statement 2

    Wednesday, February 15, 2012 7:25 PM
  • try statement like this

            for(int i=0; i<5; i++)
            {
                Console.WriteLine("Statement "+i);
                Console.WriteLine("Statement "+i);     
            }

    More on loop........ C# For Loop

    Lev


    • Edited by leveena_lap Thursday, January 23, 2014 6:50 AM
    Thursday, January 23, 2014 6:50 AM