Hi, I'm a complete noob to computer programming and finding my 5th assignment very difficult. Sorry this is so long!
I've been asked to:
Write a program that:
•1) Creates an array containing 100 random double numbers in the [0,250) range;
•2) Sorts them in descending order;
•3) Prints the contents of the sorted vector out. The sorting should be coded as a separate function double* sort_array(double* ).
So far, i've created a program that looks like this, however it doesn't include a seperate sorting array as i don't know how to do it and instead of arranging in a descending order, it arranges it in an ascending order. If someone could teach me how to include this sorting array i'd be grateful!
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
double nums[100];
int a, b, t;
double size=100;
for (t=0; t<size; t++) { nums[t] = (double)(rand()%250); }
for (t=0; t<size; t++) cout << nums[t] << " ";
cout << "\n";
cout << "\n";
cout << "I will now rearrange these numbers in a descending order: \n";
cout << "\n";
for (a=1; a<size; a++) {
for (b=size-1; b>=a; b--) {
if (nums[b-1] > nums[b]) {
t = nums[b-1];
nums[b-1] = nums[b];
nums[b] = t;
}
}
}
ALTERNATIVELY: I got help from a programmer, who gave me this program, however some variables weren't declared and when i tried to declare them myself, the program did not have 100 sorted descending numbers.
This is the program!
delete[] arr; //deallocate array from memory, not needed but good practice
return 0;
}
//used for debugging to display the array of doubles
void printarr(double* myarray)
{
for (size_t i = 0; i < 100; i++)
cout << myarray[i] <<endl;
}
//function creates and returns an array initialized with 100 random doubles
double* create_array()
{
double* myarray = new double[100];
for (size_t i = 0; i < 100; i++)
// myarray[i] = (double)(rand()/250.0);
myarray[i]= ((double)rand()/(double)(RAND_MAX+1)) + rand()%249;
Change if (nums[b-1] > nums[b]) to if (nums[b-1] < nums[b]) .
Why do you want a separate array to sort in? Looks to me like the instructions want you to make the sorting code a separate function, but don't demand making any extra arrays.