### Creating a message with each value

I created a program to generate 3 random numbers, but I can't figure out to get a message to go with them. Being as they're random, do I set a message for 1,2, and 3 as an int? If they weren't random it may be easier.

 ``1234567891011121314151617181920212223242526272829303132333435`` ``````#include #define MAX_NUM 4 using namespace std; void randnum() { int random; srand(time(NULL)); for(int i=1;i<4;i++) { random=rand()%MAX_NUM; cout<
I'm not sure exactly what you're asking. Do you want to display the same message next to each number, or do you want the message to change depending on what the number is?
I assume that each number will correspond with a specific message. One way is to use multiple if-else conditions, or a switch-case, but my preferred solution is to use a lookup table, in this case an array containing the different messages. Since the value of `random` may vary between 0 and 3, there are four possible messages.

 ``123456789101112131415161718192021222324252627282930`` ``````#include #include #include #include const int MAX_NUM = 4; using namespace std; void randnum() { srand(time(NULL)); string message[MAX_NUM] = { "Apple", "Orange", "Banana", "Grapefruit" }; for (int i=0; i<3; i++) { int random = rand() % MAX_NUM; cout << random << " " << message[random] << endl; } } int main() { randnum(); cin.get(); return 0; }``````

Notice the use of a constant rather than #define, this is the preferred method in C++.
Last edited on
Okay, thank you. I really appreciate the replies. You were correct about me needing a specific value for each random number, which really confused me when my professor gave me the assignment. After looking over you gave us it seems kind of easy to understand.
Topic archived. No new replies allowed.