I need some help solving this problem: This is in C++. Its asking to load an arr
ID: 3667036 • Letter: I
Question
I need some help solving this problem:
This is in C++.
Its asking to load an array of random numbers (NUM_ELEMENTS), display them( with 10 numbers in each row, and NUM_ELEMENTS rows) so an end line after 10 random numbers. Then I need to bubble sort them from least to greatest, and then redisplay it. Heres what I have so far:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std:
#define NUM_ELEMENTS 100
void loadData(int * data[]){
srand( time(NULL) );
for(int i=0; i<NUM_ELEMENTS; i++){
int number = rand() % 1000+1;
data[i]=number;
}
}
void sort (double data, int NUM_ELEMENTS)
{
for (int i = 0; i < NUM_ELEMENTS; i++)
{
for (int j = 0; j < i; j++)
{
if(data[i] < data[j])
{
double temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
}
void display(int data){
int c=0;
for (int i=0, i<NUM_ELEMENTS, i++){
if( ){
c=0;
cout<<endl;
}
cout<<data[i]<<","<<" ";
c++;
}
}
int main() {
int data[NUM_ELEMENTS];
loadData(data);
display(data);
sort(data);
display(data);
}
Explanation / Answer
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
#define NUM_ELEMENTS 100
void loadData(int* data){
srand( time(NULL) );
for(int i=0; i<NUM_ELEMENTS; i++){
int number = rand() % 1000+1;
data[i]=number;
}
}
void sort (int* data)
{
for (int i = 0; i < NUM_ELEMENTS; i++)
{
for (int j = 0; j < i; j++)
{
if(data[j] > data[j+1])
{
int temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
}
}
}
printf(" Elements are sorted ");
}
void display(int* data){
for (int i=0; i<NUM_ELEMENTS; i++){
if(i%10==0)
cout<<endl;
cout<<data[i]<<","<<" ";
}
cout<<" ";
}
int main() {
int data[NUM_ELEMENTS];
loadData(data);
display(data);
sort(data);
display(data);
}