PRINT Fibonacci
series
0, 1, 1, 2,
3, 5, 8, 13, 21
The Fibonacci series 0,
1, 1, 2, 3, 5, 8, 13, 21 begins with the numbers 0 and 1 and has the property
that each succeeding number is the sum of the two preceding numbers.
Using C#, write a
nonrecursive function fibonacci(n) that calculates the nth Fibonacci number.
Then write a program to display a table of two columns consisting of the first
15 numbers and their associated Fibonacci numbers.
You can do
it by many ways
1st
by array
int[] arr1 = { 0 };
int[] arr2 = { 1 };
int val1 = 0;
int val2=1;
for (int i = 0; i <= 7; i++)
{
if (i < 1)
Console.Write(arr1[i] + " " + arr2[i]+" ");
else
{
int sum = arr1[0] + arr2[0];
Console.Write(sum +" ");
arr1[0] = arr2[0];
arr2[0] = sum;
}
}
2nd by variable
static void Main(string[] args)
{
int[]
arr1 = { 0 };
int[]
arr2 = { 1 };
int
val1 = 0;
int
val2=1;
int
sum = 0;
while
(sum <= 21)
{
Console.Write(val1 + " ");
sum= val1 + val2;
val1 = val2;
val2 = sum;
}
Console.ReadLine();
}
If you want
n number of Fibonacci series
In Above Example you can pass dynamic value
while
(sum <= “you can pass the number here”)
No comments:
Post a Comment