read in numbers into array print out sort my program reads
read in numbers into array , print out, sort - my program reads in and prints out but crashes before the sort - crashes after it prints out the scores - *important I have to use pointers!!!! c++
#include <iostream>
using namespace std;
void sortarray(int *tarray, int );
void displayarray(int *[], int);
void averageshowarray(int *[], int);
int main()
{
int Size;
int count;
cout << \"enter the size: \" << endl;
cin >> Size;
int *valptr = new int[Size];
for(count = 0; count < Size; count++)
{
cout << \"Enter Test scores: \" << endl;
cin >> *(valptr + count);
}
for(count = 0; count < Size; count++)
{
cout << *(valptr + count) << endl;
}
//sort the array in order.
sortarray (valptr, Size);
// display the test scores and average.
//displayarray(valptr, Size);
//averageshowarray(&valptr, Size);
return 0;
}
void sortarray(int *b, int amount)
{
int startscan, minindex;
int *minelem;
for(startscan = 0; startscan < (amount - 1); startscan++)
{
minindex = startscan;
*minelem = b[startscan];
for(int index = startscan + 1; index < amount; index++)
{
if((b[index]) < *minelem)
{
*minelem = b[startscan];
b[startscan] = *minelem;
}
}
}
}
Solution
Working c++ code:
#include <iostream>
using namespace std;
void sortarray(int *tarray, int );
void displayarray(int *[], int);
void averageshowarray(int *[], int);
void sortarray(int *b, int amount)
{
int startscan, minindex;
int *minelem;
for(startscan = 0; startscan <= (amount - 1); startscan++)
{
minindex = startscan;
minelem = &(b[startscan]);
for(int index = startscan + 1; index <= amount-1; index++)
{
if((b[index]) < *minelem)
{
minindex = index;
minelem = &(b[index]);
}
}
int tmp = b[startscan];
b[startscan] = *minelem;
b[minindex] = tmp;
}
cout << \"Sorted Array is \" << endl;
for(startscan = 0; startscan <= (amount - 1); startscan++)
{
cout << b[startscan] << endl;
}
}
int main()
{
int S;
int count;
cout << \"enter the size: \" << endl;
cin >> S;
int *valptr = new int[S];
for(count = 0; count < S; count++)
{
cout << \"Enter Test scores: \" << endl;
cin >> *(valptr + count);
}
cout << \"Input Array is \" << endl;
for(count = 0; count < S; count++)
{
cout << *(valptr + count) << endl;
}
//sort the array in order.
sortarray (valptr, S);
// display the test scores and average.
// displayarray(valptr, S);
//averageshowarray(&valptr, Size);
return 0;
}
Sample Output:
enter the size:
5
Enter Test scores:
2
Enter Test scores:
3
Enter Test scores:
1
Enter Test scores:
5
Enter Test scores:
4
Input Array is
2
3
1
5
4
Sorted Array is
1
2
3
4
5


