question

FranKDuc-4126 avatar image
0 Votes"
FranKDuc-4126 asked AgaveJoe answered

Cant understand result from array

Hello,

I am trying to understand the result from this code, Can anyone explain me in plain math what it is doing.

 int[] array = new int[7];
 int i, k;
    
 array[0] = 1;
         
      for ( k = 1; k < 7; k++)
       {
         array[k] = array[k-1] +2; 
             
    
       }
          
          for(i = 0; i < 7; i++)
        {
          Console.WriteLine(array[i]);
                 
        }

The result is 1, 3 , 5, 7, 9, 11, 13.

If array[0] = 1, i assume first number in result is 1 than the loop begins at 1 so 1-1 +2 = 2? But at loop k= 2, 2 -1 +2 = 3? Than i will get a 4. But thats not the result. Its 5.

Thank you

dotnet-csharp
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

A better approach is learning how to use the Visual Studio debugger. The debugger has a single step feature which allows you to execute one line at a time and view all the local variables. You'll be able to see the variables before executing a line of code and the variables after executing a line of code.

The first iteration is array[1] = 1 + 2. array[k-1] is array[1-1] or array[0]. array[0] contains a 1.




1 Vote 1 ·

II use an online compiler. I plan to install it.
ok i get it now. i mixed the k betwen is position and the result calculation.

0 Votes 0 ·

1 Answer

AgaveJoe avatar image
0 Votes"
AgaveJoe answered

You can always print the variable values to get an idea of what's happening in the code.

 int[] array = new int[7];
 int i, k;
    
 array[0] = 1;
    
 for (k = 1; k < 7; k++)
 {
     Console.WriteLine($"k = {k}");
     Console.WriteLine($"array[k] = {array[k]}");
     Console.WriteLine($"k - 1 = {k - 1}");
     Console.WriteLine($"array[k - 1] = {array[k - 1]}");
     Console.WriteLine($"array[k - 1] + 2 = {array[k - 1] + 2}");
     array[k] = array[k - 1] + 2;
 }
    
 for (i = 0; i < 7; i++)
 {
     Console.WriteLine(array[i]);
 }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.