tjamnz
Thread Starter
- Joined
- Jun 15, 2004
- Messages
- 775
Hello... I'm trying to count the total of all even numbers between the given range in Java.
I'm using a for loop, but am not getting the desired output.
// Code here
import java.util.Scanner;
public class SumEveryOtherNum {
public static void main (String[] args){
int num, sum = 0;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a number greater than 1: ");
num = scan.nextInt();
for (int count = 2; count <= num; count+=2){
sum+=count;
if (num < 1)
System.out.println ("Number entered not valid. Try again");
else
System.out.println("All even numbers added =" + (sum));
}
}
}
/*
If i enter the value 10 at the prompt, my output looks like this.
For some reason i figured "sum+=count" would add each number looped, and just output 30.
It prints this output instead:
Enter a number greater than 1:
10
output:
All even numbers added =2
All even numbers added =6
All even numbers added =12
All even numbers added =20
All even numbers added =30
Im trying to count the values, and for the result to only print the value of 30 such as:
All even numbers added = 30
Thanks for any ideas !
*/
I'm using a for loop, but am not getting the desired output.
// Code here
import java.util.Scanner;
public class SumEveryOtherNum {
public static void main (String[] args){
int num, sum = 0;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a number greater than 1: ");
num = scan.nextInt();
for (int count = 2; count <= num; count+=2){
sum+=count;
if (num < 1)
System.out.println ("Number entered not valid. Try again");
else
System.out.println("All even numbers added =" + (sum));
}
}
}
/*
If i enter the value 10 at the prompt, my output looks like this.
For some reason i figured "sum+=count" would add each number looped, and just output 30.
It prints this output instead:
Enter a number greater than 1:
10
output:
All even numbers added =2
All even numbers added =6
All even numbers added =12
All even numbers added =20
All even numbers added =30
Im trying to count the values, and for the result to only print the value of 30 such as:
All even numbers added = 30
Thanks for any ideas !
*/