I'm trying to make a program that will take an input for a limiting value, then output the fibonacci sequence until the limit is reached. This is what I've got so far:
int n1 = 0, n2 = 1, n3 = 0, i, ToInfinity = 3, limit, terms = 0;
List<int> fibonaccisequence = new List<int>();
Console.Write("Enter the limiting value: ");
limit = Convert.ToInt32(Console.ReadLine());
fibonaccisequence.Add(n1);
fibonaccisequence.Add(n2);
do
{
for (i = 2; i < ToInfinity; i )
{
n3 = n1 n2;
fibonaccisequence.Add(n3);
n1 = n2;
n2 = n3;
ToInfinity = 1;
terms = 1;
}
}
while (n3 <= limit);
Console.WriteLine(fibonaccisequence);
Console.WriteLine("There are {0} terms up to {1].", terms, limit);
But whenever I execute the code, it says "Array dimensions exceeded supported range", which obviously means that it is going on forever, instead of stopping at the limit. I may not be seeing something obvious, but can anyone suggest why this isn't working.
CodePudding user response:
Let's first see what is happening in your code
for (i = 2; i < ToInfinity; i )
{
...
}
You're running the loop as long as value of i
is less than ToInfinity
.
And you're increasing the value of i
and ToInfinity
in every iteration by 1
.
So basically this loop is never stopping.
Let's see how we can reach to your objective
You're trying to find Fibonacci sequence until the limit is reached.
So I would suggest you to try it using while
loop first (assuming you're new to this).
Let's see how you can do it using while loop.
while(n1 n2 <= limit) // as n3 = will be n1 n2
{
n3 = n1 n2;
fibonaccisequence.Add(n3);
n1 = n2;
n2 = n3;
terms = 1;
}
Note: You need to initialize the variable "terms
" with 2
. Cause you've already taken 2
sequences (n1
, n2
).
Now I would suggest you to learn little bit more about do while
loop first. Then try to use that for implementing above logic.
Few resources to learn more about loop
CodePudding user response:
I guess both ToInfinity and i variables are increasing with same amount so basically for loop will never stop.