❔ Trying to make a bit of code to display all values of fibonacci until the nth term input
Have got this so far (i am a beginner)
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(Fibonacci(n));
public static int Fibonacci(int x) {
int first = 1;
int second = 2;
int next = 3;
for (int i = 3; i <= x; i++){ next = first + second; Console.WriteLine("{0}", next); first = second; second = next; }
}
for (int i = 3; i <= x; i++){ next = first + second; Console.WriteLine("{0}", next); first = second; second = next; }
}
28 Replies
What part are you having trouble with?
it says not all code paths return a value and im just confused
So, your function is defined to return an int:
Do you ever return an int?
i want to return the series of fibonacci numbers so if i put 3 in i want it to return 1,1,2
If you just want to print and not return a value, change the return type from int to void
There is a difference between "returning" and "printing"
would you mind explaining that for me
sorry i am knew to coding
If you don't know what a return value from a method is I would suggest going through a basic C# tutorial, such as $helloworld
er
$helloworld
Written interactive course https://learn.microsoft.com/en-us/users/dotnet/collections/yz26f8y64n7k07
Videos https://dotnet.microsoft.com/learn/videos
okay ill check that out thank you very much i might be back later to ask smth else 😆 🙂
Sure, good luck
once i converted it to void
it now gives me the error cannot convert bool to void\
but i havent used a bool anywhere lmao
Show the current code
$code
To post C# code type the following:
```cs
// code here
```
Get an example by typing
$codegif
in chat
If your code is too long, post it to: https://paste.mod.gg/$codegif
Remove the Console.WriteLine there
You aren't returning anything so there is nothing to pass to Console.WriteLine
should i just put fibonacci(n)
Yeah
oki dokiee
Since you are printing the values inside your Fibonacci method
it also wont return first and second didgets but i cant figure out where to put that in my code
like i know what to write idk where to put it
You could just special case those:
Or, rewrite your code to not start the loop at 3 and have it also print the initial values.
oh okay ill give it ago thank you very much 🙂
u have saved me
can i ask one question i got this part from a friend but i dont fully understand how it works
That's called a format string. The
{0}
part is placeholder where the thing after the comma will be inserted. If you had two things to insert it might look like this:
However, you can do the same thing with something called string interpolation, which is usually the preferred way these days:
i think ive seen that before but writen in a different way
yeah thats it
thank you very mcuh
u have been super helpful
Happy to help
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.