Extracting even and odd numbers using WHILE LOOP.

Hello, Please help me with my code.
I want the user to input 2 numbers.
Then the program will extract the even numbers between these two numbers.
And extract the odd numbers as well.

For Example:-
if the user put 1 and 4
Even numbers: 2 4
Odd numbers: 1 3

Using ((ONLY)) while loop and if condition!

Thanks in advance.

What's wrong with my code?!

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;

int main()

{ 

	int num1;
	int num2;
	int n;

	n = 0;
	



	    cout << "Please enter 2 numbers and I will tell you the range between them.\n";   
		cout << "Enter the first number \n";
	    cin >> num1;
	    cout << "Enter the second number \n";
		cin >> num2;


		while (num1<=n && num2>=n)

	{ 

		if ((n % 2) == 0)
			cout << "The even numbers are " << n;
			

		     

		
			if ((n % 2) != 0)
				cout << "The odd numbers are " << n;



			n++;
		}










	return 0;
}
Line 24: Your loop is never going to execute. You initialize n to 0. Unless the user enters a negative number, num1 <= 0 will return false.



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
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

int main()
{
    int first_number ;
    std::cout << "first number? " ;
    std::cin >> first_number ;

    int last_number ;
    std::cout << "last number? " ;
    std::cin >> last_number ;

    int first_odd_number ;
    if( first_number%2 == 1 ) first_odd_number = first_number ;
    else first_odd_number = first_number+1 ;

    int first_even_number ;
    if( first_odd_number == first_number ) first_even_number = first_number+1 ;
    else first_even_number = first_number ;

    // print out the even numbers
    std::cout << "\neven numbers are: " ;
    int number = first_even_number ;
    while( number <= last_number )
    {
        std::cout << number << ' ' ;
        number += 2 ; // get to the next even number
    }
    std::cout << '\n' ;

    // print out the odd numbers
    std::cout << "\nodd numbers are: " ;
    number = first_odd_number ;
    while( number <= last_number )
    {
        std::cout << number << ' ' ;
        number += 2 ; // get to the next odd number
    }
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/83b26fa7e1c2ba6d
Thank you so much.
How about if I want to find the sum and average of the even numbers?
And finding the sum and average of the odd numbers as well..?

Thanks again!
> How about if I want to find the sum and average of the even numbers?
> And finding the sum and average of the odd numbers as well..?

You would be able to do that (quite easily) on your own; c'mon, make a genuine attempt.
Topic archived. No new replies allowed.