-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
68 lines (59 loc) · 2.17 KB
/
Program.cs
File metadata and controls
68 lines (59 loc) · 2.17 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
public class Fibonacci
{
public static List<int> list;
static void Main(string[] args)
{
//calling the method that validates the input and proceeds further if the input is valid.
FibCounter();
//printing the list of the fibonacci sequence to the console and the last element as well as a goodbye message.
foreach (int i in list)
{
Console.WriteLine(i);
}
Console.WriteLine("The number you are looking for is: " + list[list.Count-1]);
Console.WriteLine("Press any key to close this window! Have a good one! =)");
//added this line so if anyone has the option for console window closure unchecked can still see the results.
Console.ReadLine();
}
public static int FibCounter()
{
Console.WriteLine("Please give me a number..");
string input = Console.ReadLine();
int fibNum = 0;
if (int.TryParse(input, out fibNum))
{
//with a valid input we call the real method that makes the calculations for us with the input.
FibMethod(fibNum);
}
else
{
//if the input is invalid (not a number) recursively call the method until a proper input is given.
FibCounter();
}
return fibNum;
}
public static List<int> FibMethod(int fibNum)
{
//basic fibonacci code, declaring an integer list, checking if the desired number is 0 or less as the original fibonacci sequence is designed for positive integers.
list = new List<int>();
if (fibNum <= 0)
{
list.Add(0);
return list;
}
//if the desired number is 1 or above the list is populated with the sum of the 2 previous elements of the list, creating a proper sequence.
if (fibNum >= 1)
{
list.Add(1);
list.Add(1);
}
for (int i = 2; i < fibNum; i++)
{
list.Add(list[i - 1] + list[i - 2]);
}
return list;
}
}