a. Define an array with a maximum of 20 integer values, and fill the array with
ID: 3545645 • Letter: A
Question
a. Define an array with a maximum of 20 integer values, and fill the array with
numbers input from the keyboard or assigned by the program. Then write a function named
split() that reads the array and places all zeros or positive numbers in an array named positive
and all negative numbers in an array named negative. Finally, have your program call a function
that displays the values in both the positive and negative arrays.
b. Extend the program written for Exercise 6a to sort the positive and negative arrays into
ascending order before they
Explanation / Answer
#include <iostream>
using namespace std;
int splitNegative(int origArr[], int newArr[], int size){
int i, j = 0;
for(i = 0; i < size; i++){
if(origArr[i] < 0){
newArr[j++] = origArr[i];
}
}
return j;
}
int splitPositive(int origArr[], int newArr[], int size){
int i, j = 0;
for(i = 0; i < size; i++){
if(origArr[i] > 0){
newArr[j++] = origArr[i];
}
}
return j;
}
void displayArray(int arr[], int size){
int i;
for(i = 0; i < size; i++){
cout << arr[i] << " ";
}
cout << endl;
}
void sort(int arr[], int size){
int i, j;
for(i = 0; i < size; i++){
for(j = 0; j <= i; j++){
if(arr[i] < arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int main(){
int n, i, npos, nneg;
int arr[20], pos[20], neg[20];
cout << "Enter the 20 values of the array:" << endl;
for(i = 0; i < 20; i++){
cin >> arr[i];
}
nneg = splitNegative(arr, neg, 20);
npos = splitPositive(arr, pos, 20);
cout << "Original array: " << endl;
displayArray(arr, 20);
cout << "Positive array: " << endl;
displayArray(pos, npos);
cout << "Negative array: " << endl;
displayArray(neg, nneg);
sort(pos, npos);
sort(neg, nneg);
cout << endl << "Positive sorted array: " << endl;
displayArray(pos, npos);
cout << endl << "Negative sorted array: " << endl;
displayArray(neg, nneg);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.