The odd-fibonacci series using Java

Hello there,
let us suppose that for some reason, you would want to print out  all the odd terms in a Fibonacci series, well fear no much as this program will be a solution to that, this program will let you print all the odd terms in a Fibonacci series. In return what the program demands is the range up to which, you would want them to be printed.
Now since the program is Short and Simple I have abstained myself from using any methods, but if, you as a coder decide to implement functions to it, feel free to do so, without any hesitation.

Program to print odd-fibonacci series in Java

import java.util.*;
class oddfibo
{
    public static void main()
    {
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter the range: ");
        int length=sc.nextInt();
        int first=0,second=1,iter=0,next;
        if(length<=0)
        System.out.println("The Input provided should always be greater than zero");
        if(length==1)
        System.out.println(first);
        else
        {
            while(iter<length)
            {
                next=first+second;
                first=second;
                second=next;
                if(next%2!=0)
                {
                    System.out.println(next);
                    iter++;
                }
            }
        }
    }
}

 

Output:

Enter the range: 5
1
3
5
13
21


Enter the range: 6
1
3
5
13
21
55


Enter the range: 7
1
3
5
13
21
55
89

Explanation :

The code begins by importing java utilities, which contains the scanner class, which will help us in taking user-defined inputs. After which we create the class and jump straight into the main function. We declare the scanner class and get the range from the user. We then initialize the values of ‘first’ to zero and ‘second’ to one.
Now we set the conditions that is, if the range is less than or equal to 0, we print out that the number should be greater than zero.
Else if number is one, we print out the first variable which is zero.
Else, we use a while loop to control the execution and create our Fibonacci series into variable next. Now if variable next is odd, we print it out and iterate the base condition.

Leave a Reply

Your email address will not be published. Required fields are marked *