Given a number ‘n’, the task is to print the Fibonacci series using Command Line Arguments. The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2
with seed values
F0 = 0 and F1 = 1.

Examples:
Input: n = 3
Output: 0, 1, 1
Input: 7
Output: 0, 1, 1, 2, 3, 5, 8
Approach:
- Since the number is entered as Command line Argument, there is no need for a dedicated input line
- Extract the input number from the command line argument
- This extracted number will be in String type.
- Convert this number into integer type and store it in a variable, say num
- Now the function fib having num value will work.
- In this function now take three variables a, b and c and now store two of them value as a=0, b=1;
- Now if the num ==1, then there will be no fibonacci number return a.
- If num >1 then we will swap the all variable values like as
- Now we will just print the all values a, b and c.
Program:
C
#include <stdio.h>
#include <stdlib.h> /* atoi */
void fib( int n)
{
int a = 0, b = 1, c, i;
if (n <= 1)
printf ( "%d " , a);
else {
printf ( "%d %d " , a, b);
for (i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
printf ( "%d " , c);
}
printf ( "\n" );
}
}
int main( int argc, char * argv[])
{
int num, res = 0;
if (argc == 1)
printf ( "No command line arguments found.\n" );
else {
num = atoi (argv[1]);
fib(num);
}
return 0;
}
|
Java
class GFG {
static void fib( int n)
{
int a = 0 , b = 1 , c, i;
if (n <= 1 )
System.out.print(a + " " );
else {
System.out.print(a + " " + b + " " );
for (i = 3 ; i <= n; i++) {
c = a + b;
a = b;
b = c;
System.out.print(c + " " );
}
System.out.println();
}
}
public static void main(String[] args)
{
if (args.length > 0 ) {
int num = Integer.parseInt(args[ 0 ]);
fib(num);
}
else
System.out.println( "No command line "
+ "arguments found." );
}
}
|
Python3
class GFG:
@staticmethod
def fib(n):
a = 0
b = 1
i = 0
if n < = 1 :
print (a, end = " " )
else :
print (a, b, end = " " )
for i in range ( 3 , n + 1 ):
c = a + b
a = b
b = c
print (c, end = " " )
print ()
if __name__ = = "__main__" :
import sys
if len (sys.argv) > 1 :
num = int (sys.argv[ 1 ])
fib(num)
else :
print ( "No command line arguments found\nUse : python3 GFG.py <number>" )
|
Output:



Time Complexity: O(N)
Auxiliary Space: O(1)