Fibonacci Series java - java

I have generated a program that calculates the fibonacci series with a limit given by the user by keyboard, but I have a problem, since I have asked that the series start at 1, and not at zero as I had done. How can I do that? my fibonacci series shows me from 1 and not from 0?
int maxNumber = 0;
int previousNumber = 0;
int nextNumber = 1;
System.out.println("How many numbers you want in Fibonacci:");
Scanner scanner = new Scanner(System.in);
maxNumber = scanner.nextInt();
System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
for (int i = 1; i <= maxNumber; ++i)
{
System.out.print(previousNumber+" ");
int sum = previousNumber + nextNumber;
previousNumber = nextNumber;
nextNumber = sum;
}

Use int previousNumber = 1; and it will start from 1.

Just make a simple change and print the number after calculation.
for (int i = 1; i <= maxNumber; ++i)
{
// System.out.print(previousNumber+" ");
int sum = previousNumber + nextNumber;
previousNumber = nextNumber;
nextNumber = sum;
System.out.print(previousNumber+" ");
}

source: Programmers Interview
/*Java Program to find the FibonacciSeries */
public class FibonacciSeries {
public static void main(String a[]){
int limit = 15; /* give limit here */
int[] feb = new int[limit];
feb[0] = 0;
feb[1] = 1;
/* store all elements in array feb[] */
for(int i=2; i < limit; i++){
feb[i] = feb[i-1] + feb[i-2];
}
/* print all array elements */
for(int i=0; i< limit; i++){
System.out.print(feb[i] + " ");
}
}
}

public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int count=scanner.nextInt();
scanner.close();
int firstTerm=1;
int secondTerm=2;
int nextTerm;
System.out.println("-----------------------");
System.out.print("Fibonacci Series: ");
System.out.print(firstTerm+","+secondTerm);
for(int i=3; i<=count; i++) {
nextTerm=firstTerm+secondTerm;
System.out.print(","+nextTerm);
firstTerm=secondTerm;
secondTerm=nextTerm;
}
}

Related

Average, minimum, maximum

so in my program is where the user enters list of numbers one at a time, and when I would end the list numbers with the "end" statement which is set to -1, and once I do that I get my average, and maximum, and minimum, my problem is that when I do get the minimum output it would be -1 everytime, I'm having trouble to remove the -1 from the array, any ideas???
import java.util.Scanner; //import scanner to user scanner tool
public class Average { //creating public class
public static void main(String[]args) { //creating public static main
Scanner input = new Scanner(System.in); //creating scanner input to grab user input
System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
double[] numbers = new double[20]; //creating 20 count array
double sum = 0;
int count = 0;
double average;
int end = -1;
for(int i = 0; i<numbers.length; i++) {
System.out.print("Enter a number: ");
numbers[i] = input.nextDouble();
if(numbers[i]== end) {
break;
}
sum+= numbers[i];
count++;
}
// gets average from user input of numbers
average = sum/count;
System.out.println("Average is: " + average);
double max = maxim(numbers);
System.out.println("Max: " + max);
double min = minim(numbers);
System.out.println("Min: " + min);
}
//method for finding out maximum number from user input
public static double maxim(double[] array) {
double maxNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] > maxNum) {
maxNum = array[i];
}
}
return maxNum;
}
//method for finding out minimum number from user input
public static double minim(double[] array) {
double minNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] < minNum && array[i]!=-1) {
minNum = array[i];
}
}
return minNum;
}
}
You need to docouple part of code that responsible for reading user input from code that compute statistics. And for remove -1 from resulting array you need simple don't put this value to result. When user input random number first check if it is not -1, and after that put it in result. Something like that:
import java.util.Scanner;
public class Average {
public static void main(String[]args) { //creating public static main
double[] numbers = readInputNumbers();
System.out.println("Average is: " + average(numbers));
System.out.println("Max: " + max(numbers));
System.out.println("Min: " + min(numbers));
}
public double[] readInputNumbers() {
Scanner input = new Scanner(System.in); //creating scanner input to grab user input
System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
double[] numbers = new double[20];
final int endInput = -1;
for(int i = 0; i < numbers.length; i++) {
System.out.print("Enter a number: ");
double nextNumber = input.nextDouble();
if(nextNumber == endInput) {
break;
} else {
numbers[i] = nextNumber;
}
}
return numbers;
}
public static double max(double[] array) {
double maxNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] > maxNum) {
maxNum = array[i];
}
}
return maxNum;
}
public static double min(double[] array) {
double minNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] < minNum && array[i]!=-1) {
minNum = array[i];
}
}
return minNum;
}
public static double average(double[] numbers) {
double sum = 0;
for(int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
return sum / numbers.length;
}
}
In jdk since 8 version your could be simplify this task like this:
import java.util.Scanner;
import java.util.stream.*;
public class Average {
public static void main(String[]args) { //creating public static main
double[] numbers = readInputNumbers();
DoubleSummaryStatistics statistics = DoubleStream.of(numbers).summaryStatistics();
System.out.println("Average is: " + statistics.getAverage()));
System.out.println("Max: " + statistics.getMax());
System.out.println("Min: " + statistics.getMin());
}
public double[] readInputNumbers() {
Scanner input = new Scanner(System.in); //creating scanner input to grab user input
System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
double[] numbers = new double[20];
final int endInput = -1;
for(int i = 0; i < numbers.length; i++) {
System.out.print("Enter a number: ");
double nextNumber = input.nextDouble();
if(nextNumber == endInput) {
break;
} else {
numbers[i] = nextNumber;
}
}
return numbers;
}
}
You could take the input into a temp variables and store it in the array only if it isn't the end flag (-1). E.g.:
for(int i = 0; i<numbers.length; i++) {
System.out.print("Enter a number: ");
double temp = input.nextDouble();
if(temp == end) {
break;
}
numbers[i] = temp;
sum += numbers[i];
count++;
}

