Hello guys. As the title says, I'm having a difficult time with Arrays. I need to create an array that stores 5 numbers (odd numbers only) If the user enters and even number, display an error message and tell them to enter only odd numbers.
I've done all of this, but everytime I try to display the list, it doesn't work. So i guess my real question is, could someone show me how to display the odd numbers stored into my array? I will post what I have below.
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
int main()
{
int array[5]; //array created for storing odd numbers only.
for (int i = 0; i < 5;)
{
cout << "Please enter 5 odd numbers: "; //user enters 5 odd numbers
cin >> array[i];
if (array[i] % 2 != 0) //if the number is odd then store it, if it is even:
{
i++;
}
else
{
cout << "Invalid input. Please only enter odd numbers!" << endl; //let the user know to enter only odd numbers.
}
}
return 0;
}
In line 15 you read directly into the array before you check it.
On line 22 you print an error message but don't remove it from the array.
You need to read it into a temporary variable and only if it is odd store it.
@AbstractionAnon, thanks for that. I see what I was missing now.
@thmm what do you mean by check it? and I'm new to arrays so i'm not sure how to remove and even number input from the array or any of that. I'm reading some material about arrays and functions currently but I'm literally like a 2 day newbie. But thank you for input.
for (int i = 0; i < 5;)
{
cout << "Please enter 5 odd numbers: "; //user enters 5 odd numbers
int tmp;
cin >> tmp;
if (tmp % 2 != 0) //if the number is odd then store it, else print error msg
{
array[i] = tmp;
i++;
}
else
{
cout << "Invalid input. Please only enter odd numbers!" << endl; //let the user know to enter only odd numbers.
}
}
@thmm - Granted it's poor practice to input directly into the array before checking, but if it's not odd, i does not get incremented and the entry gets overwritten the next time through the loop.
@AbstractionAnon,
why would it be overridden? Once an element is inserted i gets incremented.
If it doesn't get inserted there is no need to increment the next index.
No it doesn't in the OP's original code. See lines 16-19.
i only gets incremented if the element is odd.
The next time through the loop, the same element is used.
sorry for the late post. You guys helped me a ton. Turns out I'm doing this wrong anyway. It gives me the required output needed, but apparently I'm supposed to not have any of this under int main () I'm supposed to have functions. So now I am off to figure out to make functions.