Error in program.

This is the basic code i need. Im trying to generate 30 random numbers under 100, put them in an array...then find the max value in the array. When i run this program, it works, however it returns 42 everytime, which is a problem for me. Any help is appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cstdlib>	
#include <ctime>
using namespace std;

int main()
{
	int max = 0;
	int num[30];

	
	srand(1);

	for (int num = 0; num < 30; num++)
	{
		num = rand() % 100 + 1;
		
		max = num;
		
	if (num > max) max = num;

		cout << max << " ";
	}

	
	
	 return 0;
}
	
I think you posted that same problem at least 5 times...
Line 16 is modifying 'num' used in the loop, not the array.
Line 18 will make line 20 always evaluate false in the if
How can I fix it.
Sorry for asking a question inside of a question, but what is the bracket symbol used for? It's on line 9.

int num[30];
Also srand(1) seeds the random number generator the same every time, so it will produce the same set
of random numbers every time.

srand( time( 0 ) );

@ xitan :
That is declaring an array, see http://www.cplusplus.com/doc/tutorial/arrays/
Line 16 is modifying 'nym' used in the loop, not the array.

What he means is that this is an example of name hiding. If you create a variable in an outer block of code, in this case main(), and then declare another variable in an inner block of code, in this case your for loop, the variable in the inner loop 'hides' the variable in the outer loop in order for you to use it. I would read up on arrays again though as your for loop is incorrect in how you are trying to assign numbers (link above).

Also, when you think about it, line 18 and 20 means tha 'max' will always contain the new value of 'num'.
Topic archived. No new replies allowed.