Second array is just random

I need to write a program that produces a single random permutation of the numbers 1 - 10. If possible, no methods or extra include libraries. Simple as can be. Here is what I have so far.
import java.util.Scanner;
public class SwitchingNum {
public static void main(String[] args) {
int num = 10;
Scanner in = new Scanner(System.in);
int[] tempArray = new int[10];
int currentSize = tempArray.length;
System.out.print("First Array: ");
for(int i = 0; i < num; i++){
tempArray[i] = i + 1;
System.out.print(tempArray[i] + " ");
}
int[] permArray = new int[tempArray.length];
System.out.println();
System.out.print("Second Array: ");
for (int i = 0; i < permArray.length; i ++){
permArray[i] = tempArray[(int) (Math.random() * currentSize -1)];
for (int j = i; j < currentSize -1; j++){
tempArray[i] = tempArray[i+1];
}
currentSize--;
System.out.print(permArray[i] + " ");
}
}
}
An easy way to shuffle an array is the Fisher–Yates shuffle. Just copy the original array into your permArray and then do:
Random rand = new Random();
for(int i = 0; i < permArray.length - 1; i++) {
int swapPosition = rand.nextInt(permArray.length - i) + i;
int tmp = permArray[i];
permArray[i] = permArray[swapPosition]
permArray[swapPosition] = tmp;
}
Don't forget to import java.util.Random. For more info, you can take a look at this question.

program that reads in ten numbers and displays the number of distinct numbers and the distinct numbers separated by one space

I know that this question has been asked before, but not in the the format that I'm writing my code.. Just started taking java classes so I am not familiar with any complex java.. the code below consists of basically all the java I know. Please help! Thanks in advance.
import java.util.Scanner;
public class problem2try {
public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;
//input
System.out.print("Please enter in 10 integers: ");
for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}
//processing
distinctArray[0] = inputList[0];
for (int i = 1; i < inputList.length; i++)
{
for (int j = 0; j < inputList.length; j++)
{
if (inputList[i] == inputList[j])
{
counter++;
continue;
}
else
{
distinctArray[i] = inputList[i];
}
}
}
//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<distinctArray.length; x++)
{
if (distinctArray[x] != 0)
System.out.print(distinctArray[x] + " ");
}
}
}
Your logic in the "processing" block seemed off. I modified it to check the current number (outer loop) to all of the known numbers (inner loop). If no match was found, it is appended to the list of known numbers and the count is incremented.
I also modified the "output" code to print the first counter numbers from the list of known numbers. Values past that index are uninitialized.
import java.util.Scanner;
public class problem2try {
public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;
//input
System.out.print("Please enter in 10 integers: ");
for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}
//processing
for (int i = 0; i < inputList.length; i++)
{
boolean found = false;
for (int j = 0; j < counter; j++)
{
if (inputList[i] == distinctArray[j])
{
found = true;
break;
}
}
if (!found)
{
distinctArray[counter++] = inputList[i];
}
}
//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<counter; x++)
{
System.out.print(distinctArray[x] + " ");
}
}
}

ForLoops Largest and Smallest number

so how would you find the largest and smallest number here?
import java.util.Scanner;
public class Loops2 {
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Type 10 numbers");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
System.out.println(number);
}
}
}
Assuming that what you are trying to do is find the largest and smallest integers are in an array of integers:
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Type 10 numbers");
//I will create the array here...
int[] nums = new int[10];
//assigning numbers/ints
for(int i = 0; i < 10; i++) {
nums[i] = input.nextInt();
}
//now to find the largest and smallest (in this order)
int largest = 0;
for(int j = 0; j < nums.length; j++)//usage of the 1-line rule :)
if(nums[j] > largest)
largest = nums[j];
int smallest = largest;
//I'm doing this, so that it keeps checking for something lower than the largest number...
for(int k = 0; k < nums.length; k++)//usage of the 1-line rule again :)
if(nums[k] < smallest)
smallest = nums[k];
System.out.println("Largest: " + largest);
System.out.println("Smallest: " + smallest);
}
Hope this helps!
This is probably the best way to implement it
import java.util.Scanner;
public class FindLargestSmallestNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Type 10 numbers");
//array of 10 numbers
int numbers[] = new int[10];
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
System.out.println(number);
numbers[i] = number ;
}
//assign first element of an array to largest and smallest
int smallest = numbers[0];
int largetst = numbers[0];
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > largetst)
largetst = numbers[i];
else if (numbers[i] < smallest)
smallest = numbers[i];
}
System.out.println("Largest Number is : " + largetst);
System.out.println("Smallest Number is : " + smallest);
}
}
import java.util.Scanner;
public class LargestSmallestNumbers {
private static Scanner input;
public static void main(String[] args) {
int count,items;
int newnum =0 ;
int highest=0;
int lowest =0;
input = new Scanner(System.in);
System.out.println("How many numbers you want to enter?");
items = input.nextInt();
System.out.println("Enter "+items+" numbers: ");
for (count=0; count<items; count++){
newnum = input.nextInt();
if (highest<newnum)
highest=newnum;
if (lowest==0)
lowest=newnum;
else if (newnum<=lowest)
lowest=newnum;
}
System.out.println("The highest number is "+highest);
System.out.println("The lowest number is "+lowest);
}
}
List<Integer> list = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Type 10 numbers");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
System.out.println(number);
list.add(number);
}
Collections.sort(list);
System.out.println("the small: "+ list.get(0));
System.out.println("the big: "+list.get(list.size() - 1));

Simple Java Fibonacci code issue

import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i<count; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i<count; i++)
{
System.out.print(fib[i] + " ");
}
}
}
This is my very simple Fib program, what i cant figure out is why it always stops one number short. For example:
run: Please enter number 6 1 1 2 3 5 8 BUILD SUCCESSFUL (total time: 5
seconds)
run: Please enter number 7 1 1 2 3 5 8 13 BUILD SUCCESSFUL (total
time: 5 seconds)
I thought in my FOR loops it should be "(int i=2; i <= count;"
but when i put in greater than or equal to in both, or either FOR loop it gives me an error
Any suggestions? i know its something easy i'm overlooking
Your code is giving correct output. but still if you need one more element try to initialize array with count + 1 and then have your loop running for i <= count
public static void main(String[] args) {
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count+1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= count; i++){
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i <= count; i++){
System.out.print(fib[i] + " ");
}
}
}
Arrays are zero-based. This means, that (assuming count = 5) if you have the following array:
int[] fib = new int[5];
then you can access fib[0], fib[1], fib[2], fib[3] and fib[4]. So
for (int i = 0; i < 5; i++) {
System.out.print(fib[i] + " ");
}
would be fine. As it would access everything in fib, starting with index 0, and stopping with the last index smaller than 5, which is 4. However, if you do:
for (int i = 0; i <= 5; i++) {
System.out.print(fib[i] + " ");
}
then you will access the last index smaller than OR EQUAL TO 5, which is 5. But, as stated before, fib[5] is invalid. That's what gives you your error.
A simpler solution is to avoid needing an array in the first place and you don't need to get the size right.
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
int count = in.nextInt();
long a = 1, b = 1;
for(int i = 0; i < count; i++) {
System.out.print(a + " ");
long c = a + b;
a = b;
b = c;
}
System.out.println();
}
There should be one more array element space for int fib[], thus the fib[count] could be stored.
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count + 1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= count; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i = 0; i<= count; i++)
{
System.out.print(fib[i] + " ");
}
}
}
public class Fibonacci
{
private int [] fibArray;
public Fibonacci()
{
}
public void Fibonacci()
{
fibArray = new int[0];
}
public void setFibonnaci(int size)
{
fibArray = new int[size];
if(fibArray.length == 1)
{
fibArray [0] = 0;
}
else if(fibArray.length == 2)
{
fibArray[0] = 0;
fibArray[1] = 1;
fibArray[2] = 2;
}
else
{
fibArray[1] = 1;
fibArray[0] = 0;
for(int x = 2; x < fibArray.length; x++)
{
fibArray [x] = fibArray[x-1] + fibArray[x-2];
}
}
}
public int getSequence(int number)
{
if(number -1 < fibArray.length)
{
return fibArray[number - 1];
}
return -1;
}
//check the test case for getFibo
public String toString()
{
String output = "";
for (int x = 0; x < fibArray.length; x++)
{
output += x + " - " + fibArray[x];
}
return output;
}
}
Late response but new to site and just trying to help. This fib class works 100%

Categories