Computing average to Fibonacci numbers - java

My task is to ask the user how many Fibonacci numbers they want and to print that, then also show the average of those numbers. I made a method to show the Fibonacci numbers in my code below, but I'm having a hard time figuring out how to incorporate the average part of the program. Not asking for you to do it for me because this is homework for class, but it would be nice to know where I am supposed to write the average part of the program.
import java.util.Scanner;
public class Clancy_Hw_03_04{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
int number = 0;
System.out.println ("Enter N: ");
number = input.nextInt();
System.out.println("\n\nFibonacci series for " + number +" numbers : ");
for(int i=1; i<=number; i++){
System.out.print(fibonacciLoop(i) +" ");
}
}
public static int fibonacciLoop(int number){
if(number == 1 || number == 2){
return 1;
}
int fibo1=1, fibo2=1, fibonacci=1;
for(int i= 3; i<= number; i++){
fibonacci = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}
}

Your problem might be easier to solve if you printed the fibonacci numbers from within your function, fibonacciLoop(), and not try to return each successive number and print it from the main loop. Then the sum and average are right at your fingertips.
For instance:
public static void main(...) {
...
System.out.println("\n\nFibonacci series for " + number +" numbers : ");
fibonacciLoop(i);
}
static void fibonacciLoop(int number) {
int fibo1 = 1, fibo2 = 1, sum = 0, average = 0, fibonacci;
for (int i = 1; i <= 2 && i <= number; i++) {
System.out.print("1 ");
sum += 1;
}
for (i = 3; i <= number; i++) {
fibonacci = fibo1 + fibo2;
System.out.print(fibonacci + " ");
fibo1 = fibo2; fibo2 = fibonacci;
sum += fibonacci;
}
System.out.println(" average = " + (float)sum/number)
}
Edit: Made sure to convert sum to a float before calculating average

Keep computing the sum and then divide it by number.
You can do something like...
int sum = 0;
for(int i=1; i<=number; i++){
int fibo = fibonacciLoop(i);
System.out.print(fibo +" ");
sum += fibo;
}
System.out.println("Average = " + sum/number);
I hope this time I got your question right.

Put another integer in your main function, to store the total value:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number = 0;
int sum = 0; // Add this here
}
Then, inside your fibonacci function, add to that variable:
public static int fibonacciLoop(int number)
{
if(number == 1 || number == 2)
{
sum += 1;
return 1;
}
int fibo1=1, fibo2=1, fibonacci=1;
for(int i= 3; i<= number; i++)
{
fibonacci = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = fibonacci;
}
sum += fibonacci; //Put this here, outisde the loop
return fibonacci;
}
When you want to output the average, simply divide sum by number:
System.out.println("Average is: " + (sum / number));

Related

How to find the smallest element in an user inputted array? Why the smallest element is displayed zero?

The code displays the sum, average, and largest element. It doesn't display the smallest element as the output is always zero. How do I display the smallest element in the array?
import java.util.Scanner;
public class Average {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int length = input.nextInt();
int[] num = new int[length];
System.out.println("Enter the "+ length + " array elements:");
int sum = 0;
int large,small;
large =small = num[0];
for (int i=0; i<length;i++) {
num[i] = input.nextInt();
sum = sum+ num[i];
}
for (int i=0; i<length; ++i) {
if (num[i]<small) {
small = num[i];
}
if(num[i]> large) {
large = num[i];
}
}
double avg = sum/length;
System.out.println("The sum is "+ sum);
System.out.println("The average is "+ avg);
System.out.println("The smallest element is "+ small);
System.out.println("The largest element is "+ large);
}
}
import java.util.Scanner;
class Average {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int length = input.nextInt();
int[] num = new int[length];
System.out.println("Enter the " + length + " array elements:");
int sum = 0;
int large, small;
for (int i = 0; i < length; i++) {
num[i] = input.nextInt();
sum = sum + num[i];
}
large = small = num[0]; // small should be assigned after num is input
for (int i = 0; i < length; ++i) {
if (num[i] < small) {
small = num[i];
}
if (num[i] > large) {
large = num[i];
}
}
double avg = sum / length;
System.out.println("The sum is " + sum);
System.out.println("The average is " + avg);
System.out.println("The smallest element is " + small);
System.out.println("The largest element is " + large);
}
}
Yea, it's happening because by default your field small is equal to 0.
And now let's look step by step your if statement
if (num[i]<small) {
small = num[i];
}
example for numbers: 22,11,6,
So first step is num[0] < 0, why 0 as mention before small = 0 by default
Step two num[1] < 0, small stills stay 0
Step Three num[2] < 0, small stills stay 0.
What are you missing, you need to assign value to small at the first iteration of your for loop, for example:
for (int i=0; i<length; ++i) {
if(i == 0){
small = num[i];
}
if (num[i]<small) {
small = num[i];
}
if(num[i]> large) {
large = num[i];
}
}
Now your program should work :)
if you use java 8 or above, you can use the stream method of Arrays. it simplifies work with arrays. for more info
firstly import the Arrays as import java.util.Arrays;
System.out.println("The sum is " + Arrays.stream(num).sum());
System.out.println("The average is " + Arrays.stream(num).average());
System.out.println("The smallest element is " + Arrays.stream(num).min());
System.out.println("The largest element is " + Arrays.stream(num).max());

Java sum from 1 to n with output showing work

I have a homework problem that I've almost finished, but I'm just stuck on how to output it correctly.
Write a program that reads a positive integer n and prints the sum of all integers from 1 to n as follows:
1+2+…+n=n(n+1)/2
The output does not contain any spaces.Example of input: 5 Corresponding output: 1+2+3+4+5=15
Here's my code:
import java.util.Scanner;
public class Homework2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
for (int i = 0;i <= n; i++) {
sum = sum + i;
}
System.out.printf("the sum of %d is %d%n", n, sum);
}
}
What I have in the printf command is just a placeholder until I can figure out the correct output.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1;i <= n; i++) {
if (i != n) {
System.out.print(i + "+");
} else {
System.out.print(i + "=");
}
}
System.out.print(n*(n+1)/2);
}
the above will work. You must be strict to the expected output.
You need to print within the loop.
And you should start at 1, like the instructions say
for (int i = 1;i < n; i++) {
sum = sum + i;
System.out.printf("%d+", i);
}
sum += n;
System.out.printf("%d=%d\n", n, sum);
You can deal with the case of printing n and = separately like so:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Print the sum of all integers from 1 to n program");
System.out.println("=================================================");
System.out.print("Please enter n: ");
int n = scanner.nextInt();
int sum = 0;
for(int i = 1; i < n; i++) {
System.out.print(i + "+");
sum += i;
}
sum += n;
System.out.print(n + "=" + sum);
}
}
Try it here!
Example output:
Print the sum of all integers from 1 to n program
=================================================
Please enter n: 5
1+2+3+4+5=15

Sum and average of numbers in Java

Here is the code but it's not optimized for all the exceptions. For example, if the user types 0 from the beginning, it will give the division by zero error and also I don't know why the sum of the numbers work.
Basically, I make num = 1 so it's different than 0 so the while loop can start, but in the end, I made sum = sum - 1; but it gave a wrong number.
Please help me.
import java.util.Scanner;
class Main {
public static void main (String[] args) {
int count = 0;
int num = 1;
double average = 0.0;
int soma = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Type a integer. 0 to exit.");
while (num != 0) {
num = scanner.nextInt();
sum = sum + num;
count++;
}
if (num == 0) {
average = sum / (count -1);
System.out.println("The sum of the numbers is: "+ soma);
System.out.println("The average of the numbers is: "+ media);
}
}
}
change while to do while:
do {
num = scanner.nextInt();
sum = sum + num;
count++;
}while (num != 0);
Change FROM:
average = sum / (count -1);
System.out.println("The sum of the numbers is: "+ soma);
System.out.println("The average of the numbers is: "+ media);
TO:
average = sum / (count);
System.out.println("The sum of the numbers is: "+ sum);
System.out.println("The average of the numbers is: "+ average);
it should work

Factorial Issue

I am new at coding Java, but I need to write a program that is from integer 1 to n. The program would ask the user to enter a positive number and if it is not positive then it will ask for another number.
Once the positive integer is entered for n in the program, it shows how the n factorial is computed followed by the result.
So my program will show everything correct except the result, it is not multiplying all the numbers together. If someone can point me in the right direction on how to get this solved that would be great!
CODE:
import java.util.Scanner;
public class Problem5 {
public static void main(String[] args){
int n, i =1;
Scanner kbd = new Scanner(System.in);
System.out.print("Enter n: ");
n = kbd.nextInt();
while (n <= 0) {
System.out.print("Enter n: ");
n = kbd.nextInt();
}
for (i = 1; i <= n; i++){
System.out.print( i+ "*");
}
System.out.print(" is " + n * i);
}
}
Output:
Enter n: 5
1*2*3*4*5* is 30
As you can see for the result it should be 120 and not 30.
Just change that part
for (i = 1; i <= n; i++){
System.out.print( i+ "*");
}
System.out.print(" is " + n * i);
for
int result = 1;
for (i = 1; i <= n; i++){
System.out.print( i+ "*");
result *= i;
}
System.out.print(" is " + result);
Your last print was wrong as you simply multiplied n with i which is a simple multiplication and have nothing to do with factorial.
Your program is doing exactly one computation ( " is " + n * i) and this computation is not doing a factorial. You probably want to do the multiplication more than once - and with different numbers.
You are not doing the calculation properly. You just show the end result of n*i`.
In the below solution, I've taken an int fact = 1 and I'm multiplying it with the value of i inside the for loop and assigning back the result to factvariable. That's the core part. Thats how you get 1*2*3...*n = n!
import java.util.Scanner;
public class SomeArrayQuestion {
public static void main(String[] args) {
int n, i = 1;
Scanner kbd = new Scanner(System.in);
System.out.print("Enter n: ");
n = kbd.nextInt();
while (n <= 0) {
System.out.print("Enter n: ");
n = kbd.nextInt();
}
int fact = 1;
for (i = 1; i <= n; i++) {
System.out.print(i + "*");
fact = fact * i;
}
System.out.print(" is " + fact);
}
}
import java.util.Scanner;
public class Problem5 {
public static void main(String[] args){
int n, i =1;
Scanner kbd = new Scanner(System.in);
System.out.print("Enter n: ");
n = kbd.nextInt();
while (n <= 0) {
System.out.print("Enter n: ");
n = kbd.nextInt();
}
int result = 1;
for (i = 1; i <= n; i++){
System.out.print( i+ "*");
result *= i;
}
System.out.print(" is " + result);
}
}
Output:
Enter n: 5
1*2*3*4*5* is 120

While loop even count

my problem is the following. If I input number 2, the code counts it as an odd number.
Remainder for 2 / 2 = 0 so the error doesn't make sense.
Below is the program:
import java.util.Scanner;
public class Ohjelma {
public static void main(String[] args) {
// Tänne voit kirjoittaa ohjelmakoodia. Ohjelmasi voit ajaa
// valitsemalla menusta Run->Run File tai painamalla Shift+F6
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int number = Integer.parseInt(reader.nextLine());
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
while (number != -1) {
System.out.println("Type numbers: ");
sum = sum + number;
number = Integer.parseInt(reader.nextLine());
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + many);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
The main problem is that for the critical part of your program it largely ignores the first input, apart from adding it to the running sum. You want to recast it like this:
Scanner reader = new Scanner(System.in);
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
do {
System.out.println("Type numbers: ");
number = Integer.parseInt(reader.nextLine());
if (number == -1)
break;
sum = sum + number;
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
} while (true);
This will certainly processes even and odd numbers correctly.
Your code reads the second line of input into number before it checks whether number is odd ... and -1 is odd.

Categories

Resources