I think you mean that the user enters some arbitrary number and the program has to print all even numbers starting from the nearest to entered number even number descending to zero.
#include <iostream>
usingnamespace std;
int main(){
int start = 100;
for (int i=start; i--;){
if (i != 0){
if (i % 2 == 0){
cout << i << " is even" << endl;
}
}
}
}
#include <iostream>
usingnamespace std;
int main(){
int start = 100;
start += 1;
for (int i=start; i--;){
if (i != 0){
if (i % 2 == 0){
cout << i << " is even" << endl;
}
}
}
}
@metulburr: your code is fine and would serve the purpose of the needed function. There are several ways to implement loops and vlad from moscow just prefers usng the do-while. I would prefer using just the while.
The line (in vlad from moscow's code)
if ( !n ) break;
is unnecessary; the do-while code is enough.
not unless, entering 0 is designed to get out of the program.
Also,
the line if ( n &1 == 0 ) doesn't work, should have been if ( n%2 == 0 ).
Why was start declared as int? Does your program process negative numbers correctly? The outpput of the program does not look good because every even number is followed by text "is even" in new line.
Moreover your program has a bug. If for example the user will enter number 101 you will display that number 102 is even. It is already your second attempt that you can not write the code correctly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main(){
int start;
cout << "Enter Starting number: ";
cin >> start;
for (int i=start+1; i>0; i--){
if (i % 2 == 0){
cout << i << " is even" << endl;
}
}
}
> Does your (metulburr's) program process negative numbers correctly?
Yes, it does.
¿what about yours?
(referring to http://www.cplusplus.com/forum/beginner/106592/#msg577348 )
> Why the check of i is inside the loop body and not in the for statement itself?
It does check for `i' in the condition of the loop. The if is superfluous.
It considers all numbers as non-negative. So logically it is correct.
[quote]@ne555
It does check for `i' in the condition of the loop. The if is superfluous/quote]
1 2
for (int i=start; i--;){
if (i != 0){
The check if (i != 0){ is outside the for statement. It is not clear why it is placed outside the for statement and executed as many times as the loop itself. This only confuses the reader. He has to understand why such strange constrauction was selected instead of a simple loop.
The program needs to print even numbers in descending order. If you would consider negative numbers, the beginning and the end must be defined as it moves to the left of the number line and it would do so indefinitely. It is not clear what wardah wants. Your codes are both correct (yes, that was a typo which I ddn't recognize immediately) as far as considering positive even numbers are concerned.