Home > OS >  Getting odd number between two number
Getting odd number between two number

Time:11-01

The rule is I need to display the odd number between two number that the user inputted.

But my code have problem.

For example when i input: 3 and 11 The output is 5 7 9 11

11 should not be included because that's what the user input even it is odd number. The rule is between. 5 7 9 is my target.

i'm thinking if it's because of my formula or the way i increment it.

First try: i increment numOne before "if"

#include <iostream>

using namespace std;

int main()
{
    int numOne,numTwo;

    cout << "Please Enter First Number : ";
    cin >> numOne;
    cout << "Please Enter Second Number ( Should be greater than first number) : " ;
    cin >> numTwo;

    cout << "Odd Numbers Between are: ";

    while (numOne<numTwo)
    {
          numOne  ;
         if ( numOne % 2 == 1)

            {
                cout<<numOne<<" ";
            }
         
        }


return 0;
}

The output is: 5 7 9 11

-still wrong because 11 should not be include- :(

**Second try: i increment numOne below "if"

#include <iostream>

using namespace std;

int main()
{
    int numOne, numTwo;

    cout << "Please Enter First Number : ";
    cin >> numOne;
    cout << "Please Enter Second Number ( Should be greater than first number) : " ;
    cin >> numTwo;

    cout << "Odd Numbers Between are: ";

    while (numOne<numTwo)
    {
        if  ( numOne % 2 == 1)
        {
            cout<<numOne<<" ";
        }

        numOne  ;
    }

    return 0;
}

The output is: 3 5 7 9

-before 11 is the problem but now it's gone when i incremented below.. But it is still wrong because 3 should not be included also- :(

3 and 11 is the users input.. Even it is odd it should not be included.. Only the odd number "between them". "5 7 9"

CodePudding user response:

If you make sure to start on the first correct number, you can skip the even numbers entirely and worry less about ordering.

int start = (numOne % 2 == 0) ? numOne   1 : numOne   2;
for (int i = start; i < numTwo; i  = 2)
{
    cout << i << ' ';
} 

If you must use while (which is inappropriate for a loop with a fixed incrementation, and you should only do it to satisfy your teacher),

int i = (numOne % 2 == 0) ? numOne   1 : numOne   2;
while (i < numTwo)
{
    cout << i << ' ';
    i  = 2;
} 

or even

if (numOne % 2 == 0)
{
    numOne = numOne   1;
}
else
{
    numOne = numOne   2;
}
while (numOne < numTwo)
{
    cout << i << ' ';
    i  = 2;
} 

CodePudding user response:

Your second attempt works if increment numOne before you start.

numOne  ;

while (numOne < numTwo)
{
    if (numOne % 2 == 1 || numOne % 2 == -1)
    {
        cout << numOne << " ";
    }

    numOne  ;
}

But, you may wish to use a for loop.

for (int i = numOne   1; i < numTwo; i  ) {
    if (i % 2 == 0) continue;

    cout << i << " ";
}
  •  Tags:  
  • c
  • Related