C Sharp Program for fibonacci Series
using System;
namespace fibonacci
{
class Program
{
static void Main(string[] args)
{
int n1;
int n2;
int n3;
Console.WriteLine("Enter the number upto which you want to calculate fibonacci series");
int lastnum = Convert.ToInt32(Console.ReadLine());
n1=0;
n2=1;
n3=0;
Console.WriteLine(n1);
Console.WriteLine(n2);
for (int i = 0; i < lastnum; i++)
{
n3 = n1 + n2;
Console.WriteLine(n3);
n1 = n2;
n2 = n3;
}
Console.ReadKey();
}
}
}
namespace fibonacci
{
class Program
{
static void Main(string[] args)
{
int n1;
int n2;
int n3;
Console.WriteLine("Enter the number upto which you want to calculate fibonacci series");
int lastnum = Convert.ToInt32(Console.ReadLine());
n1=0;
n2=1;
n3=0;
Console.WriteLine(n1);
Console.WriteLine(n2);
for (int i = 0; i < lastnum; i++)
{
n3 = n1 + n2;
Console.WriteLine(n3);
n1 = n2;
n2 = n3;
}
Console.ReadKey();
}
}
}
Output
Enter the number upto which you want to calculate fibonacci series
5
0
1
1
2
3
5
8
- Using System- Namespace containing all the basic classes and methods.
- Class Program- Program is the name of the class.
- static void Main(Stings [] args)- Main method from where the execution of the program starts.
- Next we declared four integer variables named n1,n2,n3,lastnum, and opted user to enter the number upto which the user want to calculate fibonacci series. We used object of Scanner class to accept that number and stored in variable 'lastnum'.
- Next we initialized n1 to 0, n2 to 1 and n3 to 0 respectively and printed those numbers on the console .
- Next , using the for loop ,we initialized counter 'i' to 0 and the specified the condition that the for loop will continue to execute until the 'i' is less than the number entered by user stored in variable 'lastnum'.
- In the loop, we added values in variable n1 and 'n2' and stored them in 'n3'. And then, we assigned value in 'n2 'to 'n1' and 'n3' to 'n2' respectively. The for loop continues to execute until the given condition becomes false. And the fibonacci series is printed on the Console/screen.
C Sharp Program for fibonacci Series
Reviewed by LanguageExpert
on
August 09, 2017
Rating:
No comments