Skip to content

Commit

Permalink
Added FibonacciGenerator.java
Browse files Browse the repository at this point in the history
  • Loading branch information
gulatikeshav authored Oct 31, 2023
1 parent d808d72 commit d7c6d23
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions FibonacciGenerator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import java.util.Scanner;

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

System.out.print("Enter the number of terms in the Fibonacci sequence: ");
int numTerms = sc.nextInt();

generateFibonacci(numTerms);

sc.close();
}

public static void generateFibonacci(int numTerms) {
int[] fibonacciSequence = new int[numTerms];
fibonacciSequence[0] = 0;
if (numTerms > 1) {
fibonacciSequence[1] = 1;
}

for (int i = 2; i < numTerms; i++) {
fibonacciSequence[i] = fibonacciSequence[i - 1] + fibonacciSequence[i - 2];
}

System.out.println("Fibonacci sequence up to " + numTerms + " terms:");
for (int i = 0; i < numTerms; i++) {
System.out.print(fibonacciSequence[i] + " ");
}
}
}

0 comments on commit d7c6d23

Please sign in to comment.