C++ for loop problem, last value negative Help

This program randomly generates a number between 1 to 10.
These numbers will be added to 100, 200, 300 ... 1000. repesctively.
The problem is that the last value is negative.
Why is the last result always negative? :(

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <time.h>
using namespace std;
struct tai
{
int seat;

}student[10];

void main()
{
	srand(time(NULL));
int seat_number;
int value[10];
int temp=10;
    for (int i = 0; i < temp; i++)
{
        bool check;

        do
{
            seat_number = (rand() % temp) + 1;

            check = true;

            for (int j = 0; j < i; j++)
				if (seat_number == value[j]){

                    check = false;
                    break;
				}

} while (!check);
        value[i] = seat_number;

}

   for (int temp = 1; temp <= 10; temp++)
{
        int comp_code;

        comp_code = temp + (100 * value[temp]);
        student[temp].seat = comp_code;

        cout << comp_code << endl;
}
}
1
2
for (int i = 0; i < temp; i++) //line 16
for (int temp = 1; temp <= 10; temp++) //line 38 
explain the differences
Last edited on
1st for loop: generates 10 random numbers between 1 to 10 without repetition.
2nd for loop: generates 10 numbers between 1 to 10 in ascending order.

I use the formula:

first loop integer + (100 * second loop integer)

so what it does is that it displays 10 numbers from 100 to 1000 (in multiples of 100) with its first two digit (from the right) representing the randomly generated numbers from the 1st for loop.

possible outcome:

103
204
301
408
506
609
702
805
910
1007 (last result)

the problem is that the last result always gives a negative result.

also, I use the same temp variable in both for loops which I initialize with a value of 10.

first loop starts at 0 and stops at 9
second loop starts at 1 and stops at 10

Both try to traverse the same array, but the second loop will make an out-of-bounds access.
Topic archived. No new replies allowed.