Q:

C program to segregate 1\'s and 0\'s in the array

0

C program to segregate 1's and 0's in the array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Program:

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 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 ilowhighsize, 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to find the difference between the large... >>
<< C program to find the missing number in the array ...