Problem: - Write a Java program to print the Nth odd Fibonacci series.
Solution: -For example:- 1 3 5 13 21 ......
Java code: -
package com.codeforsolution.java.logical;
import java.util.Scanner;
public class OddFibonacciSeriesExample {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Enter the terms to print odd fibonacci series: ");
int term=sc.nextInt();
sc.close();
int num1=0,num2=1;
printOddFibonacci(num1, num2,term);
}
private static void printOddFibonacci(int num1, int num2, int term) {
int iter=0,next;
if(term<=0)
System.out.println("Entered number should be greater than zero");
if(term==1)
System.out.print(num1);
else
{
while(iter<term)
{
next=num1+num2;
num1=num2;
num2=next;
if(next%2!=0)
{
System.out.print(" "+next);
iter++;
}
}
}
}
}
Output: -
Enter the terms to print odd fibonacci series: 5
1 3 5 13 21