The Fibonacci Sequence is relatively simple - you take the initial number and the second number and add them together starting from 0 and 1, like so:
0 + 1 = 1 1 + 1 = 2 1 + 2 = 3 2 + 3 = 5 3 + 5 = 8and so on.
This can be implemented in a simple way in C#.
First, go to File, New Project, Console Application, Ok.
Now, go in between the starting and closing brackets ( { and } ) of the Main function.
Start off by declaring (and initializing) 3 integers, firstnumber, secondnumber and thirdnumber
int firstnumber = 0, secondnumber = 1, thirdnumber = 0;We have made secondnumber equal to 1, as our algorithim will plus the first number (which we have initialized to 0) and the secondnumber (initialized to 1) and then create our third number by adding them (we've initialized this to 0 for the sake of initializing them all)
For now, we are going to hard code (yes I know, throw bricks at me everyone) the upper bound limit that we want to go to, however you could take the input from the user, store it in another integer and then check the third number against it. To do this, we will use a while loop. We will use 20 as our upper bound limit.
while (thirdnumber < 20)
{
Now, we have to add the first number and the second number and store it as the third number.
thirdnumber = firstnumber + secondnumber;
Then, we must print out our thirdnumber to the console, while enforcing our upper limit, which we will do with an if statement.
if (thirdnumber < 20)
{
Console.WriteLine(thirdnumber);
}
Now, we must set the first and second numbers to their appropriate values, it is VERY important you do this in the right order and to the right variables. If you set the second number first, you won't be able to set the first number to the second number. So you must set the first number to the second number and then set the second number to the third number. Then we must finish off the while loop with a closing bracket. And then just for good measure, we'll add a read line after the while loop so that we don't get any annoying console closing problems.
firstnumber = secondnumber; secondnumber = thirdnumber; } Console.ReadLine();
When you run this, it should show the numbers in the fibbonacci sequence upto your upper bound limit. The final code should look like this (including the bits that are automatically there when creating a new console project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int firstnumber = 0, secondnumber = 1, thirdnumber = 0;
while (thirdnumber < 20)
{
thirdnumber = firstnumber + secondnumber;
if (thirdnumber < 20)
{
Console.WriteLine(thirdnumber);
}
firstnumber = secondnumber;
secondnumber = thirdnumber;
}
Console.ReadLine();
}
}
}
If you liked my tutorial, please tip the scales (+rep) me :)


Sign In
Create Account


Back to top









