I'm trying to write a function delete an element in a C++ array, that is, shift every element one to the left, starting at the index.
The code
#include <iostream>
using namespace std;
const int MAX_SIZE = 50;
void fill_array(char array[], int ¤t_size, const int max_size);
void print_array(const char array[], const int current_size);
int delete_index(char array[], int ¤t_size, int index);
int main () {
char array[MAX_SIZE] = {' '};
int current_size = 0;
fill_array(array, current_size, MAX_SIZE);
int index = 4;
delete_index(array, current_size, index);
cout << "After deleting element at index " << index << " the array is: ";
print_array(array, current_size);
return 0;
}
int delete_index(char array[], int ¤t_size, int index) {
// Check input
if (index > current_size) {
cout << "Index must be between 0 and " << current_size - 1 << endl;
return -1;
}
for (int i = index; i < current_size; i++) {
cout << "array[" << index << "] = " << index << endl;
array[index] = array[index + 1];
}
current_size--;
cout << current_size << endl;
return 0;
}
However, the output I get when inputting "thisisnotworking" and index 4 is:
Please input characters for the array (max of 50) or enter '*' to quit:
onetwothree*
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
10
After deleting element at index 4 the array is: onetoothre
I don't understand it is not increasing the index in the for loop.
I've read similar questions here and elsewhere but couldn't fix the problem still. Any idea why this is?
NOTE: I only want to use arrays (not vectors, etc.).
for (int i = index; i < current_size; i++) {
cout << "array[" << index << "] = " << index << endl;
array[index] = array[index + 1];
}
Your loop counter is i. Inside your loop, you should use i instead of index
Corrected:
for (int i = index; i < current_size; i++) {
cout << "array[" << i << "] = " << array[i] << endl;
array[i] = array[i + 1];
}
Because you use array[index] = array[index + 1] while you need array[i] = array[i + 1]
It's the same here: cout << "array[" << i << "] = " << i << endl;
use pointers to dynamically change the size:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int* ClearElement(int array[], int index, const int& SizeOrig, int& NewSize)
{
array[index] = -1;
NewSize = SizeOrig;
NewSize--;
int* ptrArray = new int[NewSize];
if(!ptrArray)
throw "No more memory!";
for(int i(0), j(0); i < SizeOrig; i++)
{
if(-1 != array[i])
{
ptrArray[j] = array[i];
j++;
}
}
return ptrArray;
}
int main()
{
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int SizeOrig = (sizeof(array) / sizeof(int));
int NewSize = SizeOrig;
int index;
try{
cout << "element index to clear: ";
cin >> index;
cout << endl;
if(index < 0 || index > NewSize)
throw "out of boundary index!";
int* ptrArray = ClearElement(array, index, SizeOrig, NewSize);
for(int i(0); i < NewSize; i++)
cout << ptrArray[i] << ", ";
delete[] ptrArray;
}
catch(char* cp)
{
cout << cp << endl;
exit(1);
}
catch(...)
{
cout << "sorry an error has happened!";
exit(1);
}
cout << endl << endl << endl;
return 0;
}
You can also use std::copy from algorithm
int max = 10;
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int index = 4;
std::copy(array+index+1, array+max, array+index);
Related
Having issues with my getPosNums3 function.....all the others work as I need them to. I'm having issues in general understanding pointers, but I am sure that will pass. The aforementioned function spits out the size and address as I need it to, but when I print the newly modified array, it prints out long identical negative integers akin to this: -5476891, -5476891. It'll put out the right amount of integers, which tells me it is a small adjustment that is hanging up my code.....all these functions modify an array down to only its positive values; they just do so via different methods. I appreciate the help
#include <iostream>
using namespace std;
typedef int* IntArrayPtr;
int* getPosNums1(int* arr, int arrSize, int& outPosArrSize);
int* getPosNums2(int* arr, int arrSize, int* outPosArrSizePtr);
void getPosNums3(int* arr, int arrSize, int*& outPosArr, int& outPosArrSize);
void getPosNums4(int* arr, int arrSize, int** outPosArrPtr, int* outPosArrSizePtr);
void printNewArray(int* arr, int arrSize);
void fillArray(int a[], int size);
int main() {
cout << "Fuction 1: " << endl;
int array_size;
cout << "What is the size of the array? ";
cin >> array_size;
IntArrayPtr a;
a = new int[array_size];
fillArray(a, array_size);
int posArraySize;
int* posNums1 = getPosNums1(a, array_size, posArraySize);
cout << "Original array is: ";
printNewArray(a, array_size);
cout << "The new address is " << posNums1 << " and the new size is " << posArraySize << " " << endl;
cout << "New array is: ";
printNewArray(posNums1, posArraySize);
delete[] a;
cout << endl;
cout << "Function 2: " << endl;
int array_size2;
cout << "What is the size of the array? ";
cin >> array_size2;
a = new int[array_size2];
fillArray(a, array_size2);
cout << "Original array is: ";
printNewArray(a, array_size2);
int* posArraySize2 = &array_size2;
int* posNums2 = getPosNums2(a, array_size2, posArraySize2);
cout << "The new address is " << posNums2 << " and the new size is " << *posArraySize2 << " " << endl;
cout << "New array is: ";
printNewArray(posNums2, *posArraySize2);
delete[] a;
cout << endl;
cout << "Function 3: " << endl;
int array_size3;
cout << "What is the size of the array? ";
cin >> array_size3;
a = new int[array_size3];
fillArray(a, array_size3);
cout << "Original array is: ";
printNewArray(a, array_size3);
int* posNums3 = new int[array_size3];
int posArraySize3 = array_size3;
getPosNums3(a, array_size3, posNums3, posArraySize3);
cout << "The new address is " << posNums3 << " and the new size is " << posArraySize3 << endl;
cout << "New array is: ";
printNewArray(posNums3, posArraySize3);
delete[] a;
cout << endl;
cout << "Function 4: " << endl;
int array_size4;
cout << "What is the size of the array? ";
cin >> array_size4;
a = new int[array_size4];
fillArray(a, array_size4);
cout << "Original array is: ";
printNewArray(a, array_size4);
int* posNums4ptr = &array_size4;
int* posNums4 = new int[array_size4];
int** posNums4ptrptr = &posNums4;
getPosNums4(a, array_size4, posNums4ptrptr, posNums4ptr);
cout << "The new address is " << posNums4ptrptr << " and the new size is " << *posNums4ptr << endl;
cout << "New array is: ";
printNewArray(posNums4, *posNums4ptr);
delete[] a;
return 0;
}
int* getPosNums1(int* arr, int arrSize, int& outPosArrSize) {
int* newArray = new int[arrSize];
int counter = 0;
for (int i = 0; i < arrSize; i++) {
if (arr[i] > 0) {
newArray[counter] = arr[i];
counter++;
}
}
outPosArrSize = counter;
return newArray;
}
int* getPosNums2(int* arr, int arrSize, int* outPosArrSizePtr) {
int size = 0, counter = 0;
int newArraySize = 0;
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
newArraySize++;
}
}
int* newArray = new int[newArraySize];
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
newArray[counter] = *(arr + i);
size++;
counter++;
}
}
*outPosArrSizePtr = size;
return newArray;
}
void getPosNums3(int* arr, int arrSize, int*& outPosArr, int& outPosArrSize){
int counter = 0, size = 0;
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
size++;
}
}
int *newArray = new int[size];
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
newArray[counter] = *(arr + i);
counter++;
}
}
delete[] outPosArr;
outPosArr = newArray;
outPosArrSize = size;
delete[] newArray;
newArray = nullptr;
}
void getPosNums4(int* arr, int arrSize, int** outPosArrPtr, int* outPosArrSizePtr){
int size = 0, counter = 0, newArraySize = 0;
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
newArraySize ++;
}
}
int* temp = new int[newArraySize];
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
temp[counter] = arr[i];
size++;
counter++;
}
}
*outPosArrSizePtr = size;
*outPosArrPtr = temp;
}
void printNewArray(int* arr, int arrSize) {
for (int i = 0; i < arrSize; i++)
cout << arr[i] << " ";
cout << endl;
}
void fillArray(int a[], int size) {
cout << "Enter " << size << " integers." << endl;
for (int i = 0; i < size; i++)
cin >> a[i];
}
The code in question is
void getPosNums3(int* arr, int arrSize, int*& outPosArr, int& outPosArrSize){
// [snip] count number of positive entries in arr and call it "size"
int *newArray = new int[size];
// [snip] copy positive entries in arr into newArray
delete[] outPosArr;
outPosArr = newArray;
outPosArrSize = size;
delete[] newArray;
newArray = nullptr;
}
First of all, it's not a good idea for this function to delete[] outPosArr because that presumes that outPosArr is either nullptr or something that was previously allocated with new[]. If it isn't one of those two things then this function has undefined behavior.
Somebody calling a function to copy numbers into an array is not typically going to also want the function to clean up some previous thing that may or may not have been in that array.
But your real problem is that you allocate memory for an array via int *newArray = new int[size], copy stuff in, and then immediately deallocate that memory by calling delete[] newArray. This leaves outPosArr to point to what used to be an array.
Also, assigning nullptr to newArray at the end of the function does nothing, because newArray is going out of scope anyway.
I need to write a C++ program where it swaps between two 1-dimensional
arrays using pointers and functions. Firstly, a void function named showValues to display both arrays before swapping takes and also a void function named swap to swap the elements between both arrays.
My question is: I'm supposed to swap the function but for some reason it wont run and I am not sure where is the error in my code
#include <iostream>
#include <iomanip>
using namespace std;
const int SIZE = 5;
void showValues(int[],int[]);
void swap(int[],int[]);
int main() {
int array1[SIZE] = {10,20,30,40,50};
int array2[SIZE] = {60,70,80,90,100};
showValues (array1, array2);
swap(array1, array2);
return 0;
}
void showValues(int array1[], int array2[]){
cout<<"The original arrays are as shown below: " << endl;
cout << " Array 1 is: ";
for (int i = 0; i < 5; ++i) {
cout << array1[i] << " ";
}
cout << "\n Array 2 is: ";
for (int i = 0; i < 5; ++i) {
cout << array2[i] << " ";
}
}
void swap(int array1[], int array2[])
{
int temp,i;
for(i=0; i<5; ++i)
{
temp = array1[SIZE];
array1[SIZE] = array2[SIZE];
array2[SIZE] = temp;
}
cout << "\nThe swapped arrays are as shown below: " << endl;
cout << " Array 1 is: ";
for (int i = 0; i < 5; ++i) {
cout << array1[i] << " ";
}
cout << "\n Array 2 is: ";
for (int i = 0; i < 5; ++i) {
cout << array2[i] << " ";
}
}
This part of your code doesn't make sense:
temp = array1[SIZE];
array1[SIZE] = array2[SIZE];
array2[SIZE] = temp;
SIZE is 5. So, you are accessing array1[5] and array2[5], i.e. the 6th element of the array. Yet, your arrays have only 5 elements to begin with (array1[0] to array1[4], same for array2), so you are accessing elements beyond the end of the array, which is undefined behavior that is probably just corrupting memory somewhere!
You probably meant to use i here, not SIZE, then the code makes sense. Instead, it would be useful to replace the "magic number" 5 with SIZE:
for(i = 0; i < SIZE; ++i)
{
temp = array1[i];
array1[i] = array2[i];
array2[i] = temp;
}
The void swap(int array1[], int array2[]) function is where you are having trouble. You actually don't even need to have another function for the swapping. You could just use std::swap() which is defined in the #include <utility> header. Since both arrays have the same size.
For example you could do something along these lines:
#include <iostream>
#include <iomanip>
#include <utility>
const int SIZE = 5;
void showValues(int[], int[]);
void swap(int[], int[]);
int main() {
int array1[SIZE] = { 10,20,30,40,50 };
int array2[SIZE] = { 60,70,80,90,100 };
int n = sizeof(array1) / sizeof(array2[0]);
showValues(array1, array2);
std::swap(array1, array2);
std::cout << "\n\nThe swapped arrays are as shown below:\n ";
std::cout << "\nArray 1 is: ";
for (int i = 0; i < n; i++)
std::cout << array1[i] << ", ";
std::cout << "\nArray 2 is: ";
for (int i = 0; i < n; i++)
std::cout << array2[i] << ", ";
return 0;
}
void showValues(int array1[], int array2[]) {
std::cout << "The original arrays are as shown below: " << std::endl;
std::cout << "\nArray 1 is: ";
for (int i = 0; i < 5; ++i) {
std::cout << array1[i] << " ";
}
std::cout << "\nArray 2 is: ";
for (int i = 0; i < 5; ++i) {
std::cout << array2[i] << " ";
}
}
Also consider not using using namespace std;.
#include <iostream>
using namespace std;
void getMaximumPositive(int* arr, int size, int* max)
{
max = nullptr; //Set default value of max pointer
for (int i = 0; i < size; i++)
{
if (arr[i] > 0) //Only positive numbers are considered while locating the maximum
{
if (max == nullptr)
max = &arr[i];
else if (arr[i] > * max)
max = &arr[i];
}
}
}
void getMaximumNegative(int* arr, int size, int* max)
{
max = nullptr; //Set default value of max pointer
for (int i = 0; i < size; i++)
{
if (arr[i] < 0) //Only negative numbers are considered while locating the maximum
{
if (max == nullptr)
max = &arr[i];
else if (arr[i] > * max)
max = &arr[i];
}
}
}
void printArrayForwards(int* arr, int size)
{
cout << "Array contents (Forwards): " << endl;
for (int i = 0; i < size; i++)
cout << arr[i] << " : ";
cout << endl;
}
void printArrayBackwards(int* arr, int size)
{
cout << "Array contents (Backwards): " << endl;
for (int i = 0; i < size; i++)
cout << *(arr - i - 1) << " : ";
cout << endl;
}
void swapMaxtoFront(int* arr, int* max_address)
{
if (max_address == nullptr)
return; //Do nothing if max_address is null
//Print the addresses and their corresponding values of the first element and the maximum element of the array
cout << endl << "Swapping elements:" << endl;
cout << "Address 1: " << arr << " Value: " << *arr << endl;
cout << "Address 2: " << max_address << " Value: " << *max_address << endl << endl;
//Code for the swap
int temp = *arr;
*arr = *max_address;
*max_address = temp;
max_address = arr;
}
void PrintArray(int* arr, int size)
{
printArrayForwards(arr, size);
printArrayBackwards(arr, size);
}
int main()
{
//Initialize pointers to null
int* array = nullptr; //Do Not Change This Variable Definition
int* max = nullptr; //Do Not Change This Variable Definition
int arr_size;
cout << "Enter the size of your array: ";
cin >> arr_size;
array = new int[arr_size]; //Reserve memory for array of size given by user
cout << "Enter array elements: " << endl;
for (int i = 0; i < arr_size; i++)
{
cout << "Element " << i + 1 << " of " << arr_size << " : ";
cin >> *(array++);
}
PrintArray(array, arr_size);
cout << endl << endl;
cout << "-----------------------------------------------" << endl << "Finding maximum positive number in array..." << endl;
getMaximumPositive(array, arr_size, max); //Max should point to the Maximum positive value in the array
swapMaxtoFront(array, max); //Swap the maximum positive number with the first element of the array
PrintArray(array, arr_size); //Print array with swapped values.
//Print maximum positive number
cout << endl;
if (max == nullptr)
cout << "*******No positive numbers found in array" << endl;
else
cout << "*******Maximum positive number in array: " << *max << endl; //Max should point to the Maximum positive value in the array, which should now be the first element
cout << "-----------------------------------------------" << endl;
cout << endl;
cout << "-----------------------------------------------" << endl << "Finding maximum negative number in array..." << endl;
getMaximumNegative(array, arr_size, max); //Max should point to the Maximum negative value in the array
swapMaxtoFront(array, max); //Swap the maximum negative number with the first element of the array
PrintArray(array, arr_size); //Print array with swapped values.
//Print maximum negative number
cout << endl;
if (max == nullptr)
cout << "*******No negative numbers found in array" << endl;
else
cout << "*******Maximum negative number in array: " << *max << endl; //Max should point to the Maximum negative value in the array, which should now be the first element
cout << "-----------------------------------------------" << endl;
delete[] array;
delete max;
array = nullptr;
max = nullptr;
return 0;
}
Output (That I am trying to look for):
Enter the size of your array: 4
Enter array elements:
Element 1 of 4 : 2
Element 2 of 4 : 8
Element 3 of 4 : 4
Element 4 of 4 : 6
Array contents (Forwards):
2 : 8 : 4 : 6 :
Array contents (Backwards):
6: 4 : 8 : 2
Finding maximum positive number in array...
Swapping elements:
Address 1: 015E10A0 Value: 2
Address 2: 015E10A4 Value: 8
Array contents (Forwards)
8 : 2 : 4 : 6 :
Array contents (Backwards)
6 : 4 : 2 : 8 :
*******Maximum positive number in array: 8
Finding maximum negative number in array...
Array contents (Forwards):
8 : 2 : 4 : 6 :
Array contenes (Backwards):
6: 4 : 2 : 8 :
*******No negative numbers found in array
The biggest problem I noticed was what you do with array:
array = new int[arr_size];
//...
for(size_t i = 0; i < arr_size; i++) {
cin >> *(array++); // here you step array
}
// ... and you use the final pointer "array" everywhere, undefined behaviour. It
// points one element outside of the area you allocated
delete[] array; // the final nail in the coffin,
Fix:
for(int i = 0; i < arr_size; i++) {
cout << "Element " << i + 1 << " of " << arr_size << " : ";
cin >> array[i];
}
With that fixed, this becomes a problem:
void printArrayBackwards(int* arr, int size) {
cout << "Array contents (Backwards): " << endl;
// arr points at the start, so arr - 0 - 1 points before start here:
for(int i = 0; i < size; i++) cout << *(arr - i - 1) << " : ";
cout << endl;
}
Fix:
void printArrayBackwards(int* arr, int size) {
cout << "Array contents (Backwards): " << endl;
for(int i = size - 1; i >= 0; --i) cout << arr[i] << " : ";
cout << endl;
}
Another thing is the getMaximumPositive and getMaximumNegative functions. You don't return a pointer to the max value in max. I changed it to a reference to an int*:
void getMaximumPositive(int* arr, int size, int*& max) {
max = nullptr; // Set default value of max pointer
for(int i = 0; i < size; i++) {
if(arr[i] > 0)
{ // Only positive numbers are considered while locating the maximum
if(max == nullptr)
max = &arr[i];
else if(arr[i] > *max)
max = &arr[i];
}
}
}
void getMaximumNegative(int* arr, int size, int*& max) {
max = nullptr; // Set default value of max pointer
for(int i = 0; i < size; i++) {
if(arr[i] < 0)
{ // Only negative numbers are considered while locating the maximum
if(max == nullptr)
max = &arr[i];
else if(arr[i] > *max)
max = &arr[i];
}
}
}
I also removed the delete max you had. It is a pointer to an int inside the array that you delete with delete[] array. You should not delete that.
Another function where to don't return the value via the parameter is in swapMaxtoFront. I changed that to:
void swapMaxtoFront(int* arr, int*& max_address) {
//...
Full code with your input mocked with
std::istringstream cin{"4 2 8 4 6"};
You passed pointer as parameter.
To receive a pointer, you should pass pointer of pointer.
You can write as this..
void getMaximumPositive(int* arr, int size, int** max) {
...
*max = &arr[ i ];
...
}
...
getMaximumPositive( arr, 10, &max );
I'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}
I have searched many examples and have yet to be able to find where exactly my problem lies. I am trying to implement the merge sort algorithm from the Cormen intro to algorithms book-- here is where I am at so far-- I have tried throwing in print statements to follow how the arrays are getting rebuilt but I am not seeing it... can anyone help?
Code:
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
int p = 0;
int q = 0;
int r = 0;
int getRandom()
{
int randNum = 0;
randNum = 1 + rand() % 100;
return randNum;
}
void populateArray(int * array, int size)
{
for (int i = 0; i < size; i++) {
array[i]=getRandom();
}
}
void merge (int * array, int p, int q, int r) // p = start, q = mid, r = end
{
int i = 0; // left array iterator
int j = 0; // right array iterator
int n1 = q - p + 1;
int n2 = r - q;
// int arrayL[n1 + 1];
//int arrayR[n2 + 1];
int arrayL[n1];
int arrayR[n2];
for (i = 0; i < n1; i++) {
arrayL[i] = array[p + i];
}
cout << "TEST ARRAY MS A: ";
for (int count = 0; count < n1; count++) {
cout << arrayL[count] << " ";
}
cout << endl << endl;
for (j = 0; j < n2; j++) {
arrayR[j] = array[q + j + 1];
}
cout << "TEST ARRAY MS B: ";
for (int count = 0; count < n2; count++) {
cout << arrayR[count] << " ";
}
cout << endl << endl;
//arrayL[n1 + 1] = 1000;
//arrayR[n2 + 1] = 1000;
//i = 0;
//j = 0;
for (int k = p, i = j = 0; k <= r; k++) {
if (j >= n2 || (i <= n1 && arrayL[i] <= arrayR[j])) {
array[k] = arrayL[i];
i++;
cout << "TEST ARRAY in loop A: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
else {
array[k] = arrayR[j];
j++;
cout << "TEST ARRAY in loop B: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
cout << "TEST ARRAY in loop: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
}
void mergeSort (int * array, int p, int r)
{
if (p < r) {
q = floor((p + r) / 2);
mergeSort(array, p, q);
mergeSort(array, q + 1, r);
merge(array, p, q, r);
}
}
int main(int argc, const char * argv[])
{
unsigned seed = time(0);
srand(seed);
int testArray[5];
populateArray(testArray, 5);
cout << "TEST ARRAY: ";
for (int count = 0; count < 5; count++) {
cout << testArray[count] << " ";
}
cout << endl << endl;
mergeSort(testArray, 0, 4);
cout << "TEST ARRAY after mergeSort: ";
for (int count = 0; count < 5; count++) {
cout << testArray[count] << " ";
}
cout << endl << endl;
return 0;
}