-2

I'm trying to convert a for loop to while loop in c++ and do some checking for duplicates in a random number generator for generating lotto numbers so far all the stuff i'm trying seems to make the compiler very unhappy and I could really use a few pointers. It's the for loop in the Harray() function that feeds the Balls[] array that i want to convert to a while loop.

#include<iostream>
#include<cstdlib>  // to call rand and srand.
#include<ctime>    // to make rand a bit more random with srand(time(0)) as     first call. 
#include<iomanip>  // to manipulate the output with leading 0 where neccesary.

using namespace std;

// Hrand() function create and return a random number.
int Hrand()
{
    int num = rand()%45+1;  // make and store a random number change 45 for more or less Balls.
    return num;             // return the random number.
}

// Harray() function create and fill an array with random numbers and some formatting.
void Harray()
{
    int Balls[6];  // change the number in Balls[6] and in the for loop for more or less nrs. a row. 
    for(int x=0; x<=6; x++)  //the loop to fill array with random numbers.
    {
        int a;           // made to pass the Balls[x] data into so i can format output.
        int m = Hrand(); // calling the Hrand() function and passing it's value in int m.
        Balls[x] = m;    // throwing it into the array tought i did this because of an error.
        a = Balls[x];    // throwing it into int a because of an type error.
        cout<<"["<<setfill('0')<<setw(02)<<a<<"]";  //format output with leading 0 if neccesary.


    }
    cout<<endl;      // start new row on new line.
}
// Main function do the thing if compiler swallows the junk.
int main()            // start the program.
{
    int h;            // int to store user cchoice.
    srand(time(0));   // make rand more random.

    cout<<"How many rows do you want to generate?"<<endl; // ask how many rows?
    cin>>h;                                       // store user input.
    for(int i=h; h>0; h--)   // produce rows from user input choice.
    {
        Harray();            // calling Harray function into action.
    }
    return 0;                // return zero keep the comipler happy.
}  

I would like to always have six diffrent numbers in a row but i don't see how to get there with the for loops i think the while loop is way to go but am open to any suggestion that will work. I'm just starting with c++ i might have overlooked some options.

Hugo
  • 11
  • 2
  • 1
    Possible duplicate of [For vs. while in C programming?](https://stackoverflow.com/questions/2950931/for-vs-while-in-c-programming) – Kevin Dec 02 '17 at 18:57
  • 1
    `x<=6;` -> `x<6;`. Arrays are 0-based and so your last valid index is 5. Accessing element at index 6 invokes *undefined bebavior* – UnholySheep Dec 02 '17 at 18:59

3 Answers3

0
int x=0;
while(x<6)
{
    int a;format output.
    int m = Hrand();value in int m.
    Balls[x] = m;   because of an error.
    a = Balls[x];   
    cout<<"["<<setfill('0')<<setw(02)<<a<<"]";
    x++;
}

Here, I also fixed a bug. Since Balls has 6 elements, the last element will be 5. Thus you want x<6 instead of x<=6. That goes for the for loop too.

One drawback of while loops is that you cannot declare local variables with them.

klutt
  • 30,332
  • 17
  • 55
  • 95
0

First of all, you should realize that the difference between a for loop and a while loop is mostly syntactic--anything you can do with one, you can also do with the other.

In this case, given what you've stated as your desired output, what you probably really want is something like this:

std::vector<int> numbers;
std::set<int> dupe_tracker;

while (dupe_tracker.size() < 6) {
    int i = Hrand();
    if (dupe_tracker.insert(i).second)
        numbers.push_back(i);
}

The basic idea here is that dupe_tracker keeps a copy of each number you've generated. So, you generate a number, and insert it into the set. That will fail (and return false in retval.second) if the number is already in the set. So, we only add the number to the result vector if it was not already in the set (i.e., if it's unique).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Also thank u for taking the time to try and help me out haven't got around to trying the code snippet yet but from reading over it seems like it should do exactly what i was going for yeah. – Hugo Dec 03 '17 at 07:10
-1

How convert for-loop to while-loop

#include <iostream>

class T545_t
{
   // private data attributes
   int j;

public:

   int exec()
      {
         // A for-loop has 3 parameters, authors often fill 2 of them with magic
         // numbers.  (magic numbers are usually discouraged, but are expected
         // in for-loops)

         // Here, I create names for these 3 for-loop parameters
         const int StartNum  = 2;
         const int EndNum    = 7;
         const int StrideNum = 2;

         std::cout << std::endl << "  ";
         for (int i = StartNum; i < EndNum; i += StrideNum ) {
            std::cout << i << "  " << std::flush;
         }
         std::cout << std::flush;


         // A while-loop must use / provide each of these 3 items also, but
         // because of the increased code-layout flexibility (compared to
         // for-loop), the use of magic numbers should be discouraged.

         std::cout << std::endl << "  ";
         j = StartNum;
         do {
            if (j >= EndNum) break;
            std::cout << j << "  " << std::flush;
            j += StrideNum;
         } while(true);
         std::cout << std::flush;


         std::cout << std::endl << "  ";
         j = StartNum;
         while(true) {
            if (j >= EndNum) break;
            std::cout << j << "  " << std::flush;
            j += StrideNum;
         }
         std::cout << std::flush;

         std::cout << std::endl << "  ";
         j = StartNum;
         while(j < EndNum) {
            std::cout << j << "  " << std::flush;
            j += StrideNum;
         }
         std::cout << std::endl;


         return 0;
      }
}; // class T545_t

int main(int , char** )
{
   T545_t   t545;
   return(t545.exec());
}

Ask me where 'j' is declared?

This code is marked as C++, so in this case, I have declared 'j' in the private data attribute 'section' of this class definition. That is where you'd look for it, right?

If your c++ code does not have class, what's the point?

2785528
  • 5,438
  • 2
  • 18
  • 20
  • That looks really neat. – Hugo Dec 02 '17 at 20:35
  • But that's beyond me still I just started playing around with c++ so i'm not al there yet just opened the book a week and half ago. But thanx for the pointer i'm gonna dive into it. – Hugo Dec 02 '17 at 20:37
  • @Hugo I have touched the code to include the rest of my code - all 'class' issues are minimally addressed. I encourage you to embrace user defined types, and practice with them at every opportunity. – 2785528 Dec 02 '17 at 23:02
  • Thank you very much for pointing me in that direction it seems from the first glances of reading some about it like some real solid advice. Greatly apriciated. – Hugo Dec 03 '17 at 07:05