So I want to print even numbers in reverse from an integer that the user inputs. However, the first number that gets outputted is strange and I cannot understand why that number is getting outputted. This is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
int main ()
{
int N=0, i;
cout << "Enter N (an integer): " << endl;
cin >> N;
cout << "All even numbers " << N << "..0 = " << i;
for (i= N; i>=0; i--) {
if(i%2==0) {
cout << i << " "; //Works but prints weird first number
}
}
return 0;
}
OUTPUT- for example 18 is integer entered:
All even numbers 18..0 = 3276618 16 14 12 10 8 6 4 2 0
Some formatting & indentation would not hurt either
Before i is used in the for loop it is uninitialized, when you use in the std::cout statement before the for loop. You are getting whatever value is in i at the time. 0 (zero) with your compiler setup.
You can initialize i as part of the for loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
int main()
{
int N { };
std::cout << "Enter N (an integer): ";
std::cin >> N;
std::cout << "All even numbers " << N << "..0 = ";
for (int i { N }; i >= 0; --i)
{
if (i % 2 == 0)
{
std::cout << i << ' ';
}
}
std::cout << '\n';
}
Enter N (an integer): 15
All even numbers 15..0 = 14 12 10 8 6 4 2 0
Another way to decrement values using an incrementing loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
int main()
{
int N { };
std::cout << "Enter N (an integer): ";
std::cin >> N;
std::cout << "All even numbers " << N << "..0 = ";
for (int i { }; i <= N; ++i)
{
if ((N - i) % 2 == 0)
{
std::cout << N - i << ' ';
}
}
std::cout << '\n';
}
Enter N (an integer): 15
All even numbers 15..0 = 14 12 10 8 6 4 2 0
#include <iostream>
int main() {
int N { };
std::cout << "Enter N (a positive integer > 1): ";
std::cin >> N;
if (N < 2)
return (std::cout << "Invalid integer\n"), 1;
std::cout << "All even numbers " << N << "..0 = ";
for (int i {N - (N % 2)}; i >= 0; i -= 2)
std::cout << i << ' ';
std::cout << '\n';
}