Answer to Question #161799 in C++ for Anonymous

Question #161799

Ask the user to enter the name of one primary color (red, blue, yellow) and a second primary color that is different from the first. Based on the user's entries, figure out what new color will be made when mixing those two colors. Use the following guide:

 

  • red and blue make purple
  • blue and yellow make green
  • yellow and red make orange


If the user enters anything that is outside one of the above combinations, return an error message.

 

Prompts:

Enter a primary color (red, blue, yellow): 

Enter a different primary color (red, blue, yellow): 

 

Possible Outputs:

red and blue make purple

blue and yellow make green

yellow and red make orange

You entered invalid colors

 

Notes and Hints:

1) The program should work regardless of the color order. In other words, it shouldn't matter if the user enters red or blue first...the two colors make purple.

2) Regarding #1, this means that the first three outputs shown above may appear with the colors in a different order. Hint: Use variables in your output to make this easy!

3) If the user has any uppercase letters, it will not work. This is normal, as C++ is case sensitive. We will solve this problem in a future in-class lesson.

 


1
Expert's answer
2021-02-09T08:30:32-0500
#include <iostream>
#include <string>

//returns true if given color is red, blue or yellow
bool isValid(std::string color) {
	if (color == "red" || color == "blue" || color == "yellow")
		return true;
	return false;
}

int main() {
	std::string color1, color2;
	std::cout << "Enter a primary color (red, blue, yellow): ";
	std::cin >> color1;
	std::cout << "Enter a different primary color (red, blue, yellow): ";
	std::cin >> color2;
	if (color1 != color2 && isValid(color1) && isValid(color2)) { //check if color1 and color2 are not the same while being red, blue or yellow
		if ((color1 == "red" && color2 == "blue") || (color1 == "blue" && color2 == "red"))
			std::cout << color1 << " and " << color2 << " make purple" << std::endl;
		else if ((color1 == "red" && color2 == "yellow") || (color1 == "yellow" && color2 == "red"))
			std::cout << color1 << " and " << color2 << " make orange" << std::endl;
		else //don't need to check for blue and yellow because we already checked for all other combinations
			std::cout << color1 << " and " << color2 << " make green" << std::endl;
	}
	else {
		std::cout << "You entered invalid colors";
	}
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog