Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my code srand is not working and i am getting same integar value every time loop runs.

What I have tried:

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
	string n;
	int len;
	int a,sum;
	int x[100];
//	cout <<"Enter credit card numbers\n";
//	cin>>n;
	for(int h=0; h<16;h++)
	{
		
  	srand(time(0));
  	x[h] = rand()%10;

	}
//	len=n.length();
for(int k=0; k<16; k++)
	{
		cout<<x[k]<<",";
	}
//		cout <<"Number is "<<n;
	cout <<endl;
}
Posted
Updated 22-Jan-22 22:43pm

1 solution

The problem is that modern processors are too fast for your code:
for(int h=0; h<16;h++)
	{
		
  	srand(time(0));
  	x[h] = rand()%10;

	}
Because they are fast, the calls to time(0) are all occurring in the same second, so the value passed to srand to initialize the random number generator is always the same, and it gets reset to the same sequence. So every time round the loop, you get the same random number (though a different number each time you run your program).

Move the call to srand outside the loop completely so the random number generator is only initialized once, and you will get different values when you call rand
 
Share this answer
 
v2
Comments
Hamza Jameel 23-Jan-22 4:47am    
Solved Thanks
OriginalGriff 23-Jan-22 5:33am    
You're welcome!
CPallini 23-Jan-22 5:24am    
5."he problem is that modern processors are too fast for your code"
I suppose that even the PDP-7 processor was fast enough... :-D
OriginalGriff 23-Jan-22 5:33am    
:DI was trying to be nice ... :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900