Home »
C programs »
C one-dimensional array programs
C program to segregate 1's and 0's in the array
Here, we are going to learn how to segregate 1's and 0's in the array in C programming language?
Submitted by Nidhi, on July 11, 2021
Problem statement
Here, we will create an array of integers and segregate 1's and 0's from the array, and print the result on the console screen.
Segregating 1's and 0's in the array
The source code to segregate 1's and 0's in the array is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
C program to segregate 1's and 0's in the array
// C program to segregate 1's and 0's in array
#include <stdio.h>
int main()
{
int arr[] = { 1, 0, 1, 0, 1, 0 };
int size = 0;
int i = 0;
int low = 0;
int high = 0;
size = sizeof(arr) / sizeof(arr[0]);
high = size - 1;
while (low < high) {
while (arr[low] == 0 && low < high)
low = low + 1;
while (arr[high] == 1 && low < high)
high = high - 1;
if (low < high) {
arr[low] = 0;
arr[high] = 1;
low++;
high--;
}
}
printf("segregated array is: ");
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Output
segregated array is: 0 0 0 1 1 1
Explanation
Here, we created an array arr with 6 elements that contain only 0's and 1's. And, we also created four variables i, low, high, size, that are initialized with 0. Then we calculated the size of the array and assigned it to the "size" variable. After that, we segregate the 0's and 1's in the array and printed them on the console screen.
C One-Dimensional Array Programs »