Hey there, I am new to java and am having a hard time. I was wondering if someone could show me in Java how to write a code using While loops to have the user -imput 2 numbers, -output the odd numbers inbetween the two numbers entered -output sum of the even numbers inbetween the two numbers entered, and -output the sqaures of the odd numbers inbetween the two numbers inputted. It%26#039;s just to see how its done and learn. Thank you!!!
While loops asking to find odd numbers inbetween to display and output sum of even numbers?
Well, I think that this is too specific to be a real world question and it looks more like a class assignment. However, I will tell you what you need to know:
In order to check if a number is odd or even, use the modulo of 2, eg:
boolean bOdd = nCurent%2;
Also, I would probably use a for loop rather than a while loop, since you already have the numbers, eg:
for(int nIterator = nFirstParam; nIterator %26lt;= nSecondParam;nIterator++){
// build up variables here
}
// output variables here
I hope that helps you out and isn%26#039;t too much of a cheat.
(By the way, I haven%26#039;t tested this out, so you%26#039;ll need to do the legwork.)
Reply:int notDone=0;//to start the loop
//used below as example
int x = 3;//get from user
int y = 10;//get from user
while (notDone==0)
{
System.out.println(%26quot;ODD%26quot;);
for( int temp=x; temp %26lt;=y ; temp++)
{
if((temp%2)==1)//using Mod (leftovers)
System.out.println(temp);
}//for
System.out.println(%26quot;Sum the EVEN%26quot;);
int temp = 0;
int sum = 0;
for( temp = x; temp %26lt;=y ; temp++)//even
{
if((temp%2)==0)//even has no leftovers
sum = sum = temp;//add them up
}//for
System.out.println(%26quot;Sum of Even %26quot; + sum);
Now do the squares
notDone = 1;//stops the loop
}//while
System.out.println(%26quot;ALL DONE%26quot;);
Reply:That%26#039;s funny, my teacher asked me to do the same thing today!
skin rash
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment