Write a C program to input elements in an array and put all even and odd elements in two separate array. How to separate even and odd elements of a given array in two separate array containing only even or odd elements using C programming.
Example:
Input size of the array: 10
Input elements in array: 0 1 2 3 4 5 6 7 8 9
Output even elements in array: 0 2 4 6 8
Output odd elements in array: 1 3 5 7 9
Happy coding ;)
Example:
Input size of the array: 10
Input elements in array: 0 1 2 3 4 5 6 7 8 9
Output even elements in array: 0 2 4 6 8
Output odd elements in array: 1 3 5 7 9
Required knowledge
Basic C programming, If else, Loop, Array, FunctionProgram
/**
* C program to put even and odd elements of an array in two separate array
*/
#include <stdio.h>
#define MAX_SIZE 1000 //Maximum size of the array
void printArray(int arr[], int len);
int main()
{
int arr[MAX_SIZE], i, n;
int even[MAX_SIZE], odd[MAX_SIZE], evenCount, oddCount;
/*
* Reads size and elements in the array
*/
printf("Enter size of the array: ");
scanf("%d", &n);
printf("Enter elements in the array: ");
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
evenCount = oddCount = 0;
for(i=0; i<n; i++)
{
// If arr[i] is odd
if(arr[i] & 1)
{
odd[oddCount] = arr[i];
oddCount++;
}
else
{
even[evenCount] = arr[i];
evenCount++;
}
}
printf("\nElements of even array: \n");
printArray(even, evenCount);
printf("\nElements of odd array: \n");
printArray(odd, oddCount);
return 0;
}
/**
* Prints the entire integer array
* @arr Integer array to be displayed or printed on screen
* @len Length of the array
*/
void printArray(int arr[], int len)
{
int i;
printf("Elements in the array: ");
for(i=0; i>len; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
Output
Enter size of the array: 10
Enter elements in the array: 0 1 2 3 4 5 6 7 8 9
Elements of even array:
Elements in the array: 0 2 4 6 8
Elements of odd array:
Elements in the array: 1 3 5 7 9
Enter elements in the array: 0 1 2 3 4 5 6 7 8 9
Elements of even array:
Elements in the array: 0 2 4 6 8
Elements of odd array:
Elements in the array: 1 3 5 7 9
Happy coding ;)
You may also like
- Array and matrix programming exercises index.
- C program to check even or odd using bitwise operator.
- C program to sort all even and odd elements of an array separately.
- C program to search an element in the array.
- C program to count frequency of each element of the array.
- C program to merge two array in third array.
- C program to remove all duplicate elements from an array.
- C program to copy all elements of the array to another array.
- C program to interchange diagonals of a matrix.
- C program to find upper triangular matrix.
- C program to find lower triangular matrix.
- C program to check Identity matrix.
- C program to check Sparse matrix.
- C program to find determinant of a matrix.
- C program to check whether two matrices are equal or not.