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 program to print fibonacci series // using goto statement #include <stdio.h> // Function to print Fibonacci Number // using goto statement void fibUsingGoto( int N)
{ int a = 0, b = 1, sum = 0;
lableFib: // Print to series first N term
if (N != 0) {
// Print series
printf ( " %d" , a);
// Create next term
sum = a + b;
a = b;
b = sum;
// Decrement N
N--;
// Jump to lableFib
goto lableFib;
}
} // Driver Code int main()
{ // Given number N
int N = 10;
// Function Call
fibUsingGoto(N);
return 0;
} |
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 program to print fibonacci // series using recursion #include <stdio.h> // Recursive function to print // Fibonacci series void fib( int a, int b, int sum, int N)
{ // Print first N term of the series
if (N != 0) {
printf ( " %d" , a);
sum = a + b;
a = b;
b = sum;
// Decrement N
N--;
// recursive call function fib
fib(a, b, sum, N);
}
} // Driver Code int main()
{ // Given Number N
int N = 10;
// First term as 0
// Second term as 1 and
// Sum of first and second term
fib(0, 1, 0, N);
return 0;
} |
0 1 1 2 3 5 8 13 21 34
Time Complexity: O(N)
Auxiliary Space: O(N)