![]() |
find out the average of odd numbers -do-while statement.
hi , I want to know if my answer is true??and I want your opinion in my answer..
• Write a program fragment to find out the average of odd numbers between two numbers given by the user using a do-while statement? int sum=0; int X=50; int Y = 70; int count=0; do{ X++; if(X%2!=0) { sum +=X; count++; } } while(X<Y); int average = sum/count; System.out.println("average=" + average ); |
Re: find out the average of odd numbers -do-while statement.
Looks like it would give the correct results, without testing i will say that you may have to change < to <= and possible change the point at which you increment X.
P.S Use [code] tags Chris |
Re: find out the average of odd numbers -do-while statement.
Quote:
|
Re: find out the average of odd numbers -do-while statement.
your code is quite right but the question says given by the user. ending with an odd no is not provided for, so the while statement should read x<=y; so as 2 test d last number, in case its odd.
|
Re: find out the average of odd numbers -do-while statement.
The code as you have written it should work; however, that's based on X and Y being even. If X were odd, the "X++;" line would be bad. If Y were odd, the "X<Y" condition would be bad.
For arbitrary X and Y, you'd either need to modify the rest of the code, or add something like the following near the beginning: :
I'd also add that since consecutive odd numbers are 2 apart, incrementing by 1 then checking if your number is odd or even is kind of wasteful. Something like the following would be better: :
I was going to point out that average may not be an int, but you can prove that the average is (X+Y)/2 (again, X and Y are both even, or both odd, I guess), so it has to be. |
| All times are GMT -5. The time now is 2:14 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC