Search code examples
c++randomintegersrandtime.h

Random Number generator to output numbers in ascending order


To start with, l'm an early beginner programmer and would like some help with this please.

I have written the following code, which from what l have tested generates:

  • 5 random numbers between: 1 and 39 //num1gen to num5gen - e.g.group A
  • 1 random number between: 1 and 14 //Thunderball - e.g.group B

I only want to cout<< the group A numbers in ascending order and l am not sure what coding is required to add this feature.

I still need the random numbers generated to be placed in the integer names shown below:

i.e

  • num1gen = 12
  • num2gen = 24
  • num3gen = 3
  • num4gen = 5
  • num5gen = 32
  • Thunderball = 12

ERROR: ISO C++ Forbids deceleration of 'i' with no type [-fpremissive] on line 16.

The code l have done so far with the help of the users below:

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <algorithm>

using namespace std;

int main()

{

 srand(time(NULL));

std::vector<int> numA(5);
srand( time(NULL) );
for( auto i(0); i < numA.size(); ++i )    //line no 16 error
numA[i] = (rand()%49+1);

  int num1gen=(rand()%49+1);    // this is the value of ball no.1
  int num2gen=(rand()%49+1);    // this is the value of ball no.2
  int num3gen=(rand()%49+1);    // this is the value of ball no.3
  int num4gen=(rand()%49+1);    // this is the value of ball no.4
  int num5gen=(rand()%49+1);    // this is the value of ball no.5


    std::sort(numA.begin(), numA.end());

num1gen=numA[0];
num2gen=numA[1];
num3gen=numA[2];
num4gen=numA[3];
num5gen=numA[4];

 cout<<num1gen<< ", "<<num2gen<< ", "<<num3gen<< ", "<<num4gen<< ", "
 <<num5gen<< " ";"

    return 0;
  }

Solution

  • If you create the numbers in A as a vector, there is an algorithm header with sort, so somthing like:

    #include <vector>
    #include <algorithm>
    
    int main() {
        std::vector<int> numA(5);
        srand( time(NULL) );
        for( unsigned int i(0); i < numA.size(); ++i )
            numA[i] = (rand()%49+1);
    //After you create the vector and do your test that they're not equal
        std::sort(numA.begin(), numA.end());
    
        return 0;
    }
    

    The std::sort() is included in the #include <algorithm> header.