11.0k views
5 votes
Write a program that sorts an array of 20 random numbersin the range from 0 through 1000.

User Ihm
by
6.0k points

1 Answer

6 votes

Answer:

#include<iostream>

#include<stdlib.h>

#include<time.h>

#include <algorithm>

using namespace std;

//main function program start from here

int main(){

//seed the rand() function

srand(time(NULL));

//initialization

int arr[20];

//generate the 20 random number

for(int i=0;i<20;i++){

arr[i]=rand()%1000; //store in array

}

sort(arr,arr+20); //sort the array by inbuilt function

cout<<"The sorted array is."<<endl;

//for display the each element in the array

for(int i=0;i<20;i++){

cout<<arr[i]<<endl;

}

}

Step-by-step explanation:

Create the main function and declare the array with size 20.

Take a for loop and generate the random number 20 times. For generating a random number, use the function rand();

rand() function which defines in the library stdlib.h, generate the random number within the range.

for example:

rand() % 20: generate the number between 0 to 19 ( Exclude 20).

for generating the random number different for every time, then we have to use srand() function and time function which defines in time.h library.

After that, store the number in the array.

Finally, take another loop and print all elements one by one.

User WillJones
by
6.4k points