I was wondering how i could set up a random number loop, but have it stop looping when it hits 1 or any other number i assign.

i use dev C++ compiler

//Damage Roller

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <conio.h>

using namespace std;

int main()

{
    srand(time(0));
    do{
    int randomNumber = rand();
    
    int die = (randomNumber%6)+1;
    cout<<"You hit for "<<die<<" damage"<<endl;
    
    getch();
}while(1);
    return 0;
}

Recommended Answers

All 4 Replies

The simplest method is to break when randomNumber is one of those values:

if ( randomNumber == 5 )
  break;

That gets a little tedious when the list of numbers to break on is long, but you can easily scale it up with a collection:

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <set>

int main()
{
  int init[] = { 1, 2, 5, 7, 9, 14, 18 };
  std::set<int> ignore ( init, init + 7 );

  srand ( (unsigned)time ( 0 ) );

  int r;

  do {
    r = rand();
    std::cout<< r <<'\n';
  } while ( ignore.find ( r ) == ignore.end() );
}

thanks for the help i got it working really good now, but is there a way to add up the randomNumbers you get after they are shown?

Of course. Just add them to a running total right after you print them. When the loop is done, you'll have a sum of all of the printed random numbers.

worked like a charm thanks so much

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.