Home > Software design >  Printing Fibonacci series between 1-99
Printing Fibonacci series between 1-99

Time:03-28

The program listed is about writing the Fibonacci series given user input that is below 100. The problem that I am having is figuring out how to get the Fibonacci to not print if the number listed by the user is above 100. However, I am unable to figure out what to do. This is my code, I am not trying to use while loop to only print if the number is between 1 and 100. however when I print 101, it still gives me the Fibonacci series.

import java.util.Scanner;

class Program_2 { 
  public static void main(String [] args){
    Scanner console = new Scanner(System.in);

    System.out.println("Enter an integer between 1-99: ");
    int num = console.nextInt(); 

    while (num>1) { 
      if(num<100) {
      System.out.println("Fibonacci Series till "   num   " terms:");
        }
      int n = 100, firstTerm = 0, secondTerm = 1;
      for (int i = 1; i <= n;   i) {
        System.out.print(firstTerm   ", ");
  
        // compute the next term
        int nextTerm = firstTerm   secondTerm;
        firstTerm = secondTerm;
        secondTerm = nextTerm;
      
        }      
    }
   } 
  }

The Output that im getting when i print 101, is

enter image description here

I've used an if/else statement, but for some reason, it didnt do anything. Then I tried using a while loop and an if statement, but its still printing above 100. I am unsure how to go about this. Any help is very much appreciated!

CodePudding user response:

To fix this issue, you can add another condition into your while loop. Right now, you are going into the while loop as long as num is greater than 1. Thus, numbers above 100 are being considered as well. To fix this, you can make your while loop start like this: while(num>1 && num<=100).

CodePudding user response:

Your while check "while(n>1)" will run infinitely. You need to change num's value after every iteration like this:

num--; //In the loop

And when num becomes less than 1, the program exits from the loop.

If you want to check whether num is less than 100 or bigger than 1 use if statement(to check if input value corresponds to your range)

while(num > 1 && num < 100){
    //your code in while loop
}else{
    System.out.println("Your value is too big or too small!");
}

And also I've noticed your output of fibonacci sequence is not right(negative values, bound in int32). You can't even display in long values because fibonacci of 9*th order are over quadrillions. Try to use BigInteger in order to show right values in the console output. Want to fancy your output? Use /t and %n in System.out.print();

  • Related