How to print out the addition of the fibonacci sequence? - java

I saw this code on the internet and decided to try it myself, but I've been wondering, how do you print out the addition of the "fibonacci"?
package fibonacci;
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int k, n, a = 1, b = 1;
k = 0;
System.out.println("input number: ");
n = sc.nextInt();
System.out.print("0 1 1 ");
while (k <= n) {
k = a + b;
if (k >= n) break;
System.out.print(k + " " );
a = b;
b = k;
}
System.out.println("Sum of 0 + 1 = 1");
System.out.println("Sum of 1 +" + a + " = " + b);
}
}
How can you generate an output like this:
0 1 1 2 3 5 8
0 + 1 = 1
1 + 1 = 2
1 + 2 = 3
2 + 3 = 5
3 + 5 = 8

this should answer your question:
package com.example.demo;
import java.util.Scanner;
public class Fibonaccci {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int k, n, a = 0, b = 1;
k = 0;
System.out.println("input number: ");
n = sc.nextInt();
System.out.print("0 1 ");
StringBuffer acumResults= new StringBuffer("\n");
while (k <= n) {
k = a + b;
acumResults.append(a+" + "+b+" = "+k+"\n");
System.out.print(k + " " );
if (k >= n) break;
a = b;
b = k;
}
System.out.println(acumResults);
}
}

Start a string with the initial calculation (0 + 1 = 1) and then append to it in each iteration of the loop the current calculation i.e.
System.out.print("0 1 1 ");
String addition = "0 + 1 = 1\n";
while (k <= n) {
k = a + b;
addition += a+ " + " +b + " = " + k + "\n";
if (k >= n) break;
System.out.print(k + " " );
a = b;
b = k;
}
System.out.println();
System.out.println(addition);

To produce exactly your output I would code the following:
package fibonacci;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int k, n, a = 1, b = 1;
k = 0;
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("input number: ");
n = sc.nextInt();
System.out.print("0 1 1 ");
numbers.add(1);
numbers.add(1);
while (k <= n) {
k = a + b;
if (k >= n) break;
System.out.print(k + " " );
a = b;
b = k;
numbers.add(k);
}
// used for loop since I don't know your Java version
System.out.println();
int oldSum = 0;
for (int i= 0; i < numbers.size(); ++i) {
int element = numbers.get(k);
System.out.println oldSum + " + " + element + " = " + (oldSum + element);
oldSum += element;
}
}
}

Related

Java: changing the order of lines with while-loop

I am new to programming and I would like to ask what should I do so that the final value of k will appear before the values of a, when I try to put it inside the loop it repeats the statement and when I put it before the loop, its value is 0.
System.out.printf("Input an integer: ");
int a = in.nextInt();
int k = 0;
System.out.print(a);
while(a > 1)
{
if(a % 2 == 0)
a = a / 2;
else
a = 3 * a + 1;
System.out.printf(", " + a);
k++;
}
System.out.println("\nk = " + k);
Output:
Input an integer: 10
10, 5, 16, 8, 4, 2, 1
k = 6
You could try:
System.out.printf("Input an integer: ");
int a = in.nextInt();
int k = 0;
String str_a = "";
System.out.print(a);
while(a > 1)
{
if(a % 2 == 0)
a = a / 2;
else
a = 3 * a + 1;
str_a += ", " + String.valueOf(a);
k++;
}
System.out.println("k = " + k);
System.out.println("a = " + str_a);

comparing a variable int that have multiple number without being an array

enter image description here
so i have this problem to solve it's working without any errors but the number of a and f isn't right they give me a false answer. the photo show the problem and we can't calculate f and a in the method genarategrades
static int genarategrades(int n) {
int a = 0;
for (int i = 0; i < n; i++) {
a = (int) (Math.random() * (100 - 50)) + 50;
System.out.print(a + " ");
}
return a;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
do {
System.out.print("Enter a positive value for n: ");
n = input.nextInt();
} while (n <= 0);
System.out.print("Genarate Grades: ");
int grade = genarategrades(n);
int A = 0;
int F = 0;
for (int i = 0; i < grade; i++) {
if (grade < 60)
F++;
else if (grade > 90)
A++;
}
System.out.println();
System.out.println("NB of A students: " + A);
System.out.println("NB of F students: " + F);
System.out.println("Percentage A: " + A + "/" + n + " = " + (double) A / n);
System.out.println("Percentage F: " + F + "/" + n + " = " + (double) F / n);
}
}
Call the genarateGrades() inside the loop if you don't want to use an array, like this:
static int genarateGrades(int n) {
int a = 0;
a = (int) (Math.random() * (100 - 50)) + 50;
System.out.print(a + " ");
return a;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
do {
System.out.print("Enter a positive value for n: ");
n = input.nextInt();
} while (n <= 0);
System.out.print("Generated Grades: ");
int A = 0;
int F = 0;
for (int i = 0; i < n; i++) {
int grade = genarateGrades(n);
if (grade < 60)
F++;
else if (grade > 90)
A++;
}
input.close();
System.out.println();
System.out.println("NB of A students: " + A);
System.out.println("NB of F students: " + F);
System.out.println("Percentage A: " + A + "/" + n + " = " + (double) A / n);
System.out.println("Percentage F: " + F + "/" + n + " = " + (double) F / n);
}
, output
Enter a positive value for n: 5
Generated Grades: 59 75 80 98 79
NB of A students: 1
NB of F students: 1
Percentage A: 1/5 = 0.2
Percentage F: 1/5 = 0.2

This program should ask user for the max num to print out to and then calculate each number starting from 1 to the maximum along with it squared

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[]arr1 = new int[max+1];
int[]arr2 = new int[max+1];
int[]arr3 = new int[max+1];
int i = 1;
// For-loop to calculate
for (i = 1;i <= max;i++)
arr1[i] = arr1[i-1] + i;
i = 1;
// While-loop to calculate
while (i <= max) {
arr2[i] = arr2[i-1] + i;
i++;
}
i = 1;
// Do-While-loop to calculate
do
arr3[i] = arr3[i-1] + i;
while (++i <= max);
for (i = 0; i <= max; i++)
System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);
System.out.println("Sum of All is " + arr1[max]);
}
I have this for doing sums but I am stuck when it comes to getting it to square
You seem to have 3 identical array objects?
Anyway, it's pretty straightforward to print the square of all numbers from 1 to max:
for (int i = 1; i <= max; i++) {
System.out.println(i + ": " + i * i);
}
There are also some fun ways to sum up the numbers from 1 to max, such as:
System.out.println(IntStream.range(1, max + 1).sum());

Dice Roll Histogram with Loops

I have a problem in my class that I just can't figure out.
This is the question:
The purpose of this quiz is to reinforce the understanding of using loops and counting as well as reviewing the use of random numbers.
Modify the program below to print a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character like # that number of times. Two dices will be used in each roll.
Example:
Histogram showing total number of dice rolls for each possible value.
Dice roll statistics (result varies):
2s: ######
3s: ####
4s: ###
5s: ########
6s: ###################
7s: #############
8s: #############
9s: ##############
10s: ###########
11s: #####
12s: ####
~~~~~~~~~~~~~~~~~~~~~
I haven't been able to get the program to print the histogram in the example above.
And this is what I have so far:
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int seedVal = 11;
randGen.setSeed(seedVal);
// FIXME 1 and 2: Set the seed to the Random number generator
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
// FIXME 3: Declare and initiate cariables needed
int numOnes = 0;
int numTwos = 0;
int numThrees = 0;
int numFours = 0;
int numFives = 0;
int numSixes = 0; // Tracks number of 6s found
int numSevens = 0; // Tracks number of 7s found
int numEights = 0;
int numNines = 0;
int numTens = 0;
int numElevens = 0;
int numTwelves = 0;
int die1 = 0; // Dice 1 values
int die2 = 0; // Dice 2 values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
if (rollTotal == 1) {
numOnes = numOnes + 1;
}
if (rollTotal == 2) {
numTwos = numTwos + 1;
}
if (rollTotal == 3) {
numThrees = numThrees + 1;
}
if (rollTotal == 4) {
numFours = numFours + 1;
}
if (rollTotal == 5) {
numFives = numFives + 1;
}
if (rollTotal == 6) {
numSixes = numSixes + 1;
}
if (rollTotal == 7) {
numSevens = numSevens + 1;
}
if (rollTotal == 8) {
numEights = numEights + 1;
}
if (rollTotal == 9) {
numNines = numNines + 1;
}
if (rollTotal == 10) {
numTens = numTens + 1;
}
if (rollTotal == 11) {
numElevens = numElevens + 1;
}
else if (rollTotal == 12) {
numTwelves = numTwelves + 1;
}
System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Print statistics on dice rolls
System.out.println("\nDice roll statistics:");
// FIXME 5: Complete printing the histogram
System.out.println("1s: " + numOnes);
System.out.println("2s: " + numTwos);
System.out.println("3s: " + numThrees);
System.out.println("4s: " + numFours);
System.out.println("5s: " + numFives);
System.out.println("6s: " + numSixes);
System.out.println("7s: " + numSevens);
System.out.println("8s: " + numEights);
System.out.println("9s: " + numNines);
System.out.println("10s: " + numTens);
System.out.println("11s: " + numElevens);
System.out.println("12s: " + numTwelves);
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
Any help would be very appreciated.
Have a loop like this where you have your print statements.
Modify your code so that instead of taking new variables every time have them in a array so that you can loop through them.
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int seedVal = 11;
randGen.setSeed(seedVal);
// FIXME 1 and 2: Set the seed to the Random number generator
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
// FIXME 3: Declare and initiate cariables needed
int[] numValues=new int[12];
int die1 = 0; // Dice 1 values
int die2 = 0; // Dice 2 values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
numValues[rollTotal]++;
System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Print statistics on dice rolls
System.out.println("\nDice roll statistics:");
// FIXME 5: Complete printing the histogram
for(int i=2;i<=12;i++)
{
System.out.print(i+"s: ");
for(int j=0;j<numVales[i];j++)
{
System.out.print("#");
}
System.out.println();
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
Let me know if you need clarification on the problem.
You can do something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//You can directly set the seed during the object creation.
Random random = new Random(System.currentTimeMillis());
// This array is used to keep the value of your dice (2 - 12)
int [] histogram = new int[13];
while(true) {
System.out.println("Enter number of rolls: ");
int numberOfRolls = scanner.nextInt();
//If you enter 0, you can simply terminate the program
if(numberOfRolls == 0) break;
for(int i = 0; i < numberOfRolls; i++) {
int rolledValue = (random.nextInt(6) + 1) + (random.nextInt(6) + 1);
histogram[rolledValue]++;
}
//Print the result to your console.
for(int i = 2; i < histogram.length; i++) {
System.out.print("Total: " + i + " ");
for(int j = 0; j <histogram[i]; j++) {
System.out.print("#");
}
System.out.println();
}
}
}
That code will have a result as below:
Enter number of rolls: 7
Total: 2
Total: 3 #
Total: 4
Total: 5 ##
Total: 6
Total: 7 ###
Total: 8
Total: 9
Total: 10 #
Total: 11
Total: 12
Looks like you're really close. You just need to print the number of # for each int variable you have. The following will do that for the numTwos:
char[] chars = new char[numTwos];
Arrays.fill(chars, '#');
String result = new String(chars);
System.out.println(result);
You can put the whole thing in a loop of 12 to print it for all of them.

Create a java program to display multiples of a number

I'm trying to Write the main method of a Java program that has the user enter two integers, i and n. If either integer is less than 2, output “Please enter numbers above 1.” Otherwise, output the n positive multiples of i, separated by spaces.
I'm close but can't figure out how to do display the multiples.
Here's what a sample run should look like:
Enter i: 4
Enter n: 6
6 multiples of 4 are: 8 12 16 20 24 28
import java.util.*;
public class HW5Problem3 {
public static void main (String [] args) {
int i = 0;
int n = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter i: ");
i = input.nextInt();
System.out.print("Enter n: ");
n = input.nextInt();
if ((i <= 1) || (n <= 1)) {
System.out.println("Please enter numbers above 1");
System.exit(1);
}
System.out.print(n + " multiples of " + i + " are: ");
}
}
import java.util.Scanner;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int i = 0;
int n = 0;
//It's use to verify the inputs (i and n).
do{
System.out.print("Enter i :");
i = input.nextInt();
System.out.print("\nEnter n :");
n = input.nextInt();
if(i >= 1 || n <= 1){
System.out.println("Please enter numbers above 1 \n");
}
}while(i <= 1 || n <= 1);
System.out.print(n + " multiples of " + i + " are: ");
for (int counter = 0 ; counter < n ; counter++) {
System.out.print(i*(2 + counter) + " ");
}
}
You'll need to create a loop (for loop or while loop) to iterate from 2 to n+1, and multiply i by your loop variable, outputting each value inside the loop
U can use following method in that class
public static void mult(int i,int n){
int[] arr=new int[n];
int count=2;
for(int x=0;x<n;x++){
arr[x]=i*count++;
}
for(int y=0;y<arr.length;y++){
System.out.print(arr[y]+" ");
}
and now your final code looks like
import java.util.*;
public class HW5Problem3 {
private int i = 0;
private int n = 0;
public static void main(String[] args) {
int i = 0;
int n = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter i: ");
i = input.nextInt();
System.out.print("Enter n: ");
n = input.nextInt();
if ((i <= 1) || (n <= 1)) {
System.out.println("Please enter numbers above 1");
System.exit(1);
} else {
System.out.print(n + " multiples of " + i + " are: ");
mult(i, n);
}
}
public static void mult(int i, int n) {
int[] arr = new int[n];
int count = 2;
for (int x = 0; x < n; x++) {
arr[x] = i * count++;
}
for (int y = 0; y < arr.length; y++) {
System.out.print(arr[y] + " ");
}
}
}
n is the multiplier, i is the factor, right? In programming the multiplier is the loop maximum:
System.out.print(n + " multiples of " + i + " are: ");
for (int inc=1; inc<=n; inc++) {
System.out.print(" " + i*inc);
}
This prints out: 4 8 12 16 20 24
If you really want to have this as output: 8 12 16 20 24 28 copy/paste this line:
for (int inc=2; inc<=(n+1); inc++)

Categories

Resources