Trying to create a program that sums all the odd numbers between 1 and 100 together, displays it, then shows the average. I can't figure out why the loop cuts off early. Super new to this too, so please go easy :p
int sum = 0;
double average;
double lowerbound = 1;
double upperbound = 100;
double number = lowerbound;
double remainder = 1;
//loop
while(number<= upperbound)
if (remainder == 1){
sum += number;
remainder = number%2;
System.out.println(number);
number++;
}else{
number++;
}
average = sum/upperbound;
System.out.println();
System.out.println ("These are your sums and averages");
System.out.println (sum);
System.out.println (average);
}
The main problem is your remainder part. You should calculate it directly:
while(number <= upperbound){
if (number % 2 == 1){
sum += number;
System.out.println(number);
}
number++;
}
What happens with your code is:
remainder starts of as 1. On the first loop number is also 1. So you enter the if case and you calculate the new remainder which is going to be 1%2 = 1. So in the next run you update remainder to be
remainder = 2%2 = 0`. //number = 2
However, since your remainder variable is now set to 0, you will never enter the if case again and therefore never update your remainder. (So the loop doesn't end any earlier, you just skip everthing inside of it)
Also notice that you don't need the else case, since you are increasing number in both the if and the else
You have to check the remainder for every value that you are calculating.
public static void main(String[] args) {
int sum = 0;
double average;
double lowerbound = 1;
double upperbound = 100;
double number = lowerbound;
//double remainder = 1;
//loop
while(number<= upperbound)
if (number%2==1){
sum += number;
//remainder = number%2;
System.out.println(number);
number++;
}else{
number++;
}
average = sum/upperbound;
System.out.println();
System.out.println ("These are your sums and averages");
System.out.println (sum);
System.out.println (average);
}
Related
Here is the entire question:
"Write a program that reads an integer value and prints the average of all odd integers between 0 and the input value, inclusive. Print an error message if the input value is less than 0. Prompt accordingly."
I can't seem to figure out how to get the math to work out in the for loop. I'm having trouble setting it up so that the loop increments in odds. I've tried a million different things and nothing has worked.
public static void main(String[] args) {
int value;
int oddAvg = 0;
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value < 0){
System.out.println("Error: Input should not be less than 0");
System.out.print("Enter an integer greater than 0: ");
value = scan.nextInt();
}
for(){
}
System.out.println("The average of odd integers between 0 and " + value + " is " + oddAvg);
}
}
A trivial approach could be to just iterate from zero to the target number and check whether each number is odd or even:
int sum = 0;
int count = 0;
for (int i = 0; i <= value; i++) {
if (i % 2 != 0) {
sum += i;
count++;
}
}
int avg = sum / count;
But this, of course, is inefficient. A slightly better approach would be to start from the first odd number, 1, and increment it by 2 in each iteration, so you'd be iterating over just the odd numbers:
double sum = 0;
int count = 0;
for (int i = 1; i <= value; i += 2) {
sum += i;
count++;
}
int avg = sum / count;
Or, if you want to really be mathematically sound, you can utilize the fact that the odd natural numbers in a given range are uniformly distributed. Since this distribution is symmetric, the average equals the mean, and you don't need a loop at all:
int start = 1;
int end = value;
if (value % 2 == 0) {
value--;
}
int avg = (end + start) / 2;
General comment:
In this specific case the average would be an int, so I used ints throughout my examples. In the general usecase, you should probably use doubles to avoid mistakes of using integer division.
Here's a solution to your problem!
public static void main(String[] args) {
int input = 25; //this is whatever value you're going up to.
int accumulator = 0; //keep track of the total sum
for (int i = 0; i < input; i++) {
if (i % 2 == 1) { //if odd
accumulator+=i; // add to the running total sum
}
}
System.out.println(accumulator/(input/2)); //print out the total/num of numbers
}
You can try this if interested in Java 8. It is naive approach implementation.
int val = 0;
final OptionalDouble average = IntStream.rangeClosed(0, val)
.filter(n -> n % 2 != 0)
.average();
System.out.println(average);
For class I am writing a program that accepts a stream of positive integers. The program will stop accounting for numbers and compute the average once a negative number is entered into the console.
My issue is, I keep writing while loops that account for the negative entered. How do I stop this? I have tried the following
do{
if (number < 0){
break;
} else if ( number >= 0) {
number = input.nextDouble();
DivideBy++;
sum+=number;
}
}while (number >= 0);
When entering 1.1, 1.9, 3, and -1, the program prints 1.25, when the correct answer is 2.
Here is another example of what I have tried:
do {
number = input.nextDouble();
DivideBy++;
sum+=number;
}while (number >= 0);
Any help is appreciated.
Try this:
Scanner input = new Scanner(System.in);
double number = 0;
double sum = 0;
int divideBy = 0;
double avg = 0;
while(number >= 0) {
System.out.println("Enter number: ");
number = input.nextDouble();
if(number < 0){
break;
}
sum+=number;
divideBy++;
avg = sum/divideBy;
}
System.out.println(avg);
Your if statement should come after the number has been read from the keyboard :]
Try this out, it worked for me:
while(number >= 0){
total = number + total;
} //Your average logic here//
What you are doing now is checking whether the number is negative after you incremented DivideBy and added the number to the sum.
You can easily fix this by undoing what you did after a negative number.
// outside the loop:
sum -= number;
DivideBy--;
Then you will get the correct result.
Or, you can do it like this - check negative first, then add it to sum.
Scanner s = new Scanner(System.in);
int num = s.nextInt();
int count = 0;
int sum = 0;
while (num > 0) {
sum += num;
count++;
num = s.nextInt();
}
System.out.println(sum / count);
Read the number before the if condition. Try this.
do {
number = input.nextDouble();
if (number < 0) {
break;
} else if (number >= 0) {
DivideBy++;
sum += number;
}
} while (number >= 0);
I am moving along in this program just fine, but as I have progressed I have seemingly made some logic errors that are tough to find & need some help. I have methods that sort the array from least to greatest. Whenever I print the smallest number to the screen it always shows that number as 0 even if I haven't typed any zero. I can get the correct highest number, except for when the user enters the max amount of numbers, then it prints the second highest number. Sometimes I get the correct output for the median, but never get the correct output for the average. Any help is greatly appreciated! I feel like I am close to the correct code, but these errors are giving me a tough time.
public static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {
//change to 100 when done testing
final int MAXSIZE = 10;
int[] nums = new int [MAXSIZE];
int usedSize, indexOfNextSmallest = 0;
double median, average;
System.out.println("Please enter each number starting from least to greatest(a negative number will quit input): ");
usedSize = getNums(nums);
for (int index = 0; index < nums.length -1; index++) {
indexOfNextSmallest = getIndexOfSmallest(index, nums);
interchange(index, indexOfNextSmallest, nums);
}
median = medians(nums);
average = averages(nums);
System.out.println("The smallest number entered is " + nums[0] + ".");
System.out.println("The largest number entered is " + nums[nums.length-1] + ".");
System.out.println("The median is: " + median);
System.out.println("The average is: " + average);
}
public static int getIndexOfSmallest(int startIndex, int[] nums) {
int min = nums[startIndex];
int indexOfMin = startIndex;
for (int index = startIndex +1; index < nums.length; index++) {
if (nums[index] < min) {
min = nums[index];
indexOfMin = index;
}
}
return indexOfMin;
}
private static void interchange(int index, int indexOfNextSmallest, int[] nums) {
int temp = nums[index];
nums[index] = nums [indexOfNextSmallest];
nums[indexOfNextSmallest] = temp;
}
public static int getNums(int nums[]) {
int usedSize = 0, userValue = 0;
while(userValue >= 0 && usedSize < nums.length) {
nums[usedSize] = userValue;
userValue = kbd.nextInt();
usedSize++;
}
if(!(userValue >= 0)) {
--usedSize;
System.out.println(usedSize + " numbers entered.");
}
else if(!(usedSize < nums.length)) {
System.out.println("Maximum amount of inputs (" + nums.length + ") reached.");
}
return usedSize;
}
public static double medians(int nums[]) {
double median;
if (nums.length % 2 == 0)
median = ((double)nums[nums.length / 2] + (double)nums[nums.length / 2 - 1]) / 2;
else
median = (double)nums[nums.length / 2];
return median;
}
public static double averages(int nums[]) {
double average;
int sum = 0;
for (int index = 0; index < nums.length; index++){
sum = sum + nums[index];
}
average = ((double)sum / (double)nums.length);
return average;
}
}
This is the output that I am getting if I enter 1, 2, 3, 4, 5, -7(the negative is to stop user input(could that be a problem?))
Please enter each number starting from least to greatest(a negative number will quit input):
1 2 3 4 5 -7
5 numbers entered.
The smallest number entered is 0.
The largest number entered is 5.
The median is: 0.5
The average is: 1.5
The answers I should be getting with correct code is 1, 5, 3.0, & 3.0
Thank you again for any help.
Your medians() and averages() methods look fine. I would recommend that you get rid of the getIndexOfSmallest() and interchange() methods. You only ostensibly need these methods because you are trying to sort. But I believe the sort is instead altering the array. Use the following method to find the minimum value:
public int getMin(int[] nums) {
int min = nums[0];
for (int i=1; i < nums.length; ++i) {
if (nums[i] < min) {
min = nums[i];
}
}
return min;
}
I will leave it as a homework assignment for you to code a method to find the maximum value.
The whole thing goes worng in two places:
The first one
final int MAXSIZE = 10;
int[] nums = new int [MAXSIZE];
This means that even though the program stopped accepting values after a negative value; all the rest of the array is filled with 0s.
To resolve this, you can choose to use ArrrayList instead on int array.
The second issue
The existing code for getnums is
public static int getNums(int nums[]) {
int usedSize = 0, userValue = 0;
while(userValue >= 0 && usedSize < nums.length) {
nums[usedSize] = userValue;
userValue = kbd.nextInt();
usedSize++;
}
if(!(userValue >= 0)) {
--usedSize;
System.out.println(usedSize + " numbers entered.");
}
else if(!(usedSize < nums.length)) {
System.out.println("Maximum amount of inputs (" + nums.length + ") reached.");
}
return usedSize;
}
Here in the while loop, the statements
nums[usedSize] = userValue;
userValue = kbd.nextInt();
will ensure that the value at num[0] will always be zero(as userValue is initialised to 0) and it won't be fetched from user input.
Instead it should be:
while(userValue >= 0 && usedSize < nums.length) {
userValue = kbd.nextInt();
nums[usedSize] = userValue;
usedSize++;
}
If you take care of these two issues; then the rest of the code should work out fine.
This is what I get when I run the program after updating it for the second issue:
Input
Please enter each number starting from least to greatest(a negative number will quit input):
5
8
4
32
-5
Output
The smallest number entered is -5.
The largest number entered is 32.
The median is: 0.0
The average is: 4.4
Which is correct cause the average and median are calculated for 10 numbers and the rest of the numbers (after entering negative number) are just 0
Update as per comments
If you just wish to reject the negative number the you can update the while loop in getnums method as:
while(userValue >= 0 && usedSize < nums.length) {
userValue = kbd.nextInt();
if(userValue >= 0) {
nums[usedSize] = userValue;
usedSize++;
}
}
Also, the if loop after that shouldn't decrease the value of usedSize
if(!(userValue >= 0)) {
System.out.println(usedSize + " numbers entered.");
}
Find Number Equal to the sum of factorial of each of its digits eg:145
From 1 to 200
I tried this :
public static void main(String[] args) {
int i = 0, x = 0, temp, temp1, digit = 0, factorial = 1, sum = 0;
System.out.println("Special Numbers from 1 to 10,000 -:");
for (i = 1; i <= 200; i++) {
temp = i;
temp1 = i;
while (temp > 0) {
digit = temp % 10;
factorial = 1;
for (x = 1; x <= digit; x++) {
factorial *= x;//factorial of digit
}
sum += factorial;//sum of factorial of a all the digits of the number
temp = temp / 10;
}
if (sum == temp1) {
System.out.println(temp1);
}
}
}
So if i put i=145 it works but othervise i get the wrong output.
You forgot to make sum 0, so you only get the correct result for the first number you try. The line sum = 0; should go before while(temp>0){.
Your sum variable is declared outside the for block.
Each time you calculate a factorial sum get added to the previous sum and hence 1! + 4! + 5! will never be 145 in this case.
Try initializing it inside the loop to 0.
You need to initialize sum inside the for loop.
for(i=1;i<=200;i++){
sum = 0; //<--include this
temp = i;
temp1 = i;
while(temp>0){
digit = temp%10;
factorial =1;
for(x = 1;x<=digit;x++){
factorial*=x;//factorial of digit
}
sum+=factorial; //sum of factorial
temp = temp/10;
}
if(sum == temp1){
System.out.println(temp1);
}
}
Is there a more elegant way to write this recursively? Armstrong Numbers
PS: been out of school for 15 years this is not homework, just some code I am trying to convert from iterative to recursively.
import java.util.Scanner;
public class RecArmstrong {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = keyboard.nextInt();
//Error checking
while(number < 0 || number > 100000){
System.out.print("Enter a number: ");
number = keyboard.nextInt();
}
if(arm(number) == number)
System.out.println(number + " is an armstrong number");
else
System.out.println(number + " is not an armstrong number.");
}
public static long arm(long n){
long temp, sum, digits = 0;
long remainder;
temp = n;
sum = 0;
if (temp == 0)
return 0; //base case
else{
while (temp != 0){
digits++; //number of digits for exponent
temp = temp / 10;
}
temp = n; //set temp back to original number
while (temp != 0){
remainder = temp % 10;
sum += Math.pow(remainder, digits);
temp = temp / 10;
}
return sum + arm(temp);
}
}
}
Maybe im mistaken (its 1AM here..), but as far as i can tell your implementation is actually not a recursion at all. With
while (temp != 0){
remainder = temp % 10;
sum += Math.pow(remainder, digits);
temp = temp / 10;
}
you do the whole calculation iteratively, until tmp is 0. Therefore in the next line
return sum + arm(temp);
arm(temp) will always return 0!
I hacked together a quick recursion of my own, which works digit by digit, starting from the last.
The function overload is necessary because every recursive call needs the total length of the original number.
public static long arm(long n){
return arm(n, Integer.toString(n).length());
}
public static long arm(long n, int num_digits){
if(n==0) //recursion finished
return;
// n%10 gives last digit
return java.lang.Math.pow(n%10,num_digits) + arm(n/10, num_digits);
}
I hope you like it ;-)
If you want to do it using java stream, you can do it like this.
public boolean isArmstrongNumber(String number) {
int exponent = number.length();
if (Integer.parseInt(number) == number.chars()
.map(n -> n - '0')
.map(n ->(int) Math.pow(Integer.parseInt("" + n),exponent))
.sum())
return true;
else return false;
}