displaying odd numbers

can anyone teach me how to output all odd numbers between two integers?
heres what i have so far-

#include <iostream>
using namespace std;
int main ()

{
int num 1;
int num 2;
cout << ("Please enter two numbers in which the first number is smaller than the second");

cout << "Enter first integer: ";
cin >> num1;
cout << "Enter second integer: ";
cin >> num2;
Your code has a mistake i.e. spaces cannot be used in the names of variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

void main()
{

	int num1, num2;

	cout << "Enter first integer: ";
	cin >> num1;
	cout << "Enter second integer: ";
	cin >> num2;

	while(num1 <= num2) {
		/* if the remainder after dividing a number by 2 isn't zero, it means that
		    the number isn't even but odd. % is called remainder or modulus operator */
		if(num1%2 != 0)
			cout << num1 << " is odd." << endl;
		num1++;
	}

	system("pause");
}
Last edited on
hey thanks..i just have a question about that. what is the purpose of putting the increment to num1 at the end?
I have used this condition for loop:

num1 <= num2

Suppose, num1 is given "2" and num2 is given "23".
When loop runs for the first time, "2" is checked.
And after checking "2", num1++; statement increments in the value of num1 which was 2.
So it becomes "3". And that increment statement keeps adding +1 to the value of num1 each time when loop runs.
Loop runs until num1's value doesn't reach num2's value i.e. 23.


I hope it answers your question.
Last edited on
yes it does..thanks a lot
Might be worth looking at too:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main() {
    int a, b;
    cout << "Enter the first interger: ";
    cin >> a;
    cout << "Enter the second integer: ";
    cin >> b;

    cout << "All the odd numbers between " << a << " and " << b << " (inclusive.)\n";
    if( a % 2 == 0 )
        a++;
    while( a <= b ) {
        cout << a << ", ";
        a += 2;
    }

    return 0;
}
Topic archived. No new replies allowed.