# Series fibonacci in a matrix n * n, C #

2

How can I introduce the fibonacci series in an "N" matrix by "N" example:

``````1 1 2 3
5 . . .
``````

My result is not as expected, it does not show the series in the matrix.

This is my code:

``````int i, j, n,aux;
int a = 0;
int b = 1;
int[,] matriz1 = new int[n, n];
for (i = 0; i < n; i++)
{
for (j = 0;  j < n; j++)
{
if (i == 0)
{
matriz1[i, j] = j + 1;
}
else
{
for (int x = 0; x < n; x++)
{
aux = a;
a = b;
b = aux + a;
Console.Write(" "+a);
}
}
}

}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(matriz1[i, j] + "\t");
}
Console.WriteLine(a);
}
``````

The result that appears on the screen is: 1 1 2 3 5 8 ........ 0 0 0 0 0 0

asked by Rom 27.07.2017 в 15:48
source

1

First of all you have to take into account the fibonacci algorithm, which can be solved in a recursive

source
1

The fibonacci sequence is based on adding the two previous numbers to which we are going to calculate. There are many ways to solve it, but I will rely on your code to give you a possible solution. Basically, it is to store the two previous numbers to calculate the next, and once calculated, the previous one is stored as the "second previous" and the one just calculated as previous:

``````int i, j, n;
int ant1 = 1; //para el numero anterior
int ant2 = 0; //para el numero anterior al anterior
int[,] matriz1 = new int[n, n];
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (i == j & i == 0) //Cuando es el primer elemento de la serie, le ponemos 0
{
matriz1[i, j] = 0;
}
else
{
matriz1[i, j] = ant1 + ant2; //en los demas casos,sumamos los dos numeros anteriores
}
ant2 = ant1;          //pasamos el numero anterior al segundo anterior
ant1 = matriz1[i, j]; // y almacenamos el numero recién calculado como el anterior
}
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(matriz1[i, j] + "\t"); //mostramos los números de la fila
}
Console.WriteLine(); //retorno de carro para mostrar la fila siguiente
}