Cover Image for Segregate 0s and 1s into array in C
88 views

Segregate 0s and 1s into array in C

To segregate 0s and 1s into separate arrays in C, you can iterate through the input array and place each element into either the “0s array” or the “1s array” based on its value. Here’s a C program to achieve this segregation:

C
#include <stdio.h>

void segregateZerosAndOnes(int arr[], int n) {
    int zeros[n]; // Array to store 0s
    int ones[n];  // Array to store 1s
    int zeroCount = 0;
    int oneCount = 0;

    // Iterate through the input array
    for (int i = 0; i < n; i++) {
        if (arr[i] == 0) {
            zeros[zeroCount++] = arr[i];
        } else {
            ones[oneCount++] = arr[i];
        }
    }

    // Copy the segregated arrays back to the original array
    for (int i = 0; i < zeroCount; i++) {
        arr[i] = zeros[i];
    }

    for (int i = 0; i < oneCount; i++) {
        arr[zeroCount + i] = ones[i];
    }
}

int main() {
    int arr[] = {0, 1, 0, 1, 1, 0, 0, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original Array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    segregateZerosAndOnes(arr, n);

    printf("Segregated Array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

In this program:

  • We create two separate arrays, zeros and ones, to store the 0s and 1s, respectively. These arrays have the same size as the input array arr.
  • We use zeroCount and oneCount to keep track of the number of 0s and 1s encountered during iteration.
  • We iterate through the input array arr, and for each element, if it is a 0, we store it in the zeros array; otherwise, we store it in the ones array.
  • After segregating the elements, we copy the segregated arrays back to the original array arr. The zeroCount variable helps us determine the starting index for the ones array in arr.

When you run this program, it will segregate the 0s and 1s in the original array into two separate sections within the same array.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS