alexanderbowen alexanderbowen - 2 years ago 109
C++ Question

Can't fix with sorting program, and copying arrays?

This program i have started is supposed take in data and sort it then output it.

The problem i'm having is that when i sort the code and it gets outputted for some reason the first two values become 0's. I assume this is something wrong with my sort function but i can't figure it out. I also want to copy the values withing "data" to a different array "sortedata" but the way i have it setup just sets all the values to zero. Any help with these two problems?

If you try this yourself just know you have to enter in double so just 5 wont work it needs to be 5.0

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

//functions

void input(double data[], double size) {


//enter data
for (int i = 0; i < size; i++) {
cout << "Enter data element \n";
cin >> data[i];
}

//output original
cout << "Original Data: \n";

for (int i = 0; i < size; i++) {
if (i) {
cout << ", ";
}

cout << data[i];
}
cout << "\n";

}
void copy(double source[], double dest[], double size) {
for (int i = 0; i <= size; i++)
source[i] = dest[i];
}
void sort(double data[], double size) {

for (int i = 19; i >= 0; i--)
{
for (int i = 0; i< 10; i++)
{
if (data[i]>data[i + 1])
{

double temp = data[i + 1];

data[i + 1] = data[i];

data[i] = temp;

}
}
}

}
void display(double data[], double size) {

//output sorted

cout << "Sorted Data \n";

for (int i = 0; i < size; i++) {
if (i) {
cout << ", ";
}

cout << data[i];
}

}

int main()
{
//variables
bool check = true;
double size = 0;
double data[20] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
double sortedata[20] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };

//input
while (true) {

//input
cout << "Enter data item count <1-20> \n";
cin >> size;

//check
if (size < 1 || size > 20) {
cout << "Item count is NOT within required range. The required range is 1 to 20. \n" << "Bye \n";
break;
}

input(data, size);
break;
}
//copy
//copy(data, sortedata, size);

//sort
sort(data, size);

//display
display(data, size);

return 0;
}

Answer Source

Firstly, in copy function replace i <= size to i < size

Secondly, in sort function replace i < 10 to i < size - 1

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download