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);
}
}
Related
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 :)
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));
I have an assignment where I am supposed to have 6 elements in an integer array and program supposed to find the highest and lowest element in an array and omit those two elements and find the average for the remaining four elements. So far my program is able to find the lowest and highest number in that array and able to omit it, however, I cant seem to save those results from the loop to a variable so I can start to calculate my average. the code is
int bucky[] = { 4, 6, 8, 19, 199, 400 };
int hello = 0;
int max = 0;
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] > max) {
max = bucky[i];
}
}
System.out.println("Max number is " + max);
int min = 0;
int j = 1;
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] < bucky[j]) {
min = bucky[i];
j = i;
}
}
System.out.println("min number is " + min);
System.out.print("{");
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] != max) {
if (bucky[i] != min) {
System.out.print(" " + bucky[i]);
}
}
}
System.out.print("}");
So far it prints out {6 8 19 199}. I want to be able to save them in a variable and calculate the average. Any help would be appreciated.
Here is a simple program that might achieve what you are after.
What should happen if all elements have the same value?
int[] input = {0,1,2,3,4,5};
int max = input[0];
int min = input[0];
int sum = 0;
for(int i : input){
sum += i;
if(i < min){
min = i;
}else if(i > max){
max = i;
}
}
System.out.println("sum for input is : " + sum);
System.out.println("highest value element is : " + max);
System.out.println("lowest value element is : " + min);
System.out.println("sum excluding extreme elements is : " + (sum - min -max));
// have cast the result as a float as i dont know if average should be truncated or not
System.out.println("average excluding extreme elements is : " + ((float)(sum - min -max)/(input.length-2)));
public static void main(String args []){
int bucky [] = new int [] {4, 6, 8, 19, 199, 400};
int max = bucky[0];
int min = bucky[0];
int sum = 0;
for(int i = 0; i<bucky.length; i++){
if(min > bucky[i]){
min = bucky[i];
}
else if(max < bucky[i]){
max = bucky[i];
}
sum += bucky[i];
}
sum -= (min + max);
System.out.println("Max is " + max);
System.out.println("Min is " + min);
System.out.println("Sum is " + sum);
System.out.println("Average is " + sum/(bucky.length-2));
}
Small program can be developed using arrays in Java as follows, which initially stores very first element of the array in min, max, and sum, then start traversing the array from first element and determine min and max value elements by comparing them with the current element pointed by input[i] of the array. Also add input[i] every time to the sum variable to get sum of all elements. After having computed min, max, and sum value elements; compute avg by subtracting min and max from sum and divide the resultant value by length - 2.
class ComputeAvg
{
public static void main (String[] a)
{
int[] input = {10,11,12,13,14,15};
int min, max, sum, avg;
min = max = sum = input[0];
int length = input.length;
for (int i = 1; i < length; i++)
{
if (min > input[i])
min = input[i];
else if (max < input[i])
max = input[i];
sum += input[i];
}
avg = (sum - min - max)/(length - 2);
System.out.println("sum for input is : " + sum);
System.out.println("highest value element is : " + max);
System.out.println("lowest value element is : " + min);
System.out.println("sum excluding min and max value elements is : " + (sum - min - max));
System.out.println("Average after excluding min and max value elements is : " + avg);
}
}
OUTPUT
======
sum for input is : 75
highest value element is : 15
lowest value element is : 10
sum excluding min and max value elements is : 50
Average after excluding min and max value elements is : 12
You're 90% there. You just need a nudge in the right direction.
You already know how to filter your results from highest and lowest with this statement (rewritten to compress nested ifs):
for(int i=0;i<bucky.length; i++){
if(bucky[i] != max && bucky[i] !=min) {
// implementation
}
}
By the way, it can be rewritten as this, thanks to De Morgan's Law. This may read more straightforward for you: "If the value in bucky[i] is neither max nor min..."
for(int i=0;i<bucky.length; i++){
if(!(bucky[i] == max || bucky[i] ==min)) {
// implementation
}
}
That was the hard part. What you now need:
A counter to tell you how many values you actually are adding. Something like adjustedTotal. You'd only ever add to this counter if the number wasn't the min or the max.
A simple sum variable, initialized appropriately, taking the values from bucky[i] such that bucky[i] != max && bucky[i] != min.
int sum=0;
for (int i=0 ;i< arr.length;i++) {
if(arr[i]!=max && arr[i]!=min) {
sum=sum+arr[i];
}
}
int average=sum/(arr.length-2)
You can define an variable named sum like Makoto mentioned above.
In additional, I would like to point out that there is something wrong with your code for calculating min.
Here is an example,
Assume the int[] array is as follows:
int bucky[] = { 6, 4, 8, 19, 400,199 };
Use your code below:
int min = 0;
int j = 1;
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] < bucky[j]) {
min = bucky[i];
j = i;
}
}
System.out.println("min number is " + min);
What will be the value for min ?
It will be 0. It is incorrect.
You can first specify the first element in array as min, and then compare it with remaining values. If any value is smaller than min, then change the value for min.
Here is an example:
int min = bucky[0];
//int j = 1;
for (int i = 1; i < bucky.length; i++) {
if (bucky[i] < min) {
min = bucky[i];
}
}
System.out.println("min number is " + min);
Make some change and move on. :)
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);
}
}
}
This is a question from the book Introduction to Java by Y Daniel Liang:
Convert for loop statement to a while loop and do-while loop?
int sum = 0;
for (int i = 0; i <= 7; i++)
sum = sum + i;
I am pretty confused on how to convert it to a do-while loop. What am I supposed to do? Please see my code below.
public class Convert_forLoop_toWhileLoop {
public static void main(String[] args) {
int sum = 0;
int i = 0;
do {
sum = sum + i;
System.out.println(sum);
i++;
} while(i <= 7);
}
}
Depending on how scrupulous you wanna be, a "more" equivalent do-while-loop of your for-loop example would be:
int sum1(int n) {
int sum = 0;
for (int i = 0; i <= n; i++) {
sum = sum + i;
}
return sum;
}
int sum2(int n) {
int sum = 0;
{
int i = 0;
if (i <= n) {
do {
sum = sum + i;
i++;
} while (i <= n);
}
}
return sum;
}
Note I wrapped your example in sum1 (passing sum1(7) is equivalent to your case).
For those who really want to split hairs -- note Java doesn't necessarily compile the 2 functions above into the same bytecode (at least when I tested it, to my surprise). 2 extra bytecode instructions for sum2 (20 vs. 22). Just something interesting I noticed.
Like this:
int sum = 0;
int i = 0;
do {
sum += i;
i++;
} while (i <= 7);
System.out.println("The sum of 0 thru " +i + " is:" + sum);
Your answer doesnt support the case where i initial value is >= number of loops.
you need to first check the condition.
while (i <= 7) {
sum+=i;
// at the last statement increase i
i++
}
System.out.println(sum);