Tuesday, 9 July 2019

Published July 09, 2019 by with 0 comment

BCSlL043 June 2016 Set 3 Solution




Question 1- Write a  java Program  to generate Fibonacci series. The starting number for  the series should be 0. Define proper class, constructor and methods in your program.

solution - 

import java.util.Scanner;
class fibonacci
{
int first_term,second_term;
fibonacci()
{
first_term=0;
second_term=1;
}
void print_fibonacci(int n)
{
        int fib;
for (int i=1;i<=n;i++)
{
            if(i==1)
            {
              fib=first_term;
            }
            else if(i==2)
            {
            fib=second_term;
            }
            else
            {
            fib = first_term+second_term;
            first_term=second_term;
            second_term = fib;
            }
            System.out.print(fib + " ");
}
}
}

public class textexample
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
fibonacci f1 = new fibonacci();

System.out.println("how many terms of fibonacci you want to print ?");
int n = sc.nextInt();
f1.print_fibonacci(n);
}
}

FileName: textexample.java

To execute the file first go to that directory where this file is saved. than complie the file usign this command :  javac textexample.java
To run the file type this command: java textexample

output:

how many terms of fibonacci you want to print ?
15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377



if you have any doubt related to this post, you can ask in comment section and if you want solution of any previous year questions. please post that question in section we will try to solve that

Thank You




0 comments:

Post a Comment