C# program to print nth number in Fibonacci series
Here's a C# program that prints the nth number in the Fibonacci series:
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the value of n: ");
int n = Convert.ToInt32(Console.ReadLine());
long result = Fibonacci(n);
Console.WriteLine($"The {n}th number in the Fibonacci series is: {result}");
}
static long Fibonacci(int n)
{
if (n <= 0)
{
throw new ArgumentException("Invalid input. n should be a positive integer.");
}
if (n == 1 || n == 2)
{
return 1;
}
long previous = 1;
long current = 1;
long next = 0;
for (int i = 3; i <= n; i++)
{
next = previous + current;
previous = current;
current = next;
}
return current;
}
}
In this program, the Fibonacci method takes an integer n as input and calculates the nth number in the Fibonacci series. It initializes three variables: previous, current, and next. It starts with previous and current both set to 1, as the first two numbers in the Fibonacci series are 1. It then iterates from 3 to n and calculates the next number by adding previous and current, and updates the variables accordingly.
The Main method prompts the user to enter the value of n, calls the Fibonacci method with the user input, and displays the result.
Note that the program assumes the user will input a valid positive integer for n. It throws an exception if the input is not a valid positive integer.