-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #6979 from gulatikeshav/patch-6
Added FibonacciGenerator.java
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] + " "); | ||
} | ||
} | ||
} |