please help with small practice program

the program is supposed to get numbers from the user into a dynamically allocated array, next it is support to use 2 other functions to sort and average said array, when input certain values into the array (1-8 for example) the array will display unsorted twice as opposed to once and then again but sorted. When i give the array different values it may only display the array once with or without the average displayed afterwards.


#include<iostream>
#include<ctime>
#include<iomanip>
#include <cstdlib>

using namespace std;


float* scores(int);
float avg(float*,int);
float * sort(float*,int);

int main(){

int num;

cout << "enter a number" << endl;
cin >> num;
cin.ignore();

float* ptr = scores(num);

for(int i=0;i<num;i++){
cout << *(ptr+i) << endl;
}


ptr = sort(ptr,num);

for(int i=0;i<num;i++){
cout << *(ptr+i) << endl;
}



float average = avg(ptr,num);

cout << average << endl;






return 0;
}

float* scores(int size){
const int derp = size;
float* ptr = new float[derp];
for(int i=0;i<size;i++){
cout << "enter an element" << endl;
cin >> *(ptr+i);
cin.ignore();
}
return ptr;
}


float avg(float* list,int size){
float total=0;
for(int i =0;i<size;i++){
total+= *(list+i);
}

return (total/size);

}


float* sort(float* list1,int size){
bool swap =false;
float hold;
do{

for(int i=0;i<size+1;i++){
if(*(list1+(i+1))>*(list1+i)){
hold = *(list1+i);
*(list1+i)=*(list1+(i+1));
*(list1+(i+1))=hold;
swap=true;
}
}


}while(swap);

return list1;
}
Last edited on
I tried running the code and the sort() function is an infinite loop. When sorting the array the variable swap might be set to true and then never changed(thus, the while(swap) is always true). I found this algorithm for sorting arrays: http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort
Here's the solution(only the sort function, the rest works just fine):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
float* sort(float* list1,int size){
    float hold;

    for (int j = 0; j < (size-1); j++)
    {
        for(int i=0; i < size - j - 1; i++)
        {
            if( *(list1+(i)) < *(list1+i+1) )
            {
                hold = *(list1 + i);
                *(list1+i) = *(list1 + (i+1));
                *(list1+(i+1)) = hold;
            }
            else if ( *(list1+i) == *(list1+i+1) ) // If two element are equal, don't swap them
            {
                *(list1 + i) = *(list1 + i + 1);
            }
        }
    }

    return list1;
}


Hope that helps!
Topic archived. No new replies allowed.