Solved

use while loop to output the sum of all even numbers

Posted on 2003-10-27
767 Views
i need to prompt the user to input 2 integers: firstNum & secondNum (firstNum must be less than secondNum).
but my main problem is that i got the unexpected output when i try to output the sum of all even numbers between these 2 integers.
Here's my codes:

import java.io.*;
import java.util.*;

public class EvenNumber
{

public static void main(String[] args) throws IOException
{
int firstNum, secondNum, n, sum, rem;

n = 0;
sum = 0;

System.out.flush();

System.out.print("please enter another one that is larger than the first integer: ");
System.out.flush();

rem = firstNum%2;

while(firstNum < (secondNum - 2))
{
if(rem == 0)
{
{
firstNum = firstNum + 2;
n++;
{
sum +=firstNum;
}
}

System.out.print(sum);
}

else
{
{
firstNum = firstNum + (2*n + 1);
n++;
{
sum += firstNum;
}
}

System.out.print(sum);
}
}
}
}

i input 3 and 17, then the output should be 47,
but it outputs "4112372".
thanks
0
Question by:crystalfish0318
• 4

LVL 86

Expert Comment

ID: 9626011

int accumulator = 0;
while (++firstNum < secondNum) {
if (firstNum % 2 != 0)
System.out.println(firstNum);
else {
accumulator += firstNum;
}
}
System.out.println(accumulator);
0

LVL 86

Expert Comment

ID: 9626021
Better with two pairs of curly braces:

int accumulator = 0;
while (++firstNum < secondNum) {
if (firstNum % 2 != 0) {
System.out.println(firstNum);
}
else {
accumulator += firstNum;
}
}
System.out.println(accumulator);
0

Author Comment

ID: 9626109
I input 3 and 17, then the output should be 47
but it shows "70".............
0

LVL 86

Accepted Solution

CEHJ earned 20 total points
ID: 9626150
These are the even numbers between 3 and 17. Their sum is seventy:

3
------------ 4
5
------------ 6
7
------------ 8
9
------------ 10
11
------------ 12
13
------------ 14
15
------------ 16
17
------------  +
------------ 70
0

LVL 86

Expert Comment

ID: 9626184
:-)
0

Featured Post

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…