In this article, we will write a C program to print all even and odd numbers in an array. The program takes an integer array from the user as input and prints all the even and odd numbers present in this array.
Sample Example:
Input: {1, 2, 3, 4, 5, 6 , 7, 8}
Output:
Even Numbers: { 2, 4, 6, 8 }
Odd Numbers: { 1, 3, 5, 7 }
A number is said to be even if it is exactly divisible by 2. Dividing even numbers by 2 always gives the remainder 0. For example, 2, 4, 6, 8, 100, 200, etc. are all even numbers.
Whereas, if the number is not exactly divisible by 2, it is said to be an odd number. Dividing such numbers by 2 always gives the remainder 1. For example, 1, 3, 5, 7, 99, 201, etc. are all odd numbers.
So, if you want to find out all the even and odd numbers in an array, you can run a for
or while
loop over the array, and check if the current element is exactly divisible by 2 or not. If it is divisible by 2, it’s an even number, if not, it’s an odd number.
To check if the number is exactly divisible by 2 or not, you can take the modulus %
of the number with 2. The modulus operator %
actually gives you the remainder of the division of two numbers.
When you take the modules %
of any number with 2 i.e. number %2
, it either gives you 1 or 0 as a result. If the result is 1, the number is odd otherwise the number is even.
number % 2 == 0 –> Even Number
number % 2 == 1 –> Odd Number
The following C program shows how you can print all even and odd numbers in an array:
// C Program to print all even and odd numbers in an array #include <stdio.h> int main() { int arr[100], size; printf("Enter the size of the array: "); scanf("%d", &size); printf("Enter elements of the array: "); for(int i = 0; i < size; i++){ scanf("%d", &arr[i]); } // Print all Even numbers printf("Even numbers are: "); for(int i = 0; i < size; i++){ if(arr[i] % 2 == 0){ printf("%d ", arr[i]); } } // Print all Odd numbers printf("\nOdd numbers are: "); for(int i = 0; i < size; i++){ if(arr[i] % 2 == 1){ printf("%d ", arr[i]); } } return 0; }
Output:
Enter the size of the array: 10 Enter elements of the array: 1 2 3 4 5 6 7 8 9 10 Even numbers are: 2 4 6 8 10 Odd numbers are: 1 3 5 7 9
Program Explanation:
The program starts by taking the size of the array from the user. Once the user finishes entering the array elements, the program iterates through the array to print out all of its even numbers.
In each iteration, the program checks if the current element of the array is divisible by 2 or not. If yes, it prints the current element(number) using the printf()
function. The same process is followed for the odd numbers.
I hope you will find this article helpful. Thanks for reading.