So I posted this earlier to receive OOP help with my code, but I dropped the Object Oriented programming aspect. My goal is to create an array of ten random integers and sort them in order. Problem is, we need to do this in 3 different languages. I only know Java and BASIC. C++ is new to me. I have everything working on my code EXCEPT that I don't get new numbers when I run the code:
#include <iostream>
usingnamespace std;
int sort ();
int arrayValue;
int array [10];
int temp;
/**
* Compares the value of two elements in myArray[]
* and sorts them in order by value
*/
int sort ()
{
for(int y = 0; y < 10; y ++)
{
for(int j = 0; j < 10; j ++)
{
if (array[j+1] > array[j])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for(int t = 0; t < 10; t ++)
{
cout << array[t];
cout << " ";
}
while(1);
}
/**
* The main () method starts everything
*/
int main ()
{
for(int x = 0; x < 10; x ++)
{
array[x] = rand() % 100;
cout << array[x];
cout << " ";
}
cout << " ";
sort (); // Runs the sort () method
}
Any suggestions on how to create new numbers when I run this?
P.S Remember I am very new to C++
// Random array numbers.cpp : main project file.
#include <iostream>
#include <ctime>
usingnamespace std;
int sort ();
int arrayValue;
int array [10];
int temp;
/**
* Compares the value of two elements in myArray[]
* and sorts them in order by value
*/
/**
* The main () method starts everything
*/
int main ()
{
srand((unsigned) time(0)); // To use the random function and get
// different numbers, using time
cout << endl << endl << "Unsorted numbers in array" << endl;
for(int x = 0; x < 10; x ++)
{
array[x] = rand() % 100;
cout << array[x];
cout << " ";
}
cout << " ";
sort (); // Runs the sort () method
}
int sort ()
{
for(int y = 0; y < 10; y ++)
{
for(int j = 0; j < 9; j ++) // Needs to be 1 less than array size
// else array out of bounds with j+1
{
if (array[j+1] > array[j])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
cout << endl << endl << "Sorted numbers in the array" << endl;
for(int t = 0; t < 10; t ++)
{
cout << array[t];
cout << " ";
}
cout << endl << endl;
return 0;
}
#include <ctime> //included for time(NULL)
#include <iostream>
#include <cstdlib> //included for rand and srand functions
usingnamespace std;
int sort ();
int arrayValue;
int array [10];
int temp;
/**
* Compares the value of two elements in myArray[]
* and sorts them in order by value
*/
int sort ()
{
for(int y = 0; y < 10; y ++)
{
for(int j = 0; j < 10; j ++)
{
if (array[j+1] > array[j])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for(int t = 0; t < 10; t ++)
{
cout << array[t];
cout << " ";
}
while(1);
}
/**
* The main () method starts everything
*/
int main ()
{
srand(time(NULL)); //randomizes seed based on time
for(int x = 0; x < 10; x ++)
{
array[x] = rand() % 100;
cout << array[x];
cout << " ";
}
cout << " ";
sort (); // Runs the sort () method
}
For more information, http://www.cplusplus.com/reference/cstdlib/srand/