Tuesday, July 28, 2009

How to add the sum of the even numbers between 2 and an inputed number in java?

Hi im a beginner in java and Im having trouble.


The excersise says:


Design and implement an application that reads an integer value and prints the sum of all even integers between 2 and the input value, inclusive. Print an error message if the input value is less than 2.





How can I get it to add all of the even numbers inbetween?


I made a program to count by two's to the inputed number but it cant add them the way I did it.

How to add the sum of the even numbers between 2 and an inputed number in java?
import java.io.*;





class SumEvens


{


static public void main( String[] argv )


throws Exception


{


System.out.print( "Enter an even number: " );


BufferedReader dis = new BufferedReader( new InputStreamReader(( System.in )));


int n = Integer.parseInt( dis.readLine() );





if (( n % 2 ) != 0 ) {


System.out.println( n + " was not even." );


System.exit( 0 );


}





int sum = 0;


for ( int i = 2; i %26lt;= n; i += 2 ) {


sum += i;


}





System.out.println( "The sum of all even numbers from 2 to " + n + " is " + sum );


}


}
Reply:hey guy,


I don't remember exact java syntax so it's been a while.. but say, you've gotten a number from the user. let's call it n.





I know in C++, you'd do something like:


int k = 0; //k can hold the sum of even //values


for(int i = 0; i %26lt;= n; n++)


{


if (n%2) == 0 //if remainder is zero after


//dividing n by 2, then n is even...


k += n;


}


cout %26lt;%26lt; k %26lt;%26lt; endl;





Hope this helps.

sd cards

No comments:

Post a Comment