Home > OS >  How can I make my function only accept odd numbers into my array, and reject even numbers? C
How can I make my function only accept odd numbers into my array, and reject even numbers? C

Time:12-07

Let me preface this by saying I am fairly new to functions and arrays. I have to make 3 functions: Function1 will be user input, Function2 will determine even/odd numbers, and Function3 will display the contents. I have Function1 and Function3 complete, and will post below, but I'm having a difficult time with Function2. What I have now will give the user an error message if they enter an even number, but it's messed up, and I just can't seem to figure out.

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;
 
void getUsrInput(int num[], int size) //function for user input (function 1 of 3)
{
    int n;

    for (int i = 0; i < size; i  )
    {
        cout << "Enter five odd numbers: ";
        cin >> n; 

        num[i] = n;

        if (num[i] % 2 != 0) //if the number is odd then store it, if it is even: //function for even or odd (function 2 of 3 *doesn't work)
        {
            i  ;
        }
        else
        {
            cout << "Invalid input. Please only enter odd numbers!" << endl; //let the user know to enter only odd numbers. 
        }
    }
}

int main() 
{   
    const int size = 5; //array size is 5 numbers
    int num[size]; 

    getUsrInput(num, size);

    cout << "D I S P L A Y - PART C/B" << endl;
    cout << "========================" << endl;

    for (int i = 0; i < size; i  )
    {       
        cout << num[i] << endl; //function for display (function 3 of 3)
    }
}

CodePudding user response:

for (int i = 0; i < size; i  )

increments i each time through the loop.

if (num[i] % 2 != 0) {
    i  ;
}

increments i each time the number is odd. So each time the user inputs an odd number, i gets incremented twice. Change the loop control to

for (int i = 0; i < size; }

so that i only gets incremented on valid input.

CodePudding user response:

It' perfect for a while loop and you only count up if the insert is ok:

void getUsrInput(int num[], int size) //function for user input (function 1 of 3)
{
    int n, i=0;

    while( i < size )
    {
        cout << "Enter five odd numbers: ";
        cin >> n;

        if (n % 2 == 0) 
            cout << "Invalid input. Please only enter odd numbers!" << endl; 
        else 
            num[i  ] = n;   // ok then store and count up        
    }
}
  •  Tags:  
  • c
  • Related