Coders Packet

Segregation of Positive and Negative elements of an Array using C++.


This is a packet used for separating the negative and positive elements present in an Array using while-loop and if-else statements in C++ language.

Code to segregate the positive and negative integers of an Array. It is written in C++ language.

Firstly, the size of the array is taken as input and then the values are taken as input from the user. The respective values are stored in the array.

The negative elements are moved to the left side of the array and the positive ones are moved to the right side.


Two iterators named left and right respectively pointing to 0th and last(n-1, where n is the size of the array) elements of the array. A while loop is initiated having the condition left<right ensuring that the two iterators don't cross each other. In that while loop, conditions are coded in such a way that if the left and right pointers both points to a negative number then the left iterator is increased by 1, and if both points to a positive element then the right iterator is decreased by 1. If the left points negative and right points a positive element then the left pointer is increased by 1 and the right one is decreased by 1. If the left points to a positive element and the right point to a negative element then both the elements are swapped and then the left iterator is increased and the right iterator is decreased. This is done so because we need the negative elements on the left side.


Using this method, the positive and negative elements of the array have been segregated.


Using a for loop starting for 0th index to last(n-1th) index is used for printing the elements of the array.

Download Complete Code


No comments yet