I want to get a two-dimensional array consisting of Fibonacci numbers, where each subsequent row continues a sequence of Fibonacci numbers from the previous row. Something like that:
Array[4 rows][4 columns];
{{0, 1, 1, 2},
{3, 5, 8, 13},
{21, 34, 55, 89},
{144, 233, 377, 610}}
I need to implement this in C#. But I started with writing in C++. This is my current code in C++ and it works right (as I need):
#include <iostream>
int main()
{
const int rows = 3;
const int cols = 4;
int long A[rows][cols];
A[0][0] = 0;
A[0][1] = 1;
for(size_t i = 0; i < rows; i++)
{
if (i == 0)
for(size_t j = 2; j < cols+1; j++)
A[i][j] = A[i][j - 2] + A[i][j - 1];
else
for(size_t j = 0; j < cols+1; j++)
A[i][j] = A[i][j - 2] + A[i][j - 1];
}
// Output:
// 0 1 1 2
// 3 5 8 13
// 21 34 55 89
for(size_t i = 0; i < rows; i++)
{
for(size_t j = 0; j < cols; j++)
std::cout << A[i][j] << " ";
std::cout << '\n';
}
}
Then I decided to move it to C#:
using System;
class MainClass {
public static void Main (string[] args) {
var rows = 3;
var cols = 4;
var A = new long[rows, cols];
A[0, 0] = 0;
A[0, 1] = 1;
for (var i = 0; i < rows; i++)
{
if (i == 0)
for (var j = 2; j < cols + 1; j++)
A[i, j] = A[i, j - 2] + A[i, j - 1];
else
for (var j = 0; j < cols + 1; j++)
A[i, j] = A[i, j - 2] + A[i, j - 1];
}
for(var i = 0; i < rows; i++)
{
for(var j = 0; j < cols; j++)
Console.WriteLine($"{A[i, j]} ");
Console.WriteLine("\n");
}
}
}
Algorithmically identical code doesn't work in C#.
The error occurs here: for (var j = 2; j < cols + 1; j++)
And the error itself: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
I tried to replace the multi-dimensinal array with jagged, and also remove the "cols/rows + 1" in loops, but it didn't help.
What it could be? Maybe it’s something about the nuances of C#. Because in C++, the code works, even though I didn’t change the algorithm.
If you need any additional information, please let me know and I will clarify. Thank you for your time.