How to calculate an average of a range? - java

I need assistance for a homework question. The question is as follows: "Compute the sum and average from a range of numbers using a while loop and a do while loop. Display the results of each loop." I already have most of the code finished, I'm just having issues with the average part of it. Here is what I have so far.
import java.util.Scanner;
public class Homework {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
//Get the minimum and maximum values for the range.
System.out.print("Enter the minimum for the range: ");
int number1 = input.nextInt();
System.out.print("Enter the maximum for the range: ");
int number2 = input.nextInt();
int sum = 0;
double average = 0;
while (sum == 0){
//Get the sum
for (int i = number1; i <= number2; i++)
sum = sum + i;
for (int i = number1; i <= number2; i++)
average = sum / i;
System.out.println("(while loop)The sum is " + sum + " and the average is " + average + ".");
}
do {
//reset the sum so it doesn't mess up.
sum = 0;
for (int i = number1; i <= number2; i++)
sum = sum + i;
for (int i = number1; i <= number2; i++)
average = sum / i;
System.out.println("(do-while loop)The sum is " + sum + " and the average is " + average + ".");
} while (sum == 0);
}
}
Now, my main issue is trying to get the average for a range where the minimum isn't 1. It works perfectly fine as long as the minimum value in the range is 1. Is there any way I could get it to work with a minimum value of more than 1.

int sum = 0;
int counter = number1;
while(counter <= number2){
sum += counter;
counter++;
}
System.out.println("Sum:\t" + sum);
System.out.println("Average:\t" + (sum / (number2 - number1 + 1));
//--------------------------------------------------
sum = 0;
counter = number1;
do{
sum += counter;
counter++;
}while(counter <= number2);
System.out.println("Sum:\t" + sum);
System.out.println("Average:\t" + (sum / (number2 - number1 + 1));
The condition of your while loop (sum == 0) made no sense. If you want to iterate over a range, the end of that range should be your condition. Thinking about the relationship between a sum and an average makes it clear you only need to loop once and then divide the result. You could repeat the loops (as you tried to do) if you wish but it's slower and unnecessary.
Cheers!
Edit: I just wanted to add this clarification which I hope will explain things a little further: The way you had written your code, your while / do-while loops would have only run once (just like if you did for (int i = 0; i < 1; i++)) and you were actually doing the looping using the more familiar for loop inside the while loop. However, as another commenter pointed out the purpose of this assignment was probably to get you to see how you can use a while loop instead of using the more intuitive for loop -- and by falling back on to the for loop instead you proved your teacher right a little :)

Related

Finding total sum of loop after finding all powers of 2 below certain number

I'm new to java/programming in general and this is a homework assignment. This is what I have so far: When I run it I get the powers of 2 below the n input. example if n = 50, output is 2 + 4 + 8 + 16 + 32 + = -2
I would like the + after 32 to be gone and I don't know how to properly sum it. I would want the sum to = 62 in this case. I tried using string builder to take off the last two characters but that isn't working for me.
import java.util.Scanner;
public class Powers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n;
System.out.print("Enter the upper limit: ");
n = scan.nextInt();
int sum = 0;
int power = 1;
for (int i = 0; i <= n; i++) {
power = 2 * power;
if (power < n && 0 < power) {
System.out.print(power + " + ");
}
sum = sum + power;
}
System.out.println(" = " + sum);
}
}
There are multiple issues here:
When reaching the upper limit you simply stop doing the output but continue doing the summation.
You use the upper limit as the number of iterations, so in case of 50 in your example, you do a sum of all values between 1 and 2^50, which is the reason why the result is negative, because the sum became larger than the maximum number an int can keep.
Concerning your question how to break a loop, there is break ;-)
Your print is always outputting a + which is why you have the + = in your output. Change the output to something like this:
if (power < n && 0 < power) {
if (i != 0) {
System.out.print(" + ");
}
System.out.print(power);
}
I've added some functionality to your code.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Type number:");
Scanner scanner = new Scanner(System.in);
int n = 0;
while (n == 0) { // to ask again if "n" is zero.
n = scanner.nextInt();
}
if (n != 0) {
scanner.close(); // to prevent resource leak
int sum = 0;
int power = 1;
for (int i = 0; i < n; i++) {
power *= 2;
sum += power;
System.out.print(power + " ");
if (sum + power * 2 < 0 | i == n - 1) {
// Should we step to the next iteration?
// If next "sum" will be bigger than the max value for
// integers
// or if this iteration is the last - it will type "sum",
// break "for" cycle and go the next line of code after
// "for" cycle.
// So in this case System.out.print("+ "); won't be
// executed.
System.out.print("= " + sum);
break;
}
System.out.print("+ ");
}
}
}
}

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

Java loop divisibility sum and average

I have made a loop that produces the sum and average of numbers 1,2,3,...,to an upperbound 100. What I am having trouble with is modifying my current code so it only includes numbers that are multiples of 7. Here is what I have:
public class SumAndAverageForLoop {
public void SumAndAverageForLoop() {
double sum = 0;
for (double i = 1; i <=100; i++) sum+= i;
System.out.println ("the average is " + sum/100);
System.out.println ("the sum is " + sum);
}
}
I am trying to do it without a main method so I had to create a Launcher class.
Any help is appreciated. Thank you in advance.
In order to determine if a number is divisible by 7 you should use the modulo devision operator % and compare the remainder to 0;
int sum = 0;
int count = 0;
for (int i = 0; i <= 100; i++) {
if (i % 7 == 0) {
sum += i;
count++;
}
}
System.out.println("the average is " + sum/count);
System.out.println("the sum is " + sum);
Also I wouldn't recommend using a double when all you need is an int. You might get caught out by precision issues further down the road. You could cast your sum to a double before dividing to by count if you want a decimal average. Like this:
System.out.println("the average is " + ((double) sum)/count);
In Java 8 this is now easily accomplished without writing error prone looping structures as follows:
IntStream.range(0,100).filter(i -> i % 7 == 0).summaryStatistics();
Result:
IntSummaryStatistics{count=15, sum=735, min=0, average=49.000000, max=98}
Your for loop should increment in 7's for each iteration and also you should maintain a count of your iterations because you need it for finding average.
int sum = 0;
int count = 0;
int average = 0;
for(int i=7; i<=100; i=i+7)
{
sum = sum + i;
count= count+1;
average = sum/count;
}
I would use the Modulus operator for this use case.
public class SumAndAverageForLoop {
public void SumAndAverageForLoop() {
double sum = 0;
for (double i = 1; i <=100; i++){
if((i % 7) == 0){
sum+= i;
}
System.out.println ("the average is " + sum/100);
System.out.println ("the sum is " + sum);
}
}

Calculating the average number in a nesting loop Java

does anyone knows how to calculate the average in a loop. Every time I calculated the average I received 0 or 1. I know that I need use average = (sum) / (salary_annually); but I can't get it to work. Thanks in advance.
import java.util.Scanner;
public class midterm
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
int average=0;
int count = 0;
int salary_annually = 0;
for(int employee =1; employee <= 2; employee++)
{
System.out.println("Employee: " + employee);
for(int year=1; year <= 2; year++)
{
System.out.println("Please Enter the Salary for Year: " + year);
salary_annually = kb.nextInt();
sum += salary_annually ;
if (min >= salary_annually)
{
min = salary_annually;
}
if (max <=salary_annually)
{
max = salary_annually;
}
average = (sum) / (salary_annually);
}
System.out.println("The average is " + average);
System.out.println("The higher number " + max);
System.out.println("The the lowest number " + min);
}
}
}
I'm guessing the problem here is that you are using integer division. Since the sum and salary_annually are both integers division works slightly different. There is not remainder because dividing two integers gives an int.
For example 1/2 is not .5 as you might expect but instead it is 0. Any fractional number is dropped when doing integer math. As another example 9/5 is not 1.8 but instead 1.
If you want the average then you can either declare sum or salary_annually as a double and declare the average as a double as well.
Change
average = (sum) / (salary_annually);
To
double average=0;// Declare it as `double` rather than `int`
average = (sum) / 2.0;
average is calculated by: average = sum / count;
you need to increment your count variable, otherwise you will always get and ArithmeticException / by zero
The Average is calculated by average = sum / count where average should be of type double.
You did declare the variable count, but didn't use it.
import java.util.Scanner;
public class Calulate {
/**
* #param args
*/
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
double average = 0;
int count = 2;
int salary_annually = 0;
for (int employee = 1; employee <= 2; employee++) {
System.out.println("Employee: " + employee);
for (int year = 1; year <= count; year++) {
System.out.println("Please Enter the Salary for Year: " + year);
salary_annually = kb.nextInt();
sum += salary_annually;
if (min >= salary_annually) {
min = salary_annually;
}
if (max <= salary_annually) {
max = salary_annually;
}
}
average = sum / count;
System.out.println("The average is " + average);
System.out.println("The higher number " + max);
System.out.println("The the lowest number " + min);
}
}
}

Calculating the average in a Loop Java

I just found that when I calculate the average for the second user, I get a different result. For example, if I add this number for the first user 10,10,10,20,20. I get 14.0 which is correct. But when I enter the same number for the second user I get 28.0? any ideas?
import java.util.Scanner;
public class midterm
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
double average=0;
int count = 0;
int salary_annually = 0;
for(int employee =1; employee <= 2; employee++)
{
System.out.println("Employee: " + employee);
for(int year=1; year <= 5; year++)
{
System.out.println("Please Enter the Salary for Year: " + year);
salary_annually = kb.nextInt();
sum += salary_annually ;
average = (sum) / 5.0;
if (min >= salary_annually)
{
min = salary_annually;
}
if (max <=salary_annually)
{
max = salary_annually;
}
}
System.out.println("The average is " + average);
System.out.println("The higher number " + max);
System.out.println("The the lowest number " + min);
}
}
}
sum = 0; // this before 2nd loop
int max = Integer.MIN_VALUE; // these too.
int min = Integer.MAX_VALUE;
for(int year=1; year <= 5; year++)
{
.
.
.
}
average = (sum) / 5.0; // this after 2nd loop
In your solution you are calculating average 5 times inside the loop! and you only get advantage from the fifth time! must be after the loop. average = (sum) / 5.0; after the loop.
You need to zero sum at the end of the loop. As it is, now it just keeps increasing and increasing as the old value is kept in memory, when coming to the next iteration.

Categories

Resources