Search code examples
c#iterationsequences

How to iterate numbers to a limit by addition


Here is the code I have right now:

for(int i=0; i< 35; ++i)
{
    int a = 1;
    a+=1;
    Console.WriteLine(a);
}

The output is:

2
2
2
...

and so on, until the loop terminates.

What I want to do is add the previous two numbers to make the nest number then so on all the way to 34.


Solution

  • This is how you can achieve what you want:

    //Initializing the elements
    int a = 0;
    int b = 1;
    int c = 1;
    
    Console.WriteLine(a); //Typing the 0'th element
    Console.WriteLine(b); //Typing the first element
    
    for(;c <= 34; c = a + b) {
        Console.WriteLine(c); //Typing the actual element
        a = b;
        b = c;
    }