Getting the same number even after using srand function.

Hi. So I was trying to create a very simple code where it would randomly generate 10 different values. But despite using the srand function I'm still getting the same input over and over again.
Here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <time.h>
using namespace std;

int main()
{
	int srand(time(NULL));	
	int i = rand() % 10 + 1;

	for (int counter = 0; counter < 10; counter = counter++)
	{
		cout << i << endl;
	}

	return 0;

}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
// #include <time.h>
#include <ctime>
// using namespace std;

int main()
{
        // int srand(time(NULL));	// *** create an integer called srand
	std::srand( std::time(nullptr) ); // call the function std::srand
	// int i = rand() % 10 + 1;

	for (int counter = 0; counter < 10; ++counter )
	{
	    // generate a new pseudo random number each time through the loop (?)
	    const int i = rand() % 10 + 1;
	    std::cout << i << '\n' ; // endl;
	}

	// return 0; // there is an implicit return 0 at end of main
}
Generating random numbers using the C++ <random> library:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <random>
// http://www.cplusplus.com/reference/random/

int main()
{
   // let's create a C++ random engine and seed it
   std::default_random_engine rng(std::random_device {}());

   // let's create a distribution that generates random numbers between 1 - 10 inclusive
   std::uniform_int_distribution<int> dis(1, 10);

   for (int i { }; i < 10; ++i)
   {
      std::cout << dis(rng) << ' ';
   }
   std::cout << '\n';
}

This isn't the only way to generate random numbers in C++, <random> has quite a number of facilities available. Including generating floating point numbers.
The reason you must put rand() % 10 + 1 inside the for loop is because C++ doesn't work like Excel. Excel let's you assign a formula to a cell and updates the value as needed based on the formula. In C++, the program evaluates the expression when encountered and assigns the resulting value to the variable. The value of the variable doesn't change until you assign something else to it.
Topic archived. No new replies allowed.