Error in using if

1

My intention with this code is to show how many numbers are odd and how many are even. (eg: Odd: 3 Par: 2).

for (int i = 0; i < 6;i++)
{
     int SePar, SeImpar, cont;

     SePar = 0;
     SeImpar = 0;
     cont = 0;                               

     if (atividade[i] % 2 == 0)
     {
         SePar = SePar + 1;
     }

     if (atividade[i] % 2 != 0)
     {
         SeImpar = SeImpar + 1;                  
     }

     cont = cont + 1;

     if (cont == 6)
     {
         Console.WriteLine("par: " + SePar + "Impar: " + SeImpar);
     }
}

    
asked by anonymous 22.08.2017 / 03:50

3 answers

3

First:

The declaration of the variables that count the odd and even numbers must be done outside the for loop, otherwise they will always be zeroed with each loop executed.

Second:

Its cont variable can be replaced by i because it is the one that makes the loop continue through i++ .

Third:

In this case, the test to check if your index (changed from cont to i ) is == 6 will never be reached, because the loop starts at 0 and goes up to 6, that is, in fact it goes to 5.

Code as it should be :

public static void par(int[] atividade)
{
    int SePar, SeImpar;

    SePar = 0;
    SeImpar = 0;

    for (int i = 1; i < 6;i++)
    {                                                
        if (atividade[i] % 2 == 0)
        {
            SePar = SePar + 1;
        }

        if (atividade[i] % 2 != 0)
        {
            SeImpar = SeImpar + 1;
        }

        if (i == 5)
        {
            Console.WriteLine("par: " + SePar + " Impar: " + SeImpar);
        }
    }
}
    
22.08.2017 / 04:00
2

It has a logic error ai, the count will always be 0, since it is being initialized inside the for loop

The correct one is:

int SePar, SeImpar, cont;

SePar = 0;
SeImpar = 0;
cont = 0;  

for (int i = 0; i < 6;i++)
{



     if (atividade[i] % 2 == 0)
     {
         SePar = SePar + 1;
     }

     if (atividade[i] % 2 != 0)
     {
         SeImpar = SeImpar + 1;                  
     }

     cont = cont + 1;


}
 if (cont == 5)
 {
    Console.WriteLine("par: " + SePar + "Impar: " + SeImpar);
 }
    
22.08.2017 / 04:00
0

Just to demonstrate the same code, but refactored.

var atividade = new [] {1,2,3,4,5,6};
var totalImpar = 0;
for (var i = 0; i < atividade.Length; i++)
{
    totalImpar += atividade[i] % 2 == 0
        ? 0
        : 1;
}
Console.WriteLine($"Pares: {atividade.Length - totalImpar}  Impares: {totalImpar}");

See working on NetFiddle .

    
22.08.2017 / 09:35