Computer Science, asked by dsdwkarunarathna9811, 10 months ago



Java program for loop 1 2 3 4 5 13 21

Answers

Answered by muskaan1411
1

public class Fibonacci {

public static void main(String[] args) {

int n = 100, t1 = 0, t2 = 1;

System.out.print("Upto " + n + ": ");

while (t1 <= n)

{

System.out.print(t1 + " + ");

int sum = t1 + t2;

t1 = t2;

t2 = sum;

}

}

}

When you run the program, the output will be:

Upto 100: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 +

Instead of displaying the series upto a specific number, this program displays it until a given number (100).

For this, we just need to compare the sum of last two numbers (t1) with n.

If t1 is less than or equals to n, print t1. Else, we're finished displaying all terms

Similar questions