Random function in C/C++

Below is a program that uses the random function .

 

Image Image

 

 

#include <stdlib.h>

#include <stdio.h>

int main()
{
int secret;  //declaration for variable “secret”
srand (time(NULL));  // initialize random function
secret = rand() % 10+1;  // variable is assigned a value
printf(“%d”,secret);  //dipslay the variable’s value on the screen
return 0;
}

Let’s explain what happens when I write “secret=rand()%10+1;”

If I wrote   secret=rand();   the program will display any number between  -231 and +231  

(because the number was declareted integer (int) and there are the limits for integer)

%10 is the function which give the rest of the divizion at 10 ; this function is avabile for each number. In this case we have %10 = the last digit of the number (it can be between 0 and 9) . At the result we add 1 , that means the random number which will be display, will be between 1 and 10.

// means commnent – you can run the program with coments

 

 

Read and try to aply this function 😉 !

Advertisements

One thought on “Random function in C/C++

  1. Pingback: brianendres50

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s