Write a program that generates and displays the Fibonacci sequences numbers of n (as input). In Fibonacci, the current third number is the sum of two previous numbers. Apply three solutions using the three loop statements: Sample input/output dialogue: Enter a no. 9 Fibonacci series: 1 1 2 3 5 8 13 21 34
1st Solution using for loop
2nd Solution – using while loop
3rd Solution-‐ using do while loop
using System;
using System.Text;
namespace ConsoleAppFibonacciSequences
{
class Program
{
static void Main(string[] args)
{
int number;
int[] result;
Console.WriteLine("Please enter a positive number for calculate Fibonacci sequences:");
if (int.TryParse(Console.ReadLine(), out number))
{
if (number < 0)
{
Console.WriteLine("The entered number must be positive.");
}
else
{
result = FibonacciSequencesUsingForLoop(number);
Console.WriteLine($"The result of a calculation using a 'for' loop is {ArrayToString(result)}.");
result = FibonacciSequencesUsingWhileLoop(number);
Console.WriteLine($"The result of a calculation using a 'while' loop is {ArrayToString(result)}.");
result = FibonacciSequencesUsingDoWhileLoop(number);
Console.WriteLine($"The result of a calculation using a 'do while' loop is {ArrayToString(result)}.");
}
}
else
{
Console.WriteLine("The entered value cannot be converted to a number.");
}
Console.ReadKey();
}
static int[] FibonacciSequencesUsingForLoop(int n)
{
if (n < 3)
{
return FibonacciSequencesWhenNumLessThanThree(n);
}
else
{
int[] result = new int[n];
result[0] = 1;
result[1] = 1;
for (int i = 2; i < n; i++)
{
result[i] = result[i - 2] + result[i - 1];
}
return result;
}
}
static int[] FibonacciSequencesUsingWhileLoop(int n)
{
if (n < 3)
{
return FibonacciSequencesWhenNumLessThanThree(n);
}
else
{
int[] result = new int[n];
result[0] = 1;
result[1] = 1;
int i = 2;
while (i < n)
{
result[i] = result[i - 2] + result[i - 1];
i++;
}
return result;
}
}
static int[] FibonacciSequencesUsingDoWhileLoop(int n)
{
if (n < 3)
{
return FibonacciSequencesWhenNumLessThanThree(n);
}
else
{
int[] result = new int[n];
result[0] = 1;
result[1] = 1;
int i = 2;
do
{
result[i] = result[i - 2] + result[i - 1];
i++;
}
while (i < n);
return result;
}
}
//Since the first numbers up to three in the Fibonacci sequence do not require calculation, we will move the work with these numbers into a separate method.
private static int[] FibonacciSequencesWhenNumLessThanThree(int n)
{
if (n < 2) // if n=0 or n=1 return array single element n
{
return new int[1] { n };
}
else
{
return new int[2] { 1, 1 };
}
}
// This method converts an int array to a string separated by whitespaces.
private static string ArrayToString(int[] array)
{
StringBuilder sb = new StringBuilder();
foreach (int i in array)
{
sb.Append(i + " ");
}
sb.Remove(sb.Length - 1, 1); // remove the last space
return sb.ToString();
}
}
}
Comments
Leave a comment