- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java Program To Print Fibonacci Sequence
Here's a Java program to print the Fibonacci sequence up to a specified number of terms:
public class Fibonacci {
public static void main(String[] args) {
int n = 10; // Number of terms
printFibonacci(n);
}
static void printFibonacci(int n) {
int n1 = 0, n2 = 1, n3;
System.out.println("Fibonacci Sequence:");
System.out.print(n1 + " " + n2); // Print first two terms
for (int i = 2; i < n; i++) {
n3 = n1 + n2;
System.out.print(" " + n3);
n1 = n2;
n2 = n3;
}
}
}
This program calculates and prints the Fibonacci sequence up to the specified number of terms (n). It initializes the first two terms as 0 and 1, and then iteratively calculates the next terms by adding the previous two terms (n1 and n2). Finally, it prints each term in the sequence.