Is it possible to loop a switch?

Pages: 12
can someone please help with this?
I'm at work.

I'll check this when I get home. Give me a few hours.
Thanks
Okay so the goal here is to step through this code and find out why it's doing what it's doing.

Let's start at these loops:

1
2
3
4
5
6
7
for( m=1; m<100; m++)
{
  for(n=1; n<100; n++)
  {
  // ... CODE
  }
}


Do you understand what this code is doing?

The 'm' for() loop will loop 99 times, each time it will run the 'n' loop which also runs 99 times.

In effect, you're running the 'CODE' 99*99 = 9801 times.

This has a similar effect as:

1
2
3
4
for(m = 0; m < 9801; ++m)
{
  //  CODE
}


The only differences are the values of 'm' and 'n' -- but you're not using either of those in CODE anyway, so that's moot.


Ask yourself what behavior it is you're looking for. Once you outline the behavior you can break it up into steps and write the code for each of those steps.

1) You want to generate a random number
2) After a number is generated, you want to print all the generated numbers up to this point (including previous numbers)
3) Then you want to repeat until X condition is met (still unsure when you want this program to exit -- right now it looks like you're just generating thousands of numbers)

So the next question is... how do you do each of those steps?

Generating a random number is pretty easy... but how about printing all the previously generated numbers? Here's a hint: you'll need to record the numbers somehow. Either in an array or in some other container like I explained in my earlier post.

Think about it... if all the numbers were in an array... could you print them? What if you had the following assignment:

1
2
3
4
5
6
7
8
9
10
11
12
13
void OutputArray( ostream& out, int numbers[], int count )
{
  // write this function
  // 'out' is the stream to print to
  // 'numbers' is the array containing the numbers you want to output
  // 'count' is the size of the numbers array (ie:  the number of numbers to output)
}

// -- or if you prefer vector to an array you can write this function instead:
void OutputArray( ostream& out, const vector<int>& numbers )
{
  // ...
}


Get that function written and working properly. You can test it with simple code to make sure it's working right... like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
  ofstream outfile ("readers.txt",ios :: out);

  // if using the array function
  int testarray[5] = {6,2,4,3,1};

  OutputArray(outfile,testarray,5);

  // if using the vector function
  vector<int> testvec(5);
  testvec[0] = 6;
  testvec[1] = 2;
  testvec[2] = 4;
  testvec[3] = 3;
  testvec[4] = 1;

  OutputArray(outfile,testvec);

  return 0;
}


Once you have that working, you might have a better idea of how to do the rest of it.
Last edited on
Topic archived. No new replies allowed.
Pages: 12