You are currently viewing Best array Re-arranging code for mixed Positive & Negative Values in 2023

Best array Re-arranging code for mixed Positive & Negative Values in 2023

Learn C Language in Easy way

Here is the explanation of the logic of performing rearrangement of the array using C Code

In this C code you will take an array with negative and positive values in mixed form. We are going to rearrange the mixed values without affecting their relative position using C Code.  After executing the code it will rearrange the elements in such a way that one side will have all negative values and another side will have all positive values but without affecting their relative position. In this C Code format we are first of all going to take input of all array elements.

As you can see we have taken array size as 50, means we are allowed to take maximum 50 elements in this array.But, we are going to use some portion of the elements for testing purpose. That portion is taken as input from the user using the first scanf function in this C Code. That input should be lesser or equal to 50. I hope all of you can understand the reason behind the number we are taking as input.

As we all know array is a static memory allocation so you can not cross the maximum limit( here 50). After that before performing the C code for re-arrangement operation we have printed the mixed form of the array. After that the actual re-arrangement  operation has taken place. After completion of that operation we have printed the resultant array, means the properly arranged array with the desired output format.

I hope you have understood the logic for this C Code. If you are having any doubt then please feel free to contact me for further explanation. You can also visit my youtube channel for more videos related to different topics. For more codes like this or with different categories please click.

 

 

#include <stdio.h>

int main()
{
    int m,i,ar[50],t,j;
   
    printf("Enter the number of elements : ");
    scanf("%d",&m);
   
    printf("Enter the elements : ");
   
    for(i=0;i<m;i++)
    {
        scanf("%d",&ar[i]);
    }
   
    printf("Before rearrangement : ");
    for(i=0;i<m;i++)
    printf("%d,",ar[i]);
    printf("\n=================================================================\n");
    for(i=0;i<m;i++)
    {
       
        if(ar[i]<0)
        {
            t=ar[i];
            j=i-1;
            while(ar[j]>0 && j>=0)
            {
                ar[j+1]=ar[j];
                j--;
            }
            ar[j+1]=t;
        }
    }
   
    printf("After rearrangement : ");
    for(i=0;i<m;i++)
    printf("%d,",ar[i]);
    return 0;
}

Leave a Reply