Reputation: 93
I know that a similar question may have been asked earlier.
The output of my code is the length of the numbers plus one based on the user input:
i.e. if the user types "5", it is 0, 1, 1, 2, 3, 8.
However, I am trying to print the subsequent nth numbers after the user has provided some number. It should be like this: if the user types "5", then the output should be 5, 8, 13, 21, 34, ...
How should I modify my code to achieve this?
Thank you for your help.
Console.WriteLine("Please enter any nth number of the Fibonacci series.");
string user_num = Console.ReadLine();
int userNumber = int.Parse(user_num);
int[] FibNum = new int[userNumber];
int firstNum = 1;
Console.Write("{0},", firstNum);
int secondNum = 1;
Console.Write("{0},", secondNum);
int sumNum = 0;
while (sumNum <= userNumber)
{
sumNum = (firstNum + secondNum);
Console.Write("{0}, ", sumNum);
firstNum = secondNum;
secondNum = sumNum;
}
Console.ReadLine();
Upvotes: 3
Views: 376
Reputation: 34170
Well to have your firstNum
and sencondNum
after user input value you have to calculate the series from the begining. but however you can simply put a if
before printing to check if the value is greater or equal to the user input then print it. otherwise just ignore it.
Console.WriteLine("Please enter any nth number of the Fibonacci series.");
string user_num = Console.ReadLine();
int userNumber = int.Parse(user_num);
int[] FibNum = new int[userNumber];
int firstNum = 1;
int secondNum = 1;
if(userNumber<=1){
Console.Write("{0},", firstNum);
Console.Write("{0},", secondNum);
}
int sumNum = 0;
while (sumNum <= userNumber)
{
sumNum = (firstNum + secondNum);
if(sumNum>=userNumber) //check to filter less values
Console.Write("{0}, ", sumNum);
firstNum = secondNum;
secondNum = sumNum;
}
Console.ReadLine();
Upvotes: 2