Answer to Question #295408 in C++ for Robot

Question #295408

You work in a printing office that the machine there can print documents in different colors. It gets an integer number between 1 to 7 and prints the documents in rainbow colors, as shown in the following table:

Number Matched Color

1 ----- red

2 ----- orange

3 ----- yellow

4 ----- green

5 ----- blue

6 ----- indigo

7 ----- violet

Design an algorithm and write a C++ program to do the following:

  • Prompt user to enter a number between 1 and 7
  • Use selection structure such as if-else or switch to find the color based on the previous table
  • Output the color related to input number. See the sample output.
  • Save the output in a file named “color.txt”.
1
Expert's answer
2022-02-08T16:26:41-0500

Algorithm:

  1. Print the prompt
  2. Read the code
  3. Select color according to the code
  4. Display output
  5. Open output file as a file stream
  6. Save output to the file stream
  7. Close file stream


Program:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

int main() {
    int code;
    string color;

    cout << "Enter a number between 1 and 7: ";
    cin >> code;

    switch (code) {
        case 1:
            color = "red";
            break;
        case 2:
            color = "orange";
            break;
        case 3:
            color = "yellow";
            break;
        case 4:
            color = "green";
            break;
        case 5:
            color = "blue";
            break;
        case 6:
            color = "indigo";
            break;
        case 7:
            color = "violet";
            break;
        default:
            cout << "Incorrect color number";
            exit(1);
    }

    cout << "Selected colr is " << color;

    ofstream fout("color.txt");
    fout << color << endl;
    fout.close();

    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