Question : C# Ref Parameter Question? How to call a method that has Ref parameter recursively?

Hello,

I am trying to compute fibonacci number recursively and calling computeFibonacciRecursive(ref fib); from main.
However, I am getting error from
return computeFibonacciRecursive(ref n - 1) + computeFibonacciRecursive(ref n - 2);
The error is:

A ref or out argument must be an assignable variable

How to fix this error? Please help.



class Program{
static void Main(string[] args){
            int fib = 20;
computeFibonacci(ref fib);Console.WriteLine(fib);
fib = 20;
computeFibonacciRecursive(ref fib);Console.WriteLine(fib);
        }

 private static int computeFibonacciRecursive(ref int n)
        {
            if (n <= 1)
            {
                return n;
            }
            else
            {
                return computeFibonacciRecursive(ref n - 1) + computeFibonacciRecursive(ref n - 2);  //<------
            }
        }

private static int computeFibonacci(ref int n)
        {
            int a = 1, b = 1;
            for (int i = 3; i <= n; i++)
            {
                int c = a + b;
                a = b;
                b = c;
                Console.WriteLine("b is= " + b);
            }
            return b;
        }

}

Answer : C# Ref Parameter Question? How to call a method that has Ref parameter recursively?

you don't need the 'ref' because you already returning a value...
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
class Program
    {
        static void Main(string[] args)
        {
            int fib = 20;
            fib = computeFibonacci(fib); Console.WriteLine(fib);
            fib = 20;
            fib = computeFibonacciRecursive(fib); Console.WriteLine(fib);
        }

        private static int computeFibonacciRecursive(int n)
        {
            if (n <= 1)
            {
                return n;
            }
            else
            {
                return computeFibonacciRecursive(n - 1) + computeFibonacciRecursive(n - 2);  //<------
            }
        }

        private static int computeFibonacci(int n)
        {
            int a = 1, b = 1;
            for (int i = 3; i <= n; i++)
            {
                int c = a + b;
                a = b;
                b = c;
                Console.WriteLine("b is= " + b);
            }
            return b;
        }

    }
Random Solutions  
 
programming4us programming4us