From f57c1fe3fd6781d00abc59236283c88073320dac Mon Sep 17 00:00:00 2001 From: danildenha <135840453+danildenha@users.noreply.github.com> Date: Wed, 6 Dec 2023 16:42:04 -0600 Subject: [PATCH] Fix for negative number case Fibonacci.cpp If the input is less than 0, handle this --- algorithms/cpp/Fibonacci.cpp | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/algorithms/cpp/Fibonacci.cpp b/algorithms/cpp/Fibonacci.cpp index 2da2e50..f77e15c 100644 --- a/algorithms/cpp/Fibonacci.cpp +++ b/algorithms/cpp/Fibonacci.cpp @@ -1,22 +1,26 @@ #include -using namespace std; int main() { int n; - cout << "Enter the number of terms" << endl; - cin >> n; + std::cout << "Enter the number of terms" << std::endl; + std::cin >> n; int a = 0, b = 1, sum = 0; - - cout << a << " " << b << " "; - - for (int i = 0; i < n - 2; i++) + if (n > 0) + { + std::cout << a << " " << b << " "; + for (int i = 0; i < n - 2; i++) + { + sum = a + b; + a = b; + b = sum; + std::cout << sum << " "; + } + std::cout << endl; + } + else { - sum = a + b; - a = b; - b = sum; - cout << sum << " "; + std::cout << "Number should be greater than 0" << std::endl; } - cout << endl; return 0; } @@ -25,4 +29,4 @@ int main() Enter the number of terms INPUT- 4 OUTPUT- 0 1 1 2 -*/ \ No newline at end of file +*/