Pergunta

shortly, how can i stop the following code after printing 20 numbers?

Thanks

    static void Main(string[] args)
    {
        int num1 = 4;
        int num2 = 7;

        for (int i = 200; i < 2000; i++)
        {
            if ((i % num1 == 0) && (i % num2 ==0))
            {
                Console.WriteLine(i);
            }
        }
        Console.Read();
    }

I tried to write "break" after the "Console.WriteLine(i);" but then it printed only 1 number and i need 20.

Thanks

Foi útil?

Solução

You need to keep track of how many numbers you've printed out and then break out of the loop once you have enough:

int counter = 0;
for (int i = 200; i < 2000; i++)
{
     if ((i % num1 == 0) && (i % num2 ==0))
     {
         Console.WriteLine(i);
         counter++;
         if(counter == 20)
             break;
     }
}

Or you can use a for loop with two conditions:

for (int i = 200, j= 0; i < 2000 && j < 20; i++)
{
    if ((i % num1 == 0) && (i % num2 ==0))
    {
        Console.WriteLine(i);
        j++;
    }

}

Outras dicas

for (int i = 200,loopCounter=0; i < 2000; i++)
    {
        if ((i % num1 == 0) && (i % num2 ==0))
        {
                 if(loopCounter == 20)
                   break;

            Console.WriteLine(i);
                    loopCounter++;
        }
    }

Whenever the program control reaches break it will exit the loop in which it it running.
To ensure that the loop breaks the right point you need to check for the condition where you want to break from the loop.

static void Main(string[] args)
{
    int num1 = 4;
    int num2 = 7;
    int counter=0
    for (int i = 200; i < 2000; i++)
    {
        if(counter>20)
           break;
        if ((i % num1 == 0) && (i % num2 ==0))
        {
            counter++;
            Console.WriteLine(i);
        }
    }
    Console.Read();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top