C#, simple for loop
-
Wednesday, September 26, 2007 3:49 AM
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 2Is there any way that the Statement 2 can loop after the Statement 1 completes the loop like:
Statement 1
Statement 1Statement 2
Statement 2
Thanks
All Replies
-
Wednesday, September 26, 2007 7:20 AM
No. Use two loops, or buffer up the output of statement 2 and write it after the loop completes.
-
Wednesday, September 26, 2007 9:50 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){
true;intI = 0;
blnLoop =
}
if (blnLoop && intI == 4){
break;}
}
You can achieve it in a single loop
-
Wednesday, February 15, 2012 7:25 PM
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

