Limiting possibilities with string arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Caffiend
    New Member
    • Jan 2007
    • 21

    Limiting possibilities with string arrays

    Hello again! I am still having problems with the code under the title "newbie woes", but I have moved on for now to another exercise. The book has asked me to write a program that will use two string arrays to select a toy out of a bag, a ball or cube in 1 of four colours. There should also only be one ball and cube for each colour, which is that part I am having problems with. Also, I am not very clear on how this code works, I will comment it and if you could let me know if I am on the right track, that would be great! So here is my code so far:

    Code:
    #include <iostream> // Is this just to allow the basic C++ code?
    #include <stdlib.h> // Not sure what this header does
    #include <time.h>  // I think this allows me to use the computer's clock 
    #include <math.h> // I think this allows me to use mathematical symbols such as *, /, ==, +, - etc... 
    using namespace std; // Not sure what this does, I just put it in every program like a good little boy...
    
    int rand_0toN1(int n); // declares function "rand_0toN1" multiplied by integer "n"
    void toy_ball_cube(); // dec;ares function "toy_ball_cube" that does not return a value
    
    char *colour[4] = {"red", "blue", "orange", "green"}; // A string array for the four colours
    char *shape[2] = {"ball", "cube"}; // A string array for the two shapes
    
    int main() {  // Begins obligatory "main" function
        int n, i; // declares integers n and i
        
        srand(time(NULL));  // Does this create a random seed from the clock time 
                            // multiplied by a null value? Could I use "1" in place of "NULL"? 
        
        while (1) {  //  I understand the concept of a while loop, but the 1 I don't get
              cout << endl;
              cout << "Enter no. of toys to take out (enter 0 to exit): ";
              cin >> n;
              if (n == 0)  
                 break;
              for (i = 1; i <= n; i++) // for loops confuse me
                 toy_ball_cube();
              }
        return 0;
        }
    
    
    /* The last two functions I don't understand, I just know that the code works */
    void toy_ball_cube() {
         int c;
         int s;
         
         c = rand_0toN1(4); 
         s = rand_0toN1(2);
         cout << "It is a " << colour[c] << " " << shape[s] << endl;
         }
    
    int rand_0toN1(int n) { 
        return rand() % n;
    }
Working...