C#: Cannot reassign variable within For loop

76 Views Asked by At

I am writing a program to to calculate a specific value in Fibonacci sequence. The recursive method works perfectly, but when I try to use for loop, it doesn't work so well:

class Program
{

    static int loopF(int n)
    {
        int result=0;
        if (n == 1)
        {
            result = n;
        }
        else if (n == 2)
        {
            result = n;
        }
        else if (n>2)
        {
            int S1 = 1; int S2 = 2; 
            for (int i = 3; i>n; i++) {
                result = S1 + S2;
                S1 = S2;
                S2 = result;
                                       }
        }
        else{
            Console.WriteLine("Input Error");
        }
        return (result);
    }

    static void Main()
    {
        Console.WriteLine(loopF(10)); //it gives me 0; wrong
        Console.WriteLine(loopF(1)); //it gives me 1; correct.
    }
}

Does anybody know where I go wrong? Thanks in advance.

2

There are 2 best solutions below

1
On BEST ANSWER

Your loop is not executing

 for (int i = 3; i>n; i++)

Variable i starts at 3 - in your test case n = 10. (10 < 3) = false so the loop does not execute.

try using less than instead

 for (int i = 3; i < n; i++)
0
On

Your loop's exit condition is wrong. It should be

for (int i = 3; i < n ; i++) { ...