Sum and Averages of an Array - java

I am working on an array problem for my college course and I'm trying to find the sum and the average of an array. Here's the code I have so far.
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
//declare the array values
weeks[0]= 2;
weeks[1]= 4;
weeks[2]= 8;
weeks[3]= 10;
weeks[4]= 14;
weeks[5]= 16;
weeks[6]= 20;
weeks[7]= 22;
weeks[8]= 24;
weeks[9]= 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
I know that the average works but I'm stuck on the sum. The problem I'm having is I cant seem to initialize the values in the array so that I can provide a sum for them. What am I doing wrong or what am I missing?

You have two problems in your code;
A) For-loop assignment
You don't need to make the first assignment, just adding sum to the week[index] is ok;
for (int index = 0; index < weeks.length; index++)
sum = sum + weeks[index];
B) Calculating the average
Sum is defined as an int which is a primitive integer, because of that, the division of an integer to an integer, the output is an integer which is not precise. Output of the division (45/10) is casted to integer, then assigned to double which is rounded off to 4, then casted to double again, and '4.0' became the result.
To avoid this unprecise result, cast sum to the double as below;
average = (double)sum / weeks.length;
The corrected version of your code is as below;
Demo
public class Module55 {
public static void main(String args[]) {
// declare the array to have 10 items for 10 weeks
// also declare sum as an int and average as a double to accommodate for
// decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
// declare the array values
weeks[0] = 2;
weeks[1] = 4;
weeks[2] = 8;
weeks[3] = 10;
weeks[4] = 14;
weeks[5] = 16;
weeks[6] = 20;
weeks[7] = 22;
weeks[8] = 24;
weeks[9] = 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++)
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = (double)sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
Output
The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6
And a note for scope
And one last note about the scope, check out this code;
for (int index = 0; index < weeks.length; index++)
weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
In the for-loop, because that no brackets are used, only the first statement under the for-loop will be considered in the scope of the loop by the compiler. That's why, for the next line, the compiler is giving error about the index because index is defined inside the scope of the for-loop.

you need to use brackets in your for loop. currently your code is evaluating like this:
for (int index = 0; index < weeks.length; index++)
{
weeks[index] = index;
}
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
you want your code to evaluate like this
for (int index = 0; index < weeks.length; index++)
{
weeks[index] = index; //logical issue, what does this line achieve?
sum = sum + weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);
This will at least solve your procedural problems but you will still need to take a look at your logic. Try using breakpoints to debug your code.

A very simple way to achieve this in Java 8 is to use the built in mechanisms for gathering statistics:
int[] weeks = {3, 4, 6, 9, 10};
IntSummaryStatistics stats = IntStream.of(weeks).summaryStatistics();
System.out.println("sum = " + stats.getSum() + "; average = " + stats.getAverage());

for (int i = 0;i < weeks.length) {
sum += weeks[i];
}
System.out.println("Sum is:" + sum);

First of all, you simply don't need the line weeks[index] = index;.
And for average you have to cast the sum to double if you want to get the average in double as you have declared the sum as int.
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = {2,4,8,10,14,16,20,22,24,26};
int sum = 0;
double average = 0;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++)
//weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = (double)sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6

Summing an array of numbers and dividing by n to get the average like this will not get the correct value - you should not compute the average using integer division.
Also, this approach might work for the example shown, but not in general. For example, try using this code to find the average of these two value: (INT_MAX-6) and (INT_MAX-2).

The corrected code. While calculating average you have cast on of the varibale to double else you will get the average as integer
public class Mod55 {
public static void main(String args[]) {
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
int sum = 0;
double average = 0;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) {
sum += weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0) {
average = (double)sum / weeks.length;
} else {
average = 0;
}
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
Java8 You could achieve the same thing like this.
int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
int sum = Arrays.stream(weeks)
.sum();
double average = Arrays.stream(weeks).average().orElse(0);

you can find this handy with lambdas.The code looks something like this.
int weeks[] = {1,2,3,4};
List<Integer> asd = IntStream.of(weeks).boxed().collect(Collectors.toList());
//asd.forEach(System.out::println);
//this outputs average
System.out.println(asd.stream().mapToDouble(val -> val).sum()/asd.size());
//this outputs sum
System.out.println(asd.stream().mapToInt(val -> val).sum());
//another way to achieve this thanks to commenter
System.out.println(IntStream.of(asd).summaryStatistics());

Related

Finding the minimum sum and maximum sum of a list of integers in an array

I am currently working on a HackerRank practice question and I only pass 5 test cases and I have no idea why. I've thought of all edge cases that I can think of myself but I fail most test cases.
Problem:
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
Example -
The minimum sum is 1 + 3 + 5 + 7 = 16 and the maximum sum is 3 + 5 + 7 + 9 = 24. The function prints
16 24
This is my solution so far:
public static void miniMaxSum(List<Integer> arr) {
// Write your code here
Collections.sort(arr);
int max = 0;
int min = 0;
int sum = 0;
int smallest = arr.get(0);
int largest = arr.get(4);
for (int i=0; i<arr.size(); i++) {
sum += arr.get(i);
}
min = sum - largest;
max = sum - smallest;
System.out.print(min+ " " + max);
}
I have no idea what test cases I'm failing since it doesn't tell me. I've tried arrays with duplicates, massive numbers, unsorted, and it all gives me expected answer. Please help!
Use long datatype because there is possibility of Integer overflowing or use 16 bit Integer.
public static void miniMaxSum(List<Integer> arr) {
// Write your code here
Collections.sort(arr);
long max = 0;
long min = 0;
long sum = 0;
long smallest = arr.get(0);
long largest = arr.get(4);
for (int i=0; i<arr.size(); i++) {
sum += arr.get(i);
}
min = sum - largest;
max = sum - smallest;
System.out.print(min+ " " + max);
}
}

bad operand types for binary operator '<=' , '+='

I don't understand why my binary operands are not working for if statements. For example I get the error, bad operand types for binary operator '<='. First type: double[] Second type: double for if(prices <=5.00)
public class Prices2
{
public static void main (String[] args)
{
double[] prices = {2.45, 7.85, 1.35, 1.55, 4.05, 9.55, 4.55, 1.45, 7.85, 1.25, 5.55, 10.95, 8.55,
2.85, 11.05, 1.95, 5.05, 8.15, 10.55, 1.05};
double average;
double total = 0.0;
int i;
for (i = 0; i < 20; i++)
{
total += prices;
}
System.out.println("Sum of all prices: "+total+"\n" );
for (i = 0; i < 20; i++)
{
if (prices <= 5.00){
System.out.println(prices + " is less than $5.00");
}
}
average = total / (20);
System.out.println("\nThe average price is " + average + "\n");
for (i = 0; i < 20; i++)
{
if (prices >= average) {
System.out.println( " Values above average: " + prices);
}
}
}
}
Since prices is an array (double[]) and 5.00 is a single double, it makes no sense to check if "prices <= 5.00". It would be like saying "If [1.2, 3.4, 5.7, 6.2, 3.4] < 5.00". So the compiler complains with that verbiage.
Updated 3/18 per follow-up question:
The short answer is to replace the prices variable with the prices[i] variable to match the iteration that checks each spot since this appears to be the goal of the computation. Also, you don't need to declare "i" at the top level. You can do that per for-loop so one loop doesn't accidentally affect another loop.
public class Prices {
public static void main(String[] args) {
// Set up a list of TEST prices to check for various conditions
double[] prices = { 2.45, 7.85, 1.35, 1.55, 4.05, 9.55, 4.55, 1.45, 7.85, 1.25, 5.55, 10.95, 8.55,
2.85, 11.05, 1.95, 5.05, 8.15, 10.55, 1.05 };
int numberOfPrices = prices.length;
// GOAL: Calculate Sum of all numbers
// For each price (i=0, 1, 2... 19), add THAT price to the current value of total
double total = 0.0;
for (int i = 0; i < numberOfPrices; i++) {
total += prices[i];
}
System.out.println("Sum of all prices: " + total + "\n");
// GOAL: Check for for those less than 5
// For each price (i=0, 1, 2... 19), see if THAT price is less than 5.00
for (int i = 0; i < numberOfPrices; i++) {
if (prices[i] <= 5.00) {
System.out.println(prices[i] + " is less than $5.00");
}
}
// Calculate the average price (without hard-coding)
double average;
// average = total / (20);
average = total / numberOfPrices;
System.out.println("\nThe average price is " + average + "\n");
// GOAL: Check for Above Average numbers
// For each price (i=0, 1, 2... 19), see if THAT price is above the average we computed before
for (int i = 0; i < numberOfPrices; i++) {
if (prices[i] >= average) {
System.out.println(" Values above average: " + prices[i]);
}
}
}
}
prices is an array. How can Java tell what you mean by asking if 20 different doubles are less than 9? Are they all less than 9? Are they less than 9 combined? Are any of them individually less than 9?
It's not a good comparison. Your operands are bad.
You probably meant to write prices[i] instead of prices in most places

How to calculate the percentage of numbers that are greater than average.?

public static void main(String[] args) {
int avg=0,sum=0,percentage=0;
Scanner input = new Scanner(System.in);
int[]arr=new int [6];
System.out.println("Enter all the elements: ");
for(int i=0; i<6; i++)
{
arr[i]=input.nextInt();
sum+=arr[i];
avg=sum/6;
}
System.out.println("Average is: "+avg);
for(int i=0;i<arr.length;i++)
{
if(arr[i]>avg)
{
percentage=(arr[i]*100/6);
}
}
System.out.println("Percentage is: "+percentage+"%");
}
For example, if 3 of the elements of the array are greater than average, percentage is 3*100/6=50%
Your calculations are wrong at the bottom part.
for(int i=0;i<arr.length;i++){
if(arr[i]>avg)
{
percentage=(arr[i]*100/6);
}
}
here, the correct calculation would be
for(int i=0;i<arr.length;i++){
if(arr[i]>avg)
{
percentage += (100/6);
}
}
you have to add the count the number of times arr[i] is greater than average and multiply the count with 100/6. The above code does exactly that.
NB: The percentage variable should be a floating point number not an integer
First, to compute the global average, do it at the end, using the array length tobe more generic
double sum=0;
for(int i=0; i<6; i++){
arr[i] = input.nextInt();
sum += arr[i];
}
avg = sum/input.length;
System.out.println("Average is: "+avg);
Then to compute the part that are the greater than the average, find how many values are greater then divide by the total number :
double greaterAvg = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]>avg){
greaterAvg++;
}
}
double percentage = 100 * greaterAvg / input.length
System.out.println("Percentage is: "+percentage+"%");
I used double type to remove int division problem : Int division: Why is the result of 1/3 == 0?
To calculate the percentage of elements having a value greater than
average. first, you have to find the count of those elements and then divide it
with the total number of elements
Try this:
public static void main(String[] args) {
int avg=0,sum=0,percentage=0;
Scanner input = new Scanner(System.in);
int[]arr=new int [6];
System.out.println("Enter all the elements: ");
for(int i=0; i<6; i++)
{
arr[i]=input.nextInt();
sum+=arr[i];
avg=sum/6;
}
System.out.println("Average is: "+avg);
int count = 0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]>avg)
{
count=count+1;
}
}
System.out.println(count);
percentage = (count*100)/6;
System.out.println("Percentage is: "+percentage+"%");
}
Output:
Enter all the elements:
1 2 3 4 5 6
Average is: 3
3
Percentage is: 50%
You need to find the total number of values that are greater than the average. Then you take that total number and divide it by the max, then multiple by 100 to return the percentage. For example, if we use 6, 5, 4, 3, 2, 1; The average is 3. The total number greater than 3 is 3 (6, 5, 4). We then take 3 (total) and divide it by max (6) to get .5 then multiply by 100 to get 50 (50%).
array = 6, 5, 4, 3, 2, 1
average = 3
max = 6
percentage = average / max * 100
public static void main(String[] args) {
int avg=0,sum=0,percentage=0;
Scanner input = new Scanner(System.in);
int[]arr=new int [6];
System.out.println("Enter all the elements: ");
for(int i=0; i<6; i++)
{
arr[i]=input.nextInt();
sum+=arr[i];
avg=sum/6;
}
System.out.println("Average is: "+avg);
int greaterThan = 0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]>avg) {
greaterThan++;
}
}
percentage = (int) (((double) greaterThan / (double) arr.length) * 100D);
System.out.println("Percentage is: "+percentage+"%");
}
You can use a counter variable initialized to zero to count the elements first, then you can simply count the percentage using COUNTER * 100 / (number of elements)
You're calculating the avg in the loop, that's not efficient as the value get crushed at each iteration. It's better to keep only the sum in the loop and calculated the avg after the first loop.
This being said, there are only two main (functional) issues in your code:
The first one is the percentage processing in the loop - you're missing the "+=" and should not use arr[i] value.
The second one is the accuracy of the percentage, should be double (e.g) instead of int (same for the average - if really needed).
To sum up :
Declare percentage as double : double percentage = 0;
Replace percentage=(arr[i]*100/6); => percentage += (100.0/6);
[Optional] Truncate/round the percentage for display: e.g. System.out.printf("Percentage is: (%.2f) %%", percentage);
Cheers!

count the odd numbers in a specified range

How do I a get the counter to count the odd number under 100 in this program?
public class checkpassfail {
public static void main(String[] args) {
int sum =0;
double avr;
int lower = 1;
int uper = 100;
int num=lower;
int counter =0;
while( num <= uper){
sum= sum+(num+=3);
counter+=3;
}
System.out.println("the sum of these nubers is\t" +sum);
System.out.println(counter);
double s =(double)sum;
avr =s/counter;
System.out.println("the average of these nubers is \t"+avr);
}
What do you actually want to do?
If I'm not wrong you want to find odd numbers in between lower_bound and upper_bound.
int lower_bound = 0, upper_bound = 10;
ArrayList<Integer> odds = new ArrayList<Integer>();
while(lower_bound < upper_bound)
{
if(lower_bound % 2 == 1)
odds.add(lower_bound);
lower_bound++;
}
// Number of odd numbers found
int numberOfOddsFound = odds.size();
Welcome to StackOverflow :)
Using the for-loop, you calculate these aggregated values with:
final int lower = 1; // Lower bound
final int upper = 100; // Upper bound
int sum = 0; // Default sum
int count = 0; // Default count
double average = Double.NaN; // Default average
int i = lower; // Init the "runnig" variable
while (i <= upper){ // Until the upper bound is reached, do:
sum += i; // Add the number to the overall sum
count++; // One more number has been used - count it
i += 2; // Add 2 since you mind odd values only
}
average = sum / count; // Calculate the average
// And enjoy the results below
System.out.println("Count: " + count);
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
There also other ways of using the formulas to calculate these characteristics of a regular sequence of numbers or with Stream-API using IntStream.range(..) which allows calculating the aggregation values directly. However, in the beginning, stick with the for-loop.
You don't have to do all of this I guess. If you already know the highest value and the lowest value, and you want to count how many odd numbers between that range, you can code it like below.
int odd_count = (upper + 1) / 2 - lower / 2;
public class checkpassfail {
public static void main(String[] args) {
int lower = 1;
int upper = 100;
int odd_count = (upper + 1) / 2 - lower / 2;
System.out.println("Odd numbers count = "odd_count);
}
}
This will print Odd numbers count = 50.

Average of an array showing 1

I have a program where the user inputs marks into the array and then gets the average value
This is using Jcreator
My problem is that when I ask for the average on my program,it says that the average is 1
This is my code :
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int averageEnglish = english.length / 10;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
English is an int array
int[] english = new int [10];
averageEnglish is a variable
int averageEnglish;
10/10 equals 1. pretty normal.
what you need to do is get the sum of all elements, and divide them by the length of the array.
also: the IDE you use is not really relevant
english.length/10 is not the average value of the array, its simply the length (10) of the array divided by 10, which is 1. You need to sum up all values of the array and divide the sum by the length of the array.
Often you want to present the result not only as an integer but with a few decimals, store the sum and average result in a double.
double sum = 0;
for (int i = 0; i < english.length; i++) {
sum += english[i];
}
double average = sum / english.length;
You are dividing the array's length by the constant 10 (which just happens to be the length), so naturally you'd get 1. You should sum all values of the array and only then divide them by its length:
double englighSum = 0;
for (int i = 0; i < english.length; ++i)
englishSum += english[i];
}
double englishAverage = englishSum / english.length;
If you want user to fill the array, you need to use Scanner object.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of grades: ");
int n = scanner.nextInt();
double[] english = new double[n];
for(int i=0; i<n; i++)
{
System.out.println("Please enter the grade for grade " + (i+1) + ":");
english[i] = scanner.nextDouble();
}
scanner.close();
Than you may use Markus Johnsson's code to proceed.
You anticipated the size of the array and assumed it is always 10 which is the first mistake, then you did your division based on the number of array elements not their sum:
int[] english = new int[10];
/* Now we assume you did some stuff here to fill the array. */
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int noOfElements = english.length; // The divisor
int sum = 0; // The dividend
for (int i = 0; i < noOfElements; i++)
{
sum += english[i];
}
// Here is your Average (Should be of type double since there will be floating points)
double averageEnglish = sum / noOfElements;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
The value of english.lenght is always 10. As in this example:
int[] english = new int [10];
It doesn't matter what data the english array holds, its lenght is always 10.
In order to do the proper calculation use the data, not the lenght of the array.

Categories