Search code examples
c#increment

What is causing the difference in these two loops?


static void Main(string[] args)
{
    int num = Convert.ToInt32(Console.ReadLine());
    int res = 1;
    while (res <= num)
    {
        res++;
        if ((res % 2) == 0)
        {
            Console.WriteLine(res);
        }
    }
}

I am using the int 8, 10, and 5 as my control groups, these SHOULD just output the even numbers starting at 1 and going till the input number(8,10,5).

static void Main(string[] args)
{
    int num = Convert.ToInt32(Console.ReadLine());
    for (int res = 1; res <= num; res++)
    {
        if ((res % 2) == 0)
        {
            Console.WriteLine(res);
        }
    }
}

Can someone help me understand?


Solution

  • The difference is that in the second loop, you are incrementing res at the very end of each iteration (that's how a for loop works), whereas in the first loop, you increment res before you check for "even".

    This means that when res is 5 and a new iteration of the while loop starts, res gets incremented to 6 first, and 6 passes the check, causing 6 to be printed. In the for loop however, res is incremented after 5 not passing the even check. The iteration then stops since 6 is now greater than 5.

    To make the while loop the same as the for loop, move res++ to the end:

    while (res <= num)
    {
        if ((res % 2) == 0)
        {
            Console.WriteLine(res);
        }
        res++;
    }