Random number generation in C/C++ without library function

Sourav Sarker
2 min readMar 14, 2019

--

A typical way of generating random number is using the rand() function in cpp. But except this, i also got a sound idea of generating random numbers using dynamic memory allocation. It’s too easy.

generating 10 random numbers

#include<stdio.h>
#include<stdlib.h>

int main()
{

for(int i = 0; i< 10; i++)
{
int *p;
p = (int*)malloc(sizeof(int)); // (definition is lying under the code)
printf(“%d\n”,p);
}

return 0;
}

we just need to declare a integer type pointer. Then we need to dynamically allocate memory for it of it’s size. But dynamic memory allocation(malloc) returns a void pointer, that’s why we need to typecast it as (int*). Then, printing the p will give a random number every time.

Generating 10 random numbers within a limit ( 20-30)

#include<stdio.h>
#include<stdlib.h>

int main()
{

for(int i = 0; i<10; i++)
{
int *p;
p = (int*)malloc(sizeof(int)); // (definition is lying under the code)
int res = ((int)p%10)+20; // (definition is lying under the code)

printf(“%d\n”,res);
}

return 0;
}

The formula is as like as the code stated above except one thing. If we want to generate random number between 20 and 30; then we need to mod the random number with it’s limit difference (p%(10)), that means (30–20=10). It will find the random the number between 0 to 10 as p will provide a random number. Now, adding the lower limit ( p%10)+20 will give random number between 20 and 30 :D .

#Happy_coding.

--

--