Home > Software engineering >  For-loops, array and operator
For-loops, array and operator

Time:01-07

Beginner asking a question.

I am testing the increment operator within for-loop and the outcome is different than I expect it to be and I have no clue why. The code is not for a specific program.

        int[] numbers = new int[10];

        for (int i = 0; i < 10; i  )
        {
            numbers[i] = i  ;
        }

        for (int a = 0; a < 10; a  )
        {
            Console.WriteLine("value is {0} at position {1}", numbers[a], a);
        }

Output is:

value is 0 at position 0
value is 0 at position 1
value is 2 at position 2
value is 0 at position 3
value is 4 at position 4
value is 0 at position 5
value is 6 at position 6
value is 0 at position 7
value is 8 at position 8
value is 0 at position 9

If i run the first for-loop without the increment (numbers[i] = i;), the values are consecutive and in order (0, 1, 2, 3 etc.). Why the increment causes every other value to be zero? I thought it would be something like 0, 2, 4, 6, 8, 10 etc.

If I run numbers[i] = i 1; outcome is something I would expect:

value is 1 at position 0
value is 2 at position 1
value is 3 at position 2
value is 4 at position 3
value is 5 at position 4
value is 6 at position 5
value is 7 at position 6
value is 8 at position 7
value is 9 at position 8
value is 10 at position 9

CodePudding user response:

The code you write is

for (int i = 0; i < 10; i  )
{
    numbers[i] = i  ;
}

that is equal to

for (int i = 0; i < 10; i  )
{
    numbers1[i] = i;
    i = i   1;
}

First time i is start from 0

// I change the i to real value for easy understanding
for (int i = 0; i < 10; i  )
{
    numbers1[0] = 0;
    i = 0   1;
    //so here i is 1
}

Second time i is 2, because after first time loop the i is 1 then the for (int i = 0; i < 10; i ) will increase i from 1 to 2, so the second time loop will be

for (int i = 0; i < 10; i  )
{
    numbers1[2] = 2;
    i = 2   1;
    //so here i is 3
}

So now you know the numbers[0] is 0 and numbers[2] is 2 but about the numbers[1] you don't set the value for it so it will be the default value which the default value of int is 0.

CodePudding user response:

Thank you Michael! I verified that out also by myself when messing around with the code. First I tried adding one more i ;

            for (int i = 0; i < 50; i  )
            {
                numbers[i] = i  ;
                i  ;
            }

It gave me value on every third row.

and then third i :

            for (int i = 0; i < 50; i  )
            {
                numbers[i] = i  ;
                i  ;
                i  ;
            }

Now value every fourth line.

Solved.

  • Related