my code is going to take ten numbers and separate the numbers to two groups : odd and positive numbers
#include <iostream>
using namespace std;
int odd(int a)
{
if (a % 2 != 0)
{
return a;
}
}
int pos(int p)
{
if (p >= 0)
{
return p;
}
}
int main()
{
int i;
int entery[10];
cout << "please enter ten number : ";
for (i = 0; i < 10; i )
{
cin >> entery[i];
}
cout << "the odd numbers are : \n" << odd(entery[i]);
cout << "your positive numbers are : \n" << pos(entery[i]);
}
it it somehow works but the odd number is always 0 and the positive number always is -858993460
I use it without array and both groups become zero
CodePudding user response:
Here it goes your code corrected. Just to let you know, your code wasn't checking all the possible conditions inside odd
and pos
functions. It just was returning something when the condition was false
.
I modified these functions, making it work with a bool
now instead of a number. In your main
method, now, when this functions returns a true
, it will print the number, but won't do it if it's returning a false
.
#include <iostream>
using namespace std;
bool odd(int a) { return a % 2 != 0; }
bool pos(int p) { return p >= 0; }
int main()
{
int i;
int entery[10];
cout << "Please enter ten numbers: ";
for (i = 0; i < 10; i )
cin >> entery[i];
cout << "The odd numbers are : ";
for(int i = 0; i < 10; i ) {
if (odd(entery[i]))
cout << entery[i] << " ";
}
cout << "\nYour positive numbers are: ";
for(int i = 0; i < 10; i ) {
if (pos(entery[i]))
cout << entery[i] << " ";
}
}
If you want to change your program in the future, you can change the for
to make it work while sizeof(entery)/sizeof(entery[0])
, so it will iterate the array looking at the size instead of the number 10
.