Reputation: 1103
public class SumAndAverage {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
int num;
for(num = 0; num <= 100; num++){
sum += num;
}
double average = ((double)sum) / num;
System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
}
}
RESULT:
The sum is 5050 The average is 50.0
What's wrong:
5050 / 100 = 50.5 NOT 50.0
Upvotes: 1
Views: 177
Reputation: 3613
Variable num will be 101 when it comes out of loop. So you need to manually subtract one or below can do the same job better with one iteration less
for(num = 0; num < 100; ){
sum += ++num;
}
Full Program
public class SumAndAverage {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
int num;
for(num = 0; num < 100; ){
sum += ++num;
}
double average = ((double)sum) / num;
System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
}
}
Check it.
Upvotes: 0
Reputation: 22241
You got it wrong. That's what happens when you don't use variables as loop checks (and when you use magic numbers anti-pattern in general)- and reuse those later. That way you are certain what value you will actually use.
public class SumAndAverage {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
int num;
int max = 100;
for(num = 0; num <= max; num++){
sum += num;
}
double average = ((double)sum) / max;
System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
}
}
Your num was equal to 101, not 100...
Upvotes: 0
Reputation: 382150
When this loop finishes
for(num = 0; num <= 100; num++){
num
is 101
, not 100
. Because what happens is that the condition is tested until it's false, and this happens when num>100
.
Upvotes: 6