The Program in C# Program to Display First n terms of Fibonacci Series is given below:
using System;
namespace FibonacciSeries
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family,enter the number of terms: ");
int n = int.Parse(Console.ReadLine());
int a = 0, b = 1, c;
Console.Write(a + " " + b + " ");
for (int i = 2; i < n; i++)
{
c = a + b;
Console.Write(c + " ");
a = b;
b = c;
}
Console.ReadLine();
}
}
}
Output:
Hello Codeauri Family,enter the number of terms:
3
0 1 1
Pro-Tips💡
Here are the step by step execution of above program:
- The program begins by importing the “System” namespace, which provides access to various types and methods that are used in the program.
- The code defines a namespace named “FibonacciSeries”. The namespace is a way to organize and group related classes.
- Within the namespace, the class named “Program” is defined. The Main method is defined inside this class and serves as the entry point for the program.
- The Main method first asks the user to input the number of terms “n” that they want to display in the Fibonacci series. This input is read from the console and stored in the integer variable named “n”.
- The Main method then declares three integer variables “a”, “b”, and “c”. “a” and “b” are initialized to 0 and 1, respectively, as the first two terms of the Fibonacci series are 0 and 1.
- The Main method then prints the first two terms of the series, “a” and “b”, to the console.
- The Main method uses a for loop to iterate from 2 to “n – 1”, as the first two terms have already been printed.
- Within the for loop, the value of “c” is calculated as the sum of “a” and “b”. This value represents the next term in the Fibonacci series.
- The Main method then prints the value of “c” to the console.
- The Main method then updates the values of “a” and “b”, so that they are ready for the next iteration of the loop. “a” becomes “b”, and “b” becomes “c”.
- The Main method finally waits for the user to press the enter key, which allows the console window to remain open until the user closes it.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.