Breaking a double loop?

Hello,
I am trying to see if there is a nicer way to break out of a double loop. I have the code
1
2
3
4
5
6
7
8
9
10
11
RAND = double(rand())/RAND_MAX;
double cum = 0;
for (row=0; row<NSrv+1; row++) {
	for (col=0; col<NSrv+1; col++) {
		cum += R[row][col];
		if ( RAND < cum) {
			goto end_loop;
		}
	}
}
end_loop:

I basically have a normalized martix, I throw a random number then stp through each matrix element and add the components. Once the cumulative sum is greater than my random number I want to stop this so I know both the row and column where this occurs. What I have above works, it compiles fine. When I run it, it gives me all this garbage and crap about libraries I think, but it actually runs and works fine. Is there a better way to break out of a double loop? On another note, does anyone know a better random number generator for c++ rather than rand()? I find it crazy that it is not uniform (0,1) but rather uniform in (0,RAND_MAX)!
You can write is as a separate function and then use return.

For random generators you can read http://www.johndcook.com/cpp_TR1_random.html
Goto is just perfect for this job.. (I don't know why people hate it so much. With appropriate labels, its just so perfect for me at least). But if you want to eliminate it anyway.. you can do it as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
bool Loop = true;
RAND = double(rand())/RAND_MAX;
double cum = 0;
for (row=0; row<NSrv+1 && Loop; row++) {
	for (col=0; col<NSrv+1 && Loop; col++) {
		cum += R[row][col];
		if ( RAND < cum) {
                           Loop = false;
		}
	}
}

And about the random number thing, a simple random number generator can be built by using time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <iostream>
#include <ctime>
using namespace std;


int main()
{
    cout << "Random Number generator using clock()";
    while (true)
    {
        cout << clock()%20<<endl;
        cout << "Generate next random number?? (y/n)"<<endl;
        char ch;
        cin >> ch;
        if (ch=='n') break;
    }
    return 0;
}


> I am trying to see if there is a nicer way to break out of a double loop

IMHO, a goto is one of the nicest ways to break out of deeply nested loops. (In C++ where a break statement cannot specify which loop to break out of.)
(deleted - sorry, I'm stupid today)
Last edited on
You are making honor at your name, as you are only checking the diagonal.
(@ne555) LOL, I shouldn't try to answer these things late at night. x.x
Thanks everyone for the help. Actually, I figured out what was wrong and what it was complainign to me about and it had nothing to do with my goto statement. It had to do with something I did to either row/col when it was a certain value after breaking out of the double loop. I guess now that I know this works, I am happy with the goto statement as it is the easiest/cleanest way to do this! Thanks again
Topic archived. No new replies allowed.