Splitting array into separate positive and negative arrays c++ - c++

I need to write a function that takes a given array and then splits it into two separate arrays with one array's elements being the positive elements of the main array and the other's elements being the negative elements of the main array. I can't seem to figure out what the loop to do this would look like.
I have written a separate function to determine how many positive and negative values are in the main array:
void count(int ARRAY[], int SIZE, int&NEG, int&POS)
{
for (int x=0; x<SIZE; x++)
{
if(ARRAY[x]>=0)
{
POS=POS+1 ;
}
if(ARRAY[x]<0)
{
NEG=NEG+1 ;
}
}
}
This counts the positives and negatives and the number of each would be the size of the respective positive and negative arrays after the split.
I have defined the function as such:
void split(int ARRAY[], int SIZE, int&NEG_ARRAY, int NEG, int&POS_ARRAY, int POS)
I just don't know how to set each of the positive elements in the main array as the elements in the new Positive-Only array and likewise for the negative array.
Thanks for your help!
After using the answers given and doing my best with the rest of the code, I got about a million lines of errors when trying to compile it. Is there a problem with how I am deleting the three dynamically allocated arrays? What huge error is preventing compiling?
Here is my code:
#include <iostream>
using namespace std;
void count(int ARRAY[], int SIZE, int&NEG, int&POS);
void split(int ARRAY[], int SIZE, int&NEG_ARRAY, int NEG, int&POS_ARRAY, int POS);
void print_array(int ARRAY[], int SIZE);
int main()
{
int SIZE (0);
int * ARRAY ;
cout<<"Enter number of elements: " ;
cin>> SIZE ;
ARRAY = new int[SIZE] ;
int x(0);
int numEle(0);
cout<<"Enter list: " <<endl;
while(numEle<SIZE)
{
ARRAY[numEle] = x ;
numEle++;
cin>>x;
}
int POS(0), NEG(0) ;
count(ARRAY, SIZE, NEG, POS) ;
int * NEG_ARRAY;
NEG_ARRAY = new int[NEG];
int * POS_ARRAY;
POS_ARRAY = new int[POS];
split(ARRAY, SIZE, NEG_ARRAY, NEG, POS_ARRAY, POS) ;
cout<<"Negative elements: "<<endl;
cout<<print_array(NEG_ARRAY, NEG) <<endl;
cout<<"Non-negative elements: "<<endl;
cout<<print_array(POS_ARRAY, POS)<<endl;
delete[] ARRAY;
delete[] NEG_ARRAY;
delete[] POS_ARRAY;
return 0;
}
void count(int ARRAY[], int SIZE, int&NEG, int&POS)
{
for (int x=0; x<SIZE; x++)
{
if(ARRAY[x]>=0)
{
POS=POS+1 ;
}
if(ARRAY[x]<0)
{
NEG=NEG+1 ;
}
}
}
void split(int ARRAY[], int SIZE, int&NEG_ARRAY, int NEG, int&POS_ARRAY, int POS)
{
NEG=POS=0;
for(int x=0; x<SIZE; x++)
{
if(ARRAY[x]<0)
{ NEG_ARRAY[NEG++]=ARRAY[x]; }
else {POS_ARRAY[POS++]=ARRAY[x]; }
}
}
void print_array(int ARRAY[], int SIZE)
{
for(int i=0; i<SIZE; i++)
{
cout << ARRAY[i] << " " ;
}
cout<<endl;
}
The code is supposed to read in the array and display the new negative and positive arrays. Thanks in advance!

You may get some C style answers
But here how I'd do using STL algorithms, as this is tagged for C++
Use std::partition
bool is_pos(int i) { return i > 0; }
auto p = std::partition(std::begin(ARRAY),
std::end(ARRAY), std::ptr_fun(is_pos));
std::copy(std::begin(ARRAY), p, std::begin(POS_ARRAY));
std::copy(p, std::end(ARRAY), std::begin(NEG_ARRAY));
Also you should use std::vector for such operations
Demo Here

This code will divide negative & positive numbers into separate arrays,
void split(int ARRAY[], int SIZE, int NEG_ARRAY[], int&NEG, int POS_ARRAY[], int&POS)
{
NEG=POS=0;
for (int i(0); i<SIZE; i++)
{
if (ARRAY[i]<0) NEG_ARRAY[NEG++]=ARRAY[i];
else POS_ARRAY[POS++]=ARRAY[i];
}
}

Its easy to modify your count() function:
void split(int ARRAY[], int SIZE, int NEG [], int POS [])
{
int ncount = 0, pcount = 0;
for (int x=0; x<SIZE; x++)
{
if(ARRAY[x]>=0)
{
POS[pcount++] = ARRAY[x];
}
if(ARRAY[x]<0)
{
NEG[ncount++] = ARRAY[x];
}
}
}

Related

How to print an array in descending order?

Basically this is my code and it works fine. I just don't know how to print it in descending order. This code basically shows the odd numbers:1,3,5,7. I want it to be printed 7,5,3,1. I know I need use the sort function but I dont know how.
#include <iostream>
using namespace std;
void fillArray(int arr[], int &n);
void printArray(int arr[], int n);
void findSum(int arr[], int &n);
int main()
{
int n;
cin>>n;
int arr[n];
fillArray(arr,n);
printArray(arr,n);
findSum(arr,n);
return 0;
}
void fillArray(int arr[], int &n)
{
int j=1;
for(int i=0;i<n;i++)
{
if(j%2==1)
arr[i]=j;
else
i--;
j++;
}
}
void printArray(int arr[], int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<", ";
}
}
void findSum(int arr[], int &n)
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+arr[i];
}
}
for(int i = n-1; i >= 0; i--)
{
cout << arr[i] << ", ";
}
example:
void printArray(int *tab, int size)
{
for (int i = size - 1; i >= 0; i--)
std::cout << tab[i] << std::endl;
}
int main() {
int tab[3] = { 1,2,3 };
printArray(tab, 3);
}
You should begin from last element array, and decrement iterator (i) to i == 0
You can simply use a sort function. There is one included with the algorithm header.
#include <algorithm> // this goes at the top
void printArray(int arr[], int n)
{
sort(arr, arr+n, [](int x, int y){return y<x;});
for(int i=0;i<n;i++)
cout << arr[i] << endl;
}
the [](int x, int y){return y<x;} part is just to make it descending. Normally it is y>x, at which point you can just omit the third parameter
Here is a repl:
https://repl.it/JQor/0

Segmentation Fault [2D array]

#include <iostream>
using namespace std;
void input_Array(char (&A)[10][10], int x, int y);
int calc_Collision(char (&A)[10][10]);
void display(char (&A)[10][10]);
void init_Array(char (&A)[10][10]);
int main()
{
int m,n,test;
char A[10][10];
init_Array(A);
cin>>test;
while (test>0)
{
cin>>m>>n;
input_Array(A,m,n);
display(A);
cout<<"FLAG";
cout<<calc_Collision(A);
test--;
}
}
//Calculates no. of ways to select two 1's in each column
int calc_Collision(char (&A)[10][10])
{
int count=0;
int sum=0;
int select(int x, int y);
for (int j = 0; j<10; j++)
{
count=0;
for(int i = 0; i<10; i++)
{
if (A[i][j]=='1')
{
count++;
}
}
sum=sum + select(count,2);
}
return sum;
}
//Returns no. of ways to select y items from x items
int select(int x, int y)
{
int fact(int a);
return (fact(x)/(fact(y)*fact(x-y)));
}
//Returns a!
int fact(int a)
{
if (a==0)
{
return 1;
}
else
{
return (a*fact(a-1));
}
}
void display(char (&A)[10][10])
{
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
cout<<A[i][j]<<"\t";
}
cout<<"\n";
}
}
Input Format:
no. of trials
no. of rows (whitespace) no. of columns
row1 (No space, 1's or 0's only)
row2...
Output:
The 2D array
Total no. of ways to select two one's in each column
Problem:
The program displays the array fine enough.
But upon coming across calc_Collision(A), the code outputs:
Segmentation fault (core dumped)
"FLAG" is NOT displayed.
Still a beginner here, so ANY help would be appreciated.
int select(int x, int y){
int fact(int a);
return (fact(x)/(fact(y)*fact(x-y)));
}
int fact(int a){
if (a==0) {
return 1;
}
else {
return (a*fact(a-1));
}
}
Notice that if x in select is less than 2, then fact(x-y) will call itself indefinitely. This is because the variable a in fact will be negative. This occurs when the size of the input array has less than 10 columns, resulting in the last column becoming empty. This causes the iteration of count to become 0 in calc_Collision. The segmentation fault does not occur if the input has 10 columns.
Since you are only computing nC2 (N choose 2), the select function can be rewritten as:
int select(int x){
return (x*(x-1))/2;
}

Merging two arrays in ascending order

I know the logic how to merge two arrays but the problem is how to code.
This was my code n it is giving correct ans but my sir told me that do it again,please tell me what I have to add in this code,
#include<iostream>
using namespace std;
int mergeArrays(int array1[],int size1,int array2[],int size2);
int main()
{
const int size1=8;
const int size=12;
int arrayA[size1]={10,25,37,49,50,51,55,60};
int arrayB[size]={2,5,26,27,29,32,40,45,70,80,90,95};
mergeArrays(arrayA,size1,arrayB,size);
}
int mergeArrays(int array1[],int size1,int array2[],int size2)
{
int size3=size1+size2;
int *array3=new int[size3];
int k=0;
for(int i=0;i<size1;i++)
{
array3[k]=array1[i];
cout<<" "<<array3[k];
}
int j=0;
for(int i=size1;i<size2;i++)
{
array3[k]=array2[j];
}
for(int i=size1;i<size2;i++)
{
for(int j=0;j<size2;j++)
{
array3[i]=array2[j];
cout<<" "<<array3[i];
}
cout<<endl;
delete[]array3;
return array3[k++];
}
}
I had searched this in many places but could not corrected my code
I had written this code but it is not giving correct ans.
#include<iostream>
using namespace std;
int merge(int *a,int *b,int aSize,int bSize);
int main()
{
const int aSize={8};
const int bSize={12};
int arrayA[aSize]={10,25,37,49,50,51,55,60};
int arrayB[bSize]={2,5,26,27,29,32,40,45,70,80,90,95};
merge(arrayA,arrayB,aSize,bSize);
return 0;
}
int merge(int *a,int *b,int aSize ,int bSize)
{
int cSize=aSize+bSize;
int *c=new int[cSize];
int j=0,k=0;
int i=0;
while(i<=aSize&&j<=bSize )
{
if(a[aSize ]<=b[bSize])
{
c[k]=a[aSize];
k++;
i++;
}
else
{
c[k]=b[bSize];
k++;
j++;
}
}
for(int i=0;i<k;i++)
{
cout<<c[i]<<endl;
}
delete[]c;
return c[k++];
}
your sir request you do Merging two arrays in ascending order. so i think you should return a new array, fill with array1 and array2's element, and the elements should be ascending order. here is a implement.(suppose your input arraies is already in ascending order.)
#include <iostream>
using namespace std;
int mergeArrays(int array1[],int size1,int array2[],int size2, int outArray[]);
int main()
{
const int size1=8;
const int size=12;
int arrayA[size1]={10,25,37,49,50,51,55,60};
int arrayB[size]={2,5,26,27,29,32,40,45,70,80,90,95};
int outArray[size1+size];
int len = mergeArrays(arrayA,size1,arrayB,size, outArray);
cout <<" "<< len;
for (int i = 0; i< size1+size; ++i){
cout <<" " << outArray[i];
}
}
int mergeArrays(int array1[], int size1, int array2[], int size2, int outArray[])
{
int i=0, j=0, k=0;
int retSize = size1+size2;
while (k<retSize){
if (i==size1){// only left array2, copy it
for (; j<size2; ++j){
outArray[k++] = array2[j];
}
}else if (j == size2) { // only left array1, copy it
for (; i<size1; ++i){
outArray[k++] = array1[i];
}
}
else if (array1[i] > array2[j]){ // copy the min value to outArray
outArray[k++] = array2[j++];
}else{
outArray[k++] = array1[i++];
}
}
return k;
}
now, let's look at your first code:
int mergeArrays(int array1[],int size1,int array2[],int size2)
{
int size3=size1+size2;
int *array3=new int[size3];
int k=0;
for(int i=0;i<size1;i++)
{
array3[k]=array1[i]; // k is not changed, so you just assign array1's each value to array3[0]
cout<<" "<<array3[k];
}
int j=0;
// what's the purpose of this loop?
// and in loop, you don't use i, you just repeat set array3[0] = array2[0]!!
for(int i=size1;i<size2;i++)
{
array3[k]=array2[j];
}
for(int i=size1;i<size2;i++) // if array2's length bigger than array1's, will enter this loop.
{
for(int j=0;j<size2;j++)
{
array3[i]=array2[j]; // this just repeat assign array2's each value to array3[i]!!
cout<<" "<<array3[i];
}
cout<<endl;
delete[]array3;
return array3[k++]; // you delete array3, but at here you access it!! this will crash!
// also, in this for i loop, you have return, so it will only execute once.
}
// reach function end and no return if not enter for loop.
}
I haven't looked at your second code. I think you still need to do more study.

Why this Selection sort code in Cpp, not giving required Output

#include<iostream>
using namespace std;
int min_arr(int arr[],int size);
void swap(int *,int *);
int main()
{
int arr[10]={31,2,55,3,77,12,89,98,43,34},loc;
int* arr1;
arr1 = &arr[0];
for(int i=0;i<10;i++)
{
for( int j=i;j<9;j++)
{
loc = min_arr(arr1,(10-i));
swap(&arr[loc],&arr[i]);
arr1++;
}
}
for(int i =0; i<10;i++)
cout<<arr[i]<<endl;
return 0;
}
int min_arr(int arr[],int size)
{
int k=0;
int temp=arr[0];
for(int i=1;i<size;i++)
{
if(arr[i]<temp)
{
temp=arr[i];
k=i;
}
}
return k;
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Why this Selection sort code in Cpp, not giving required Output? Kindly find the flaw! I have taken two functions to find min of the sub arrays as we procede. And as i find the min, i return its index and swap the first position of the sub array and minimum valued element!
After rearranging the code and adding some debug lines, it's pretty easy to find out what's wrong:
Firstly, the second loop (j loop) is completely pointless
Secondly loc variable is not 0-based but i-based (as you searched over arr1, which is incremented by the loop), so arr[loc] should be arr[loc+i]
Corrected, smartly indented (that's important to make tour code easily readable) code:
#include<iostream>
#define ARRAY_SIZE 10
using namespace std;
int min_arr(int arr[],int size);
void swap(int *,int *);
int main()
{
int arr[ARRAY_SIZE]={31,2,55,3,77,12,89,98,43,34},loc;
int* arr1;
arr1 = &arr[0];
for( int i = 0; i < ARRAY_SIZE; i++ )
{
//for( int j = i; j<ARRAY_SIZE-1; j++ )
{
loc = min_arr(arr1,(ARRAY_SIZE-i));
// for debug:
//std::cout << "min found at " << loc << std::endl;
swap(&arr[loc+i],&arr[i]);
// for debug:
//for( int i =0; i<ARRAY_SIZE; i++ )
// cout << arr[i] << " ";
//cout << std::endl;
arr1++;
}
}
for( int i =0; i<ARRAY_SIZE; i++ )
cout<<arr[i]<<endl;
return 0;
}
int min_arr( int arr[], int size )
{
int k=0;
int temp=arr[0];
for( int i=1; i<size; i++ )
{
if( arr[i] < temp )
{
temp=arr[i];
k=i;
}
}
return k;
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
It will output:
2
3
12
31
34
43
55
77
89
98
In your version you just go with pointers beyond the area mapped for the array.
First of all, call of the function min_arr. It requires array, not pointer:
loc=min_arr(arr,(10-i));
Second, the function itself. You always start from the beginning of the array, that's why already sorted elements go resorted.
int min_arr(int arr[],int size)
{
int k=10-size;
int temp=arr[k];
for(int i=k+1;i<10;i++)
{
if(arr[i]<temp)
{
temp=arr[i];
k=i;
}
}
return k;
}
for(int i=0;i<10;i++)
{
for( int j=i;j<9;j++) //shouldn't this be j < 10 ?
......

C++ Returning two values in Array

I am almost done with my code; however, one part is not working well. Simply, reading from a file that contains only numbers(ex. cars sold). by using an array, trying to get the total of those numbers, max, and the number of the max index. My question is: how can I return the two values from my MaxSold function? it returns only the max added to the index which is not correct. the result should point to the employee number then the max.
This is my code so far:
#include <iostream>
#include <fstream>
/*#include <vector>
#include <iomanip>*/
void Read(int arryList[], int size);
void Print(int arryList[], int size);
int total(int arryList[], int size);
int MaxSold(int arryList[], int size, int& number);
using namespace std;
ifstream inFile("C:\\cars.dat");
int main()
{
int cars[7];
int i;
Read(cars,7);
Print(cars,7);
cout<<"The total of sold cars is: "<<total(cars, 7)<< "\n";
cout<<"The Max "<< MaxSold(cars, 7, i);
}
void Read(int arryList[], int size){
for(int i = 0; i < 7; i++)
{
inFile >> arryList[i];
}
return;
}
void Print(int arryList[], int size){
for (int i = 0; i < 7; i++){
cout << i + 1 << "-"<< arryList[i] << "\n";
}
return ;
}
int total(int arryList[], int size){
int sum = 0;
for (int i = 0; i < size; i++){
sum +=arryList[i];
}
return sum;
}
int MaxSold(int arryList[], int size, int& number){
int Maximum= 0;
int relate=0;
for( int i=0 ; i<7 ; i++){
if (arryList[i] > Maximum){
Maximum = arryList[i];
relate = i+1;
}
}
return Maximum, relate;
}
Use std::pair
#include<utility>
//..
std::pair<int,int> MaxSold(int arryList[], int size, int& number)
{
//...
return std::make_pair( Maximum, relate );
}
Then,
std::pair<int,int> p = MaxSold(cars, 7, i) ;
std::cout<< p.first ; //maximum
std::cout<< p.second ; //relate
You cannot return more than one value from a function. Of course, that value can be a container for multiple values. It can be your own custom type, but the simplest way would be to return a std::pair<int,int>.
std::pair<int, int> MaxSold(int arryList[], int size, int& number)
{
// ...
return std::make_pair(Maximum, relate);
}