Home > front end >  How can we replace the higest 5 numbers in an array of 10 with 1 and smallest 5 into 0 in C programi
How can we replace the higest 5 numbers in an array of 10 with 1 and smallest 5 into 0 in C programi

Time:10-24

Here's the question my teacher gave me

Write a C program to store 10 integers in an array of size 10 and display the contents of the array. Replace the highest 5 numbers in the array by 1 and lowest 5 numbers by 0 and display the contents of the new array. [For e.g. Original Array 44 11 6 99 30 78 32 31 66 55 New Array 1 0 0 1 0 1 0 0 1 1

I have been struggling in this question whole day :(

CodePudding user response:

There are a lot of ways to solve this problem. A good way would be sort the array into another array and then replace the 1st half with 0s and the second half with 1s like this:

#include<stdio.h>

int main(){
    const int arraySize = 10;
    int i, j;
    int arr[arraySize];
    int arrSorted[arraySize];
    int temp;

    // Get input from user
    printf("Please enter 10 numbers!\n");
    for (i = 0; i < arraySize; i  )
    {
        scanf("%d", &arr[i]);
        // Copy array into another to sort it later
        arrSorted[i] = arr[i];
    }
    
    // Print input
    printf("Input:  ");
    for (i = 0; i < arraySize; i  )
    {
        printf("= ", arr[i]);
    }
    printf("\n");


    //Sort the array in ascending order
    for (i = 0; i < arraySize; i  ) 
    {
        for (j = i   1; j < arraySize; j  ) 
        {
           if(arrSorted[i] > arrSorted[j]) 
           {
               temp = arrSorted[i];
               arrSorted[i] = arrSorted[j];
               arrSorted[j] = temp;
           }
        }
    }

    // Start replacing procedure
    for (i = 0; i < arraySize; i  )
    {
        for (j = 0; j < arraySize; j  )
        {
            if (arr[j] == arrSorted[i])
            {
                if (i < arraySize / 2) // Replace 1st half with 0s
                {
                    arr[j] = 0;
                }
                else                   // Replace 2nd half with 1s
                {
                    arr[j] = 1;
                }
                break;
            }
        }
    }

    // Print result
    printf("Result: ");
    for (i = 0; i < arraySize; i  )
    {
        printf("= ", arr[i]);
    }
    printf("\n");

    return 0;
}

Of course, you can use the C standard library qsort() function if you don't want to sort yourself.

Another solution would be, find the median number of the array then replace any number which is less than it with 0 and any number bigger than it with 1. Although with this solution there will be some challenges regarding what to do with the median number itself and what if there are multiple median numbers (duplicated)?

  • Related