Random function

I have a problem to understand how random function work in c++
how we can calculate the output of random function
1
2
3
4
5
6
7
8
9
10
11
12
13
  void main()
{
randomize();
int NUM;
NUM=random(3)+2;
char TEXT[]=”ABCDEFGHIJK”;
for (int I=1;I<=NUM; I++)
{
for (int J=NUM;J<=7;J++)
cout<<TEXT[J];
cout<<end1;
}
}

another code is
void main()
{
randomize();
int info,rundum;
cin>>info;
rundom = random(info)+9;
for(int n=1;n<=rundum-1;n++)
cout<<n;
}
Last edited on
There's no standard function randomize() and only a standard function long random(void). It seems you're using some proprietary library?
sir i am asking if this type of coding is given then how we can find the output without run the code on computer
the code is written above what will be the output how we can find
so plz help me to understand the random function and how it works by giving some example
Both random() and randomize() are Borland-style functions, though they may still be available on some modern compilers, they are not part of the standard.

This is what it might look like replaced by the standard C++ counterparts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand(time(NULL));       // replace randomize();
    
    int num;
    
    num = 2 + rand() % 3;    //  replace random()
    
    char text[]="ABCDEFGHIJK";

    for (int i=1; i<=num; i++)
    {
        for (int j=num; j<=7; j++)
            cout << text[j];
        cout << endl;
    }
}

typical output:
DEFGH
DEFGH
DEFGH


how we can find the output without run the code on computer

This is a good exercise, understanding how the code works without actually running it is a necessary skill.

I would though suggest you should also run the code on an actual computer to check whether it behaves as expected.

First, randomize() or srand() here are a way of giving a new seed to the random-number generator, so that each time the program runs the results will be different. (Though it uses the current time as a seed - if it was run more than once during the same second the output would not change).

That's the easy part, it can usually be taken for granted.


Function rand() generates a pseudo-random number in the range 0 to RAND_MAX. ( A range of at least 0 to 32767)

When we want a number within a smaller range we can use random(3) or rand()%3 which will give a result in the range {0, 1, 2 }

The rest of the code I leave for you to consider - please come back if you have further questions.

references - standard functions:
http://www.cplusplus.com/reference/cstdlib/rand/
http://www.cplusplus.com/reference/cstdlib/srand/
Topic archived. No new replies allowed.