Program 4 - Pick color Class Create a class that randomly pick a color from an array of colors: string colors[7]; Have the colors array and all functions defined in the class. Create and use a void setElement( index, "color") function to assign values to the array elements 0 to 6: red, orange, yellow, green, blue, indigo, violet. Have a function that prints out all the colors in the array. Have a function that randomly pick One color from the array and cout's the color. (Research Random number code) Run your Code - Produce the correct output and Turn it in for credit ---------------------------------------------------------------------------------------

Respuesta :

Answer:

#include<cstdlib>

#include<bits/stdc++.h>

#include<time.h>

using namespace std;

class Colors{

string colors[7];

public:

void setElement(int,string);

void printAllColors();

void printRandomColor();

};

void Colors::setElement(int index,string color){

colors[index] = color;

}

void Colors::printAllColors(){

cout << "Printing all the colors:\n";

for(int i=0;i<7;i++){

cout << colors[i] <<"\t";

}

}

void Colors::printRandomColor(){

srand (time(NULL));

int index = rand() % 7;

cout<< "\n\nThe random picked color:";

cout << colors[index] << endl;

}

int main(){

Colors color;

color.setElement(0,"red");

color.setElement(1,"orange");

color.setElement(2,"yellow");

color.setElement(3,"green");

color.setElement(4,"blue");

color.setElement(5,"indigo");

color.setElement(6,"violet");

color.printAllColors();

color.printRandomColor();

}

to get the random color we are using srand and rand function. we are using time as seed to srand() function,because every time the time is changed. And based on that we are using rand() function and doing mod with 7 with the random number to get the index between 0 to 6, as ut array size is 7(0 to 6).

In the setElement(int index,string color) method we are inserting the value of colors in the colors array based on index.

In the printAllColors() function we are printing all the colors in the array.

In the printRandomColor() er are printing any random color based on rand() function.

and in main() we are initializing the string array with colors and calling the functions.

Ver imagen ofentsemaphalla

Answer:

C++.

Explanation:

#include <iostream>

#include <stdlib.h>

#include <time.h>

//////////////////////////////////////////////////////////////////////

class Color {

private:

   string colors[7];

public:

   void setElement(int index, string color) {

       colors[index] = color;

   }

   void printColors() {

       for (int i = 0; i < 7; i++) {

           cout<<colors[i]<<endl;

       }

   }

   void randomColorPicker() {

       srand (time(NULL));

       int colorIndex = rand() % 6; // random number in the range of 0 to 6;

       cout<<colors[color_index]<<endl;

   }

};