write a menu driven program to run the following series using loop in bluej or java :- (i) Fibonacci series (ii) Tribonacci series
Answers
To understand these programs, you should have the knowledge of for loop and while loop.
If you are new to java, refer this java programming tutorial to start learning from basics.
Example 1: Program to print fibonacci series using for loop
public class JavaExample { public static void main(String[] args) { int count = 7, num1 = 0, num2 = 1; System.out.print("Fibonacci Series of "+count+" numbers:"); for (int i = 1; i <= count; ++i) { System.out.print(num1+" "); /* On each iteration, we are assigning second number * to the first number and assigning the sum of last two * numbers to the second number */ int sumOfPrevTwo = num1 + num2; num1 = num2; num2 = sumOfPrevTwo; } } }
Answer:
(i) fibonacci-
import java.util.*;
public class fibonacci
{
public static void main()
{
Scanner sc=new Scanner (System.in);
int a,b,c;
System.out.println("Enter a no. for fibonacci series=");
a=sc.nextInt();
b=(a+1);
c=a+b;
System.out.println(+c);
a=b;
b=c;
c=a+b;
System.out.println(+c);
a=b;
b=c;
c=a+b;
System.out.println(+c);
a=b;
b=c;
c=a+b;
System.out.println(+c);
a=b;
b=c;
c=a+b;
System.out.println(+c);
a=b;
b=c;
c=a+b;
System.out.println(+c);
}
}
(ii) tribonacci-
import java.util.*;
public class tribonacci
{
public static void main()
{
Scanner sc = new Scanner (System.in);
int a=0,b=1,c,d;
c=a+b;
d=a+b+c;
System.out.println(+a);
System.out.println(+b);
System.out.println(+c);
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
a=b;
b=c;
c=d;
d=a+b+c;
System.out.println(+d);
}
}