Dear, the question of the problem in the subject, here is the code:

class Program { public static void Main(string[] args) { int[] arr = new int[5]; Work ob = new Work(); ob.Go(arr); for(int i =0; i< arr.Length; i++) { Console.WriteLine(arr[i]); } Console.ReadLine(); } } class Work { int temp = 0; public void Go(int[] arr) { for(int i = 0; i < arr.Length; i++) { if(i == 0) { arr[i] = temp; continue; } if((i % 1) == 0) { arr[i] = (temp = temp + 2); } } } } 

The problem is solved correctly, but I do not understand why the correct result. Indeed, in the third step of the iteration, the array should be filled with zero (on the second index). That is, index 2 will NOT pass the parity check and the default constructor will fill it with zero. But this is not happening. Why?

  • Not null , but the current value of the temp variable. Which was increased by 2 in the previous step ( temp = temp + 2 ). - Dmitry D.
  • 3
    Discover the debugger. It is made in order not to guess how the program works, but to see how exactly it works. - Vladimir Martyanov

1 answer 1

Let's start with the tenp variable declared in the Work class and used in the Go method.

Its initial value is 0.

 int temp = 0; 

In the Go method, for each value of the variable i , except for the value 0, the variable temp increased by 2

  if((i % 1) == 0) { arr[i] = (temp = temp + 2); 

and successively takes the values ​​2, 4, 6 and so on. These values ​​are assigned to the elements of the array.

  arr[i] = (temp = temp + 2); 

By the way, one could write this expression without using parentheses.

  arr[i] = temp = temp + 2; 

since assignment statements are grouped from right to left.

Keep in mind that any positive integer when dividing by 1 gives a remainder equal to 0. Therefore, the expression in this if clause

  if((i % 1) == 0) { 

always true. There is no parity check in the loop. :) The parity check condition looks like

  if((i % 2) == 0) { ^^ 

The Go method could be written much easier, and not so elaborate. for example

 public void Go(int[] arr) { for ( int i = 0; i < arr.Length; i++ ) arr[i] = 2 * i; } 

Or if you use the temp variable

 public void Go(int[] arr) { for ( int i = 0; i < arr.Length; i++ ) { arr[i] = temp; temp += 2; } } 

And there is no need to make it a non-static class method. It would be better to write

 public static void Go(int[] arr) { /*...*/ } ^^^^^^ 

Of course, in this case, the temp variable, if it is used in the method, must also be declared as a static variable. However, in the context that you showed the use of code, there is no need for this variable at all.