In this program, we are going to share a C program to segregate even and odd elements of array. If you are a beginner and want to start learning the C programming, then keep your close attention in this tutorial as I am going to share a C program to segregate even and odd elements of array with the output.
We have designed this program for beginners for learning purpose. Copy below c program and execute it with c compiler to see the output of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#include<stdio.h> /* Function to swap *a and *b */ void swap(int *a, int *b); void segregateEvenOdd(int arr[], int size) { /* Initialize left and right indexes */ int left = 0, right = size-1; while (left < right) { /* Increment left index while we see 0 at left */ while (arr[left]%2 == 0 && left < right) left++; /* Decrement right index while we see 1 at right */ while (arr[right]%2 == 1 && left < right) right--; if (left < right) { /* Swap arr[left] and arr[right]*/ swap(&arr[left], &arr[right]); left++; right--; } } } /* UTILITY FUNCTIONS */ void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } /* driver program to test */ int main() { int arr[] = {12, 34, 45, 9, 8, 90, 3}; int arr_size = sizeof(arr)/sizeof(arr[0]); int i = 0; segregateEvenOdd(arr, arr_size); printf("Array after segregation "); for (i = 0; i < arr_size; i++) printf("%d ", arr[i]); return 0; } |
Array after segregation 12 34 90 8 9 45 3
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.