### Simple array question

Hello,

I'm new to c++ and I'm having a play around with arrays and I'm trying to figure something out.

For this little game I'm trying to have it so that a random element of the array is selected and put into he variable 'Gold'. I'm scratching my head trying to figure out how to get it work.

So far I have: -

 ``123456789101112131415161718192021222324252627282930313233`` ``````// ChestTest1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "math.h" #include #include #include #include #include using namespace std; // Variables int Gold=0; int Chest[5]={10, 20, 30, 40, 50}; // Function void LootChest() { // Generates random number between 0-4 to give player when chest looted srand( (unsigned)time(0) ); int ChestRoll=0; ChestRoll=rand() % 5; } int main() { cout<<"The chest gave you "<

I'm not quite sure how to get the output of 'ChestRoll' to take that number element of 'Chest[]' and put it into the int called 'Gold'.

Any help or direction would be appreciated =)
Last edited on

First off, only set your seed once at the start of your program.

Basically grab a random number between 0 and 4, remember arrays start at 0. Use that number as an index to your array and get its number. i.e.

`result = Chest[ChestRoll];`

Last edited on
 ``1234567891011121314151617181920212223242526`` ``````#include #include int LootChest() { int chestRoll = rand() % 5; return chestRoll; } int main() { srand((unsigned)time(0)); int chest[5] = {10, 20, 30, 40, 50}; int gold = 0; int index = LootChest(); gold = chest[index]; // also could have done: // gold = chest[LootChest()] ; std::cout << "The chest gave you " << gold << " gold." << std::endl; return 0; } ``````
Last edited on
Make use of `return` keyword, and return looted gold from LootChest function.

 ``1234567891011121314`` ``````int Chest[5]={10, 20, 30, 40, 50}; int LootChest() { int ChestRoll=rand() % 5; return Chest[ChestRoll]; } int main() { srand( (unsigned)time(0) ); // only needed once per program life cout<<"The chest gave you "<< LootChest() <<" gold."<

Then you can think of going one step further - making function `int LootChest(int* Chest)` that you can use with different chests, containg different treasures:

 ``1234567`` ``````int CommonChest [] = {1, 5, 10, 20}; int NoblemanChest [] = {10, 50, 100, 200}; int EpicChest[] = {100, 500, 1000, 2000}; cout<<"The CommonChest gave you " << LootChest(CommonChest) <<" gold."<
Last edited on
That's great guys =)

I'll have a bit of a play around with all that.

Really appreciated, thanks again!
Topic archived. No new replies allowed.