How to Display numbers, in specified numbers only

How to make a Program to display even numbers, in User inputted numbers.
Example:
User inputted 3-20 (my program need to identify the even numbers in 3-20 and display it to the user)

OUTPUT:
User Input: 3-20
Even Numbers: 4 6 8 10 12 14 16 18 20

Is there anyone can help me? I don't see anything that can help me with this. Thank you.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>

int main()
{
    int from ;
    int to ;
    std::cin >> from >> to ;

    // what does from + from%2 yield?
    // why is the increment ( n += 2 ) in steps of two?
    for( int n = from + from%2 ; n <= to ; n += 2 ) std::cout << n << ' ' ;
    std::cout << '\n' ;
}
Thanksss :) can you explain how this happen?
I think this is an easier/more basic way to look at it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>

using namespace std;

int main()
{
	int minimum;
	int maximum;
	cout << "Please enter the minimum:";
	cin >> minimum;
	cout << "Please enter the maximum:";
	cin >> maximum;

	//Since we will count from minimum up to maximum, let's first find the closest even number to minimum
	if ((minimum % 2) != 0) //Given any number: x    - if (x%2) is not equal to 0, then x is not even. Since x is odd, we will increase x by 1 to make it even
	{
		minimum += 1; //make minimum the lowest closest even number in the range
	}


	for (int i = minimum; i <= maximum; i+=2) //for each even number from the minimum to the maximum
	{
		cout << i << " "; //print out this even number
	}
	cout << endl;
	system("pause");
}
no offense, it's pretty simple... try to study JL's codes...
Nobody said it was complicated. This is just easier to visualize for the noobs. They're essentially doing the same thing.
> This is just easier to visualize for the noobs

Yes. Particularly because of the comments in the code.

Parenthetically, it also fixes an error in my original code: from%2 would be -1 if from is an odd negative integer.
Topic archived. No new replies allowed.