When I try to display the test scores in the function sortArray, I can only access the memory address. How to I access the values of the scores?? Also is the sortArray function correct overall?
#include <iostream>
using namespace std;
void sortArray(int *[], int);
int main()
{
int *testScores = nullptr;
//dynamically allocate an array
int scoreNUMS;
int score;
cout << "Please enter the total number of test scores" << endl;
cin >> scoreNUMS;
testScores = new int[scoreNUMS];
//dynamically allocates an array large enough to hold scoreNUMS
for(int i = 1; i <= scoreNUMS; i++)
{
cout << "Enter student " << i << "'s test score" << endl;
cin >> score;
if (score <= -1)
{
cout << "Please enter positive numbers only!" << endl;
}
*(testScores + i) = score;
//puts the input score in the array
}
sortArray(&testScores, scoreNUMS);
return 0;
}
Im not sure if the function below is correct because I was unaware where to place the * and the &
void sortArray(int *array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for(int count = 0;count < (size - 1); count++)
{
if(array[count] > array[count + 1])
{
temp = *array[count];
array[count] = array[count + 1];
array[count + 1] = &temp;
swap = true;
}
}
}while(swap);
for(int i = 0; i < size; i++)
cout << *(array + 1) << endl;
}
Error: Array consist scoreNUMS elements, the first one is testScores[0] - first index is zero. And last index is scoreNUMS-1
You must write
for(int i = 0; i < scoreNUMS; i++)
PS: You can use next prototype:
void sortArray(int [], int);
UPD: passing an array to a function is performed by passing a pointer to the first element of the array. (Your array does not copied when you pass it to function)
And run function by this way: sortArray(testScores, scoreNUMS);
Related
For an assignment for school, I need to create a program that takes one array and splices another into it, assigning the first X values of the first array into a new array, then all of the second, and then the rest of the first. It is also required that this is done by means of dynamically allocated arrays. I don't understand why, but for some reason, the heap is becoming corrupted and I can't figure out why. I am just now learning about pointers, so the solutions I have found don't make much sense to me.
If someone could point out exactly what I'm doing wrong, and explain it to me so that I can learn from my mistakes, I'd greatly appreciate it. Thanks!
#include <stdlib.h>
#include <iostream>
#include <time.h>
int* createArray(int);
int* splice(int[], int[], int, int, int);
void arrayPrint(int []);
using namespace std;
int main(void)
{
int firstLength, secondLength, copyLength;
cout << "Enter the length of the first array: ";
cin >> firstLength;
cout << "Enter the length of the second array: ";
cin >> secondLength;
cout << "Enter the length of the first array to be copied: ";
cin >> copyLength;
int* firstArray;
int* secondArray;
int* thirdArray;
srand(100);
firstArray = createArray(firstLength);
secondArray = createArray(secondLength);
firstArray = new int[firstLength];
for (int i = 0; i < firstLength; i++)
firstArray[i] = rand() % 100;
secondArray = new int[secondLength];
for (int i = 0; i < secondLength; i++)
secondArray[i] = rand() % 100;
thirdArray = splice(firstArray, secondArray, firstLength, secondLength, copyLength);
cout << "First Array: " << endl;
for (int i = 0; i < firstLength; i++)
{
cout << firstArray[i] << ", ";
}
arrayPrint(firstArray);
cout << endl << "Second Array: " << endl;
for (int i = 0; i < secondLength; i++)
{
cout << secondArray[i] << ", ";
}
arrayPrint(secondArray);
cout << endl << "Spliced Array: " << endl;
arrayPrint(thirdArray);
delete firstArray;
delete secondArray;
delete thirdArray;
system("pause");
return 0;
}
int* createArray(int arrayLength)
{
int* createdArray;
createdArray = new int[arrayLength];
for (int i = 0; i < arrayLength; i++)
createdArray[i] = rand();
return createdArray;
}
int* splice(int firstArray[], int secondArray[], int firstLength, int secondLength, int copyLength)
{
int* splicedArray;
splicedArray = new int[copyLength];
for (int i = 0; i < copyLength; i++)
{
splicedArray[i] = firstArray[i];
}
for (int j = 0; j < secondLength; j++)
{
splicedArray[j + copyLength] = secondArray[j];
}
for (int k = 0; k < firstLength - copyLength; k++)
{
splicedArray[k + copyLength + secondLength] = firstArray[k + copyLength];
}
return splicedArray;
}
void arrayPrint(int toPrint[])
{
for (int i = 0; i < sizeof(toPrint) / sizeof(*toPrint); i++)
{
if ((i % 10) == 9)
cout << toPrint[i] << endl;
else
cout << toPrint[i] << ", ";
}
}
Combining C_Raj's answer, vinodsaluja's and Wander3r's comments:
you are allocating first and second arrays twice, once is enough, actually more is memory leak (vinodsaluja).
Logically, since thirdarray is a combination of first and second arrays, its length should be sum of both array lengths, which is firstlength+secondlength not copylength. This is where heap corruption occurs (vinodsaluja).
Finally ararys should be deallocated with delete[] (Wander3r).
C_Raj's code is what the result should be so I'm not copying it.
I'm writing a program for an assignment in which the program stores grades in array, has a function that inputs the grades and stores them in an array and returns the number of grades, handles up to 20 grades, has a function that sorts the array of grades, and has a separate function that takes the sorted array and returns the median. I have the code written but it is not sorting the array. Not sure what I am doing wrong. Any help would be greatly appreciated.
#include <iostream>
using namespace std;
int main();
void bubbleSort(double[], int); //Function prototypes
void swap(double &, double &);
void findMedian(double[], int, int, int, int, int);
int main()
{
int numgrades; // the number of grades in the array
double grades[20]; // array of grades
int first = 0,
last,
middle;
double medianeven; // median if # of elements are even
double medianodd; // median if # of elements are odd
bool isEven(int); // determines if the #of elements is even
cout << "Please enter the number of grades. ";
cin >> numgrades;
for (int index = 0; index <= numgrades - 1; index++)
{
cout << "Enter test score "
<< (index + 1) << ":";
cin >> grades[index];
}
void bubbleSort(double grades[], int numgrades);
for (int index = 0; index <= numgrades - 1; index++)
{
cout << grades[index];
}
(((last) = (numgrades - 1)));
(((middle) = (first + last) / 2));
if (isEven(numgrades))
{
(medianeven = ((grades[middle] + grades[middle + 1]) / 2));
cout << "The median grade is +" << medianeven << "." << endl;
}
else
{
((medianodd = grades[middle]));
cout << "The median grade is -" << (medianodd) << "." << endl;
}
return 0;
}
void bubbleSort(double array[], int numgrades)
{
int minIndex;
double minValue;
for (int start = 0; start < (numgrades - 1); start++)
{
minIndex = start;
minValue = array[start];
for (int index = start + 1; index < numgrades; index++)
{
if (array[index] < minValue)
{
minValue = array[index],
minIndex = index;
}
}
swap(array[minIndex], array[start]);
}
}
void swap(double &a, double &b)
{
double temp = a;
a = b;
b = temp;
}
bool isEven(int number)
{
bool status;
if (number % 2 == 0)
status = true;
else
status = false;
return status;
}
In main
void bubbleSort(double grades[], int numgrades);
is a forward declaration of the bubbleSort function, not a call to it.
bubbleSort(grades, numgrades);
will call the function.
I have a task to create a program which makes array via user input and then in new function to create another array which only consists of even elements and then the result should be returned via pointer to the newly created array.
Bear in mind that I just started learning C++ so pointers here are not on spot.
#include <iostream>
using namespace std;
int* getEven(int *niz, int *n)
{
int i;
for(i = 0 ; i < *n ; i++)
{
if(niz[i] % 2 == 0)
cout << niz[i];
}
}
int main()
{
int n, i;
int *niz;
cout << "Enter positive and larger number than 50: ";
cin >> n;
if(n <= 50)
cout << n;
else
{
cout << "Error. Number is lower than 50." << endl;
abort;
}
niz = new int[n];
for(i = 0 ; i < n ; i++)
{
cout << "Enter next element:" << endl;
cin >> niz[i];
}
int *a = getEven(niz, n);
cout << endl;
cout << a[0] << endl;
system("pause");
return 0;
}
If you are intending to create a new array which might not contain all the elements from the first one, you need an additional parameter to keep track of the number of elements in the new array. Here is how you do it:
int* getEven(int *inputArray, int inputLength, int *outputLength)
{
int *outputArray = new int[inputLength];
*outputLength = 0;
for(int i = 0; i < inputLength; i++)
{
if(inputArray[i] % 2 == 0)
{
outputArray[*outputLength] = inputArray[i];
outputLength++;
}
}
return outputArray;
}
And here is an example on how to use it in main:
int outLen = 0;
int *a = getEven(niz, n, &outLen);
for(i = 0; i < outLen; i++)
cout << a[i] << endl;
Also, bear in mind that you will need to manually delete the dynamically allocated arrays to prevent memory leaks. This applies to the array created in the main function too. Therefore, you need to do this:
delete []niz;
delete []a;
#include <iostream>
using namespace std;
const int lab8 = 10;
int labArray[lab8];
void promptUser(int [], int);
void sortArray(int [], int);
void showArray(const int[], int);
int searchArray(const int [], int, int value);
int x = 0;
int results = 0;
int main()
{
promptUser(labArray, lab8);
sortArray(labArray, lab8);
showArray(labArray, lab8);
cout << "Choose an integer you want to search from the array: " << endl;
cin >> x;
results = searchArray(labArray, lab8, x);
if (results == -1) {
cout << "That number does not exist in the array. \n";
else
{
cout << "The integer you searched for was for at element " << results;
cout << " in the array. \n";
}
}
void promptUser(int numbers[], int size)
{
int index;
for (index = 0; index <= size - 1;index++ )
{
cout << "Please enter ten numbers to fill the array " << endl
<< (index + 1) << ": ";
cin >> numbers[index];
}
}
void sortArray(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size -1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
void showArray(const int array[], int size)
{
for (int count = 0; count < size; count++)
{
cout << "The array you entered when sorted was: ";
cout << array[count] << " ";
cout << endl;
}
}
int searchArray(const int array[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = - 1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
I am new to c++ and just working on an assignment for my class. I thought the program I wrote would have worked but for the life of me I can not figure out why it will not compile. I am sure I am missing something or not understanding how it should work completely. The errors I keep receiving are expected expression on line 26 by the 'else' statement and when I put the 'if' and 'else' statements in I started receiving function not allowed here errors. Any help would be greatly appreciated.
In the if statement, you open the bracket { but you never close it. Not sure if this is the problem but it should raise some issues.
if (results == -1) {
cout << "That number does not exist in the array. \n";
**}**
else
{
cout << "The integer you searched for was for at element " << results;
cout << " in the array. \n";
}
This is how it should look. Try it
Im trying to implement the Quick Select Algorithm on a Array that has randomly generated numbers. Now after writing the algorithm in code, it does not sort the array from lowest to highest nor am i able to find the kth smallest element. I would appreciate the help i get. Thank you.
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
void printArray(int *myArray, int n){
for(int i = 0; i < n; i++){
cout << myArray[i] << " ";
}
}
int Partition(int *myArray, int startingIndex, int endingIndex){
int pivot = myArray[endingIndex];
int partitionIndex = startingIndex;
for(int i = startingIndex; i<endingIndex; i++){
if(myArray[i]<= pivot){
swap(myArray[i],myArray[partitionIndex]);
partitionIndex++;
}
}
swap(myArray[partitionIndex],myArray[endingIndex]);
return partitionIndex;
}
int QuickSelect(int *myArray, int startingIndex, int endingIndex, int KthElement){
/*if(startingIndex < endingIndex){
int partitionIndex = Partition(myArray, startingIndex,endingIndex);
QuickSelect(myArray,startingIndex,partitionIndex-1);
QuickSelect(myArray,partitionIndex+1,endingIndex);
}*/1
if (startingIndex < endingIndex){
int partitionIndex = Partition(myArray, startingIndex, endingIndex);
if(KthElement == partitionIndex)
return KthElement;
if(KthElement < partitionIndex)
QuickSelect(myArray, startingIndex, partitionIndex - 1, KthElement);
else
QuickSelect(myArray, partitionIndex + 1, endingIndex, KthElement);
}
}
int main(){
int numOfElements;
int KthElement;
srand(time(NULL));
cout<<"Enter The Amount Of Numbers You Wish To Use: ";
cin >> numOfElements;
int myArray[numOfElements];
cout << "Array Before Sorting: ";
for(int i = 0; i< numOfElements; i++){
myArray[i] = rand() %10;
}
printArray(myArray, numOfElements);
cout << endl;
cout << endl;
cout <<"Enter The Index Of The Kth Element You Wish To Retrieve: ";
cin >> KthElement;
QuickSelect(myArray, 0,numOfElements,KthElement);
cout << "Array After Sorting: ";
printArray(myArray, numOfElements);
cout << endl;
cout <<"The " <<KthElement<<" Smallest Element Is: " << QuickSelect(myArray,0,numOfElements,KthElement);
}
For numOfElements as 5, array extends from 0 to 4.
Your endingIndex assumes that its the last index of the array.
Fix:
QuickSelect(myArray, 0,numOfElements-1,KthElement);
Problems with your code:
Your program accesses out of bound array locations in
int pivot = myArray[endingIndex];
Have a check for k<1 and k>(num_of_elements).
Check your code for num_of_elements = 1 as well.
Check what k means for the array, i.e For k=1 , arr[0] should be returned not arr[1];