Short Circuit, rand() and srand() in C++

Short circuit evaluation is an evaluation in which the logical expression stops functioning as soon as the value of the expression is known.The logical expression is evaluated from left to right and the evaluation will stop as soon as the final true value of the expression is determined.

1. Lack of short circuit can create a problem :

               Index=1;
               while((Index < Listlen) && (list[Index] != Key))
                   Index = Index + 1;
              

If the expression does not contain a short circuit, then both operands "&&" are evaluated.

2. C++ use short circuit evaluation for common Boolean operators (& & & ||).



Example :

bool1 && bool2

The && operator in C ++ uses short-circuit evaluation so that if bool1 evaluates to false then it does not evaluate bool2.

rand() in C++

The rand () function is used to generate random numbers in C ++. The rand() function will generate a sequence of random numbers.The rand() function will create the same sequence again and again whenever we compile the program.So if we generated 10 random numbers using a loop, the same random number would be generated again when the program recompiled.

Syntax :

int rand(void): 
This will returns a pseudo random number in the range 0 to RAND_MAX.
RAND_MAX: Is a constant whose default value can vary between implementations but is given at least 32767.


Example :

#include <iostream>

using namespace std;

int main()
{
    
    for(int i = 0; i<5; i++) 
    cout<< rand()<<"\n";

    return 0;
}


Output :

453 
1276 
3425 
89
1004

srand() in C++

srand(unsigned) function is used to Sets the seed for rand.The srand() function sets the starting point for producing a series of pseudo-random integers.If there is no srand() function, the rand() seed is set as srand(1).

Syntax :

void srand( unsigned seed ): 
Seeds the pseudo-random number generator used by rand() 
with the value seed.


Example :

#include <iostream>

using namespace std;

int main()
{
     srand(time(0)); 
    for(int i = 0; i<5; i++) 
    cout<< rand()<<"\n";

    return 0;
}


Output :

453 
1276 
3425 
89
1004

Exercise:-

1. What is function srand(unsigned)?

A. Sets the seed for rand
B. Doesn’t exist
C. Is an error
D. None of the mentioned

View Answer


2. Which is the best way to generate numbers between 0 to 99?

A. rand()-100
B. rand()%100
C. rand(100)
D. srand(100)

View Answer



Program :-

srand() function with time()

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
  srand(time(0));
  int random = rand();
  cout << "Seed = " << time(0) << endl;
  cout << "Random number = " << random << endl;
return 0;
} 


Output :

Seed = 1485583981
Random number = 22589





Visit :


Discussion


* You must be logged in to add comment.