Solved: Java - for loop count range problem

Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

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 ! :D

*/
 

tjamnz

Thread Starter
Joined
Jun 15, 2004
Messages
775
import java.util.Scanner;
public class AnotherTest {


public static void main(String[] args) {

Scanner scan = new Scanner (System.in);

int sum = 0;
int upperLimit;
System.out.println("Enter an integer (Output will add numbers in between 2 and upperLimit): ");
upperLimit = scan.nextInt();

for (int current = 2; current <= upperLimit; current += 2)
sum += current;

System.out.println("Sum of even numbers between 2 and " + upperLimit + " inclusive is: " + sum);
// TODO Auto-generated method stub

}

}

// removed the if else statements from prev version
 
Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 807,865 other people just like you!

Latest posts

Staff online

Members online

Top