开发者

How can I change this loop to not use continue?

I used the continue statement to make this simple program and got the desired output.

for(m=1;m<=3;m++)
{
   for(n=1;n<=2;n++)
   {
      if(m==n)
         continue;
      cout<<m<<" "<<n<开发者_如何学Go;<endl;
   }
}

output:

1  2
2  1
3  1
3  2

Now I want it without using the coninue statement. Is there any way to make it?


Simple as that:

if (m != n) {
  cout<<m<<" "<<n<<endl;
}


My solution is even simpler. It doen't use even if:

for(int m=1;m<=3;m++)
{
  for(int n=1;n<=2;n++)
  {
      m != n && (cout<<m<<" "<<n<<endl);
  }
}

Output:

1 2
2 1
3 1
3 2

Demo : http://www.ideone.com/rMSuK

Note that I'm not going to do this in production code, but for this particular problem, thinking of it as a puzzle, its good to have fun sometime, playing around with how C++ works. :D


Another solution using callbacks:

void print(int m, int n)
{
  cout<<m<<" "<<n<<endl;
}
void noprint(int m, int n)
{ 
}

typedef void (*fn)(int,int);
fn calls[] = {noprint,print};
for(int m=1;m<=3;m++)
{
   for(int n=1;n<=2;n++)
   {
        calls[m!=n](m,n);
   }
}

Online demo : http://www.ideone.com/jLStA


if (m != n)
{
  cout<...
}

....... need more characters...dammit


Like this (I took the freedom to properly indent your code and use std:: where appropriate):

for (m = 1; m <= 3; m++) {
    for (n = 1; n <= 2; n++) {
        if (m != n) {
            std::cout << m << " " << n << "\n";
        }
    }
}


Here is a solution that does not require an if:

for (int m = 1; m <= 3; ++m)
{
    for (int n = 1; n < m; ++n)
    {
        std::cout << m << " " << n << std::endl;
    }
    for (int n = m + 1; n <= 2; ++n)
    {
        std::cout << m << " " << n << std::endl;
    }
}

As you can see, I simply skip the m by not including it in the iteration :)


Simply reverse the condition and put the rest of the code inside it.

As you tagged the question with C#, here's the C# code:

for(int m = 1; m <= 3; m++) {
  for(int n = 1; n <= 2; n++) {
    if (m != n) {
      Console.WriteLine("{0} {1}", m, n);
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