Question: Help with global variable in C++ program using if/else if not the nested if-else statements. Define a global counter variable at the beginning of the

Help with global variable in C++ program using if/else if not the nested if-else statements.

Define a global counter variable at the beginning of the program. Increment this variable immediately before each condition that is checked.

With these changes the sample executions would look something like this:

Please input a visible wavelength: 495.6

Your wavelength corresponds to the color Blue.

You evaluated 4 conditional expressions.

Please input a visible wavelength: 795.6

Your wavelength is too large.

You evaluated 8 conditional expressions.

I have the program working until I uncomment the second global variable before the "else if" statement (i++;). Please help with global variable in else if statements.

CODE:

#include #include using namespace std; //Declare Global Variable int i = 0;

int main() { //Declare variable for user input int wavelength; //Prompt user for wavelength input cout << "Please enter a wavelength between 400 and 700" << endl; //Store user input in wavelength variable cin >> wavelength; //Add to global variable before comparison i++; if(wavelength < 400) { //Print wavelength output color cout << "The wavelength you inputted was too small." << endl; cout << "You evaluated " << i << " conditional expressions." << endl; return 0; } //Add to global variable before comparison //i++; else if (wavelength < 445) { //Print wavelength output color cout << "Your wavelength is Violet" << endl; cout << "You evaluated " << i << " conditional expressions." << endl; } else if (wavelength < 475) { //Print wavelength output color cout << "Your wavelength is Indigo" << endl; cout << "You evaluated " << i << " conditional expressions." << endl; } else if (wavelength < 510) { //Print wavelength output color cout << "Your wavelength is Blue" << endl; } else if (wavelength < 570) { //Print wavelength output color cout << "Your wavelength is Green" << endl; } else if (wavelength < 590) { //Print wavelength output color cout << "Your wavelength is Yellow" << endl; } else if (wavelength < 650) { //Print wavelength output color cout << "Your wavelength is Orange" << endl; } else if (wavelength < 700) { //Print wavelength output color cout << "Your wavelength is Red" << endl; } else { //Print wavelength output color cout << "Your wavelength is Big" << endl; }

return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!