Given a number N, the task is to print Fibonacci Series till Nth number without using any loop.
Examples:
Input: N = 5
Output: 0 1 1 2 3
Input: N = 10
Output: 0 1 1 2 3 5 8 13 21 34
Method 1: Using goto statement: The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. It can be used to jump from anywhere to anywhere within a function. Below are the steps:
- Declare 3 int variable a, b and sum. a is the first value, b is the second value and the sum is the addition of a + b.
- Use label to create the loop with goto statement.
- If-else is checked if the condition is true then it continues the program else it terminates it.
- Print sum because the value of sum is 0 now and then use the concept of swapping as:
sum = a + b
a = b
b = sum
-
Below is the implementation of above approach:
C
#include <stdio.h>
void fibUsingGoto( int N)
{
int a = 0, b = 1, sum = 0;
lableFib:
if (N != 0) {
printf ( " %d" , a);
sum = a + b;
a = b;
b = sum;
N--;
goto lableFib;
}
}
int main()
{
int N = 10;
fibUsingGoto(N);
return 0;
}
|
Output:
0 1 1 2 3 5 8 13 21 34
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 2 – Using Recursion:
- Declare three variable a, b, sum as 0, 1, and 0 respectively.
- Call recursively fib() function with first term, second term and the current sum of the Fibonacci series.
- After main function call fib() function, the fib() function call him self until the N numbers of Fibonacci Series are calculated.
- Update the value of a, b, and sum in each recursive call as shown below:
sum = a + b
a = b
b = sum
-
Below is the implementation of the above approach:
C
#include <stdio.h>
void fib( int a, int b, int sum, int N)
{
if (N != 0) {
printf ( " %d" , a);
sum = a + b;
a = b;
b = sum;
N--;
fib(a, b, sum, N);
}
}
int main()
{
int N = 10;
fib(0, 1, 0, N);
return 0;
}
|
Output:
0 1 1 2 3 5 8 13 21 34
Time Complexity: O(N)
Auxiliary Space: O(N)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!