The following programs will print even and odd numbers in an array.
C++ Program to Find Even Numbers in Array
When the remainder of a number 'x' divided by 2 is equal to zero, the number is said to be even. To find remainder modulo operator denoted by % is used. (x%2 == 2).
Source Code:
#include <iostream>
using namespace std;
int main()
{
// creating an array and initializing it.
int sizeOfArray = 10;
int arr[sizeOfArray];
for (int i = 0, count = 1; i < 10; i++, count++)
{
arr[i] = count;
}
// Printing even numbers of array..
cout << "Even numbers in the array are: " << endl;
bool evenNumberFound = false;
for (int i = 0; i < sizeOfArray; i++)
{
if (arr[i] % 2 == 0)
{
cout << arr[i] << " ";
evenNumberFound = true;
}
}
if (evenNumberFound == 0)
{
cout << "There are no even numbers in the Array." << endl;
}
cout << endl;
return 0;
}
Output:
Even numbers in the array are:
2 4 6 8 10
C++ Program to Find Odd Numbers in Array
The numbers that give a remainder not equal to zero are odd numbers.
Simple changing the sign in the condition of the above program we can find odd numbers. (x % 2 != 0)
Source Code:
#include <iostream>
using namespace std;
int main()
{
// creating an array and initializing it.
int sizeOfArray = 10;
int arr[sizeOfArray];
for (int i = 0, count = 1; i < 10; i++, count++)
{
arr[i] = count;
}
// Printing Odd numbers of array..
cout << "Odd numbers in the array are: " << endl;
bool OddNumberFound = false;
for (int i = 0; i < sizeOfArray; i++)
{
if (arr[i] % 2 != 0)
{
cout << arr[i] << " ";
OddNumberFound = true;
}
}
if (OddNumberFound == 0)
{
cout << "There are no Odd numbers in the Array." << endl;
}
cout << endl;
return 0;
}
Output:
Odd numbers in the array are:
1 3 5 7 9
If you have any queries about this program or about anything, do ask in a comment. I will try to answer as many questions as I can.
Comments
Post a Comment