🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

C++ Workshop - Week 6 (Ch. 7) - Quizzes and Exercises

Started by
22 comments, last by Dbproguy 16 years, 1 month ago

Quizzes and Extra Credit for Week 6.

Post your answers to the Quizzes from Week 6 here rather than in the chapter thread, so as not to spoil things for the others. Chapter 7 Quiz 1. What does a while-loop cause your program to do? 2. What does the “continue” statement do? 3. What does the “break” statement do? 4. What is it called when you have a loop in which the exit condition can never be met? 5. What loop device do you use if you want to ensure the loop executes at least once, regardless of the success/failure of the test condition? 6. What are the 3 parts to a for-loop header? 7. Can you initialize, test, or perform more than one action within a loop header? If so, what does the syntax look like? 8. Which of the three components of a for-loop header can be left out? 9. According to the new ANSI standard, what is the scope of variables declared in the for-loop header? 10. What types of expressions can be used in a switch statement? 11. What happens if there is no ‘break’ statement at the end of a switch case? 12. Why is it a good idea to always have a default case in a switch statement? Chapter 7 Exercises 1. Guessing Game: Returning to the “guess the number” exercise from week 3, lets now make it a complete game. In your main function generate a random ‘secret’ number using the method shown in week 5 between 1 and 100. Next, repeatedly ask the user to guess the number UNTIL s/he gets the answer correct. Each time they guess let them know whether the number was higher or lower than their guess. Once the user has guessed correctly, let them know and tell them how many guesses it took. 2. Color Menu: In this exercise you are going to write a program that shows the user a menu asking them what color they would like to display their menu in. The menu itself, will be a list of matching numbers and colors. Use the menu below to determine menu options. Present the menu to the user over and over again, allowing them to change the color of the menu until they choose the q option. Once they select ‘q’, terminate the program. There is helper code below to allow you to change the color of the console window. Once the user has selected a color option, set the color for the console window, and then re-print the menu onto the screen. Although not strictly necessary for this exercise, I encourage you to make an enum out of the following menu options and color names, and then use a switch statement to check for color values. The program will work just fine without, however….perhaps try it both ways and see how it’s different in this case. Show the users the following menu: -------------------------------------------- 1. Dark Blue 2. Dark Green 3. Teal 4. Burgundy 5. Violet 6. Gold 7. Silver 8. Gray 9. Blue 10. Green 11. Cyan 12. Red 13. Purple 14. Yellow 15. White Q. Quit Please select a color to display your menu: --------------------------------------------

// To gain access to the functionality required to change the console window colors, add the following include file
#include <windows.h>

// In function main, call the following line ONCE, to get the handle to the console window
HANDLE hConsole = GetStdHandle( STD_OUTPUT_HANDLE );

// To actually SET the color of the console window use the following line of code.
SetConsoleTextAttribute( hConsole, COLOR_VALUE ); // where COLOR_VALUE is the color code to set it to
Cheers and Good luck!
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints
Advertisement
1. What does a while-loop cause your program to do?
Repeats a statement or block of statements as long as a condition is true.

2. What does the “continue” statement do?
Immediately jumps back to the top of the loop and checks the condition again.

3. What does the “break” statement do?
Exits the loop.

4. What is it called when you have a loop in which the exit condition can never be met?
An infinite (or forever) loop.

5. What loop device do you use if you want to ensure the loop executes at least once, regardless of the success/failure of the test condition?
do-while

6. What are the 3 parts to a for-loop header?
initialisation, condition, increment.

7. Can you initialize, test, or perform more than one action within a loop header? If so, what does the syntax look like?
Yes, by using commas. E.g.

for(int i =0, int j = 5; i < 10; ++i, --j)

8. Which of the three components of a for-loop header can be left out?
Any or all of them.

9. According to the new ANSI standard, what is the scope of variables declared in the for-loop header?
The variables are visible within the for loop only.

10. What types of expressions can be used in a switch statement?
Anything that evaluates to a numerical value eg ints or chars.

11. What happens if there is no ‘break’ statement at the end of a switch case?
Processing falls through to the next case.

12. Why is it a good idea to always have a default case in a switch statement?
It helps to check for errors.

Chapter 7 Exercises

1. Guessing Game:

// randomnumber.cpp#include <iostream>#include <cstdlib>#include <ctime>int generateNumber();int main(){	srand((unsigned)time(NULL));	std::cout << "Random Number Guessing Game!" << std::endl;	std::cout << "----------------------------" << std::endl;	std::cout << "Guess the random number between 1 and 100." << std::endl;		int answer = generateNumber();	int attempts = 0;	int guess = -1;	bool finished = false;	while(!finished)	{		++attempts;		std::cout << "> ";		std::cin >> guess;		if (guess == answer)		{			std::cout << "Correct!!!" << std::endl;			std::cout << "You found the answer in " << attempts << " tries!" << std::endl;			finished = true;		}		if (guess > answer)		{			std::cout << "The number is lower!" << std::endl;		}		if (guess < answer)		{			std::cout << "The number is higher!" << std::endl;		}	}	return 0;}int generateNumber(){	return (rand() % 100) + 1;}


2. Color Menu:
// colours.cpp#include <iostream>#include <string>#include "windows.h"enum COLOUR { DARK_BLUE = 1, DARK_GREEN, TEAL, BURGUNDY, VIOLET, GOLD, SILVER,			  GREY, BLUE, GREEN, CYAN, RED, PURPLE, YELLOW, WHITE };void displayMenu();std::string getInput();int main(){	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);	bool finished = false;	while(!finished)	{		displayMenu();		std::string choice = getInput();		if (choice == "1")			SetConsoleTextAttribute(hConsole, DARK_BLUE);		else if (choice == "2")			SetConsoleTextAttribute(hConsole, DARK_GREEN);		else if (choice == "3")			SetConsoleTextAttribute(hConsole, TEAL);		else if (choice == "4")			SetConsoleTextAttribute(hConsole, BURGUNDY);		else if (choice == "5")			SetConsoleTextAttribute(hConsole, VIOLET);		else if (choice == "6")			SetConsoleTextAttribute(hConsole, GOLD);		else if (choice == "7")			SetConsoleTextAttribute(hConsole, SILVER);		else if (choice == "8")			SetConsoleTextAttribute(hConsole, GREY);		else if (choice == "9")			SetConsoleTextAttribute(hConsole, BLUE);		else if (choice == "10")			SetConsoleTextAttribute(hConsole, GREEN);		else if (choice == "11")			SetConsoleTextAttribute(hConsole, CYAN);		else if (choice == "12")			SetConsoleTextAttribute(hConsole, RED);		else if (choice == "13")			SetConsoleTextAttribute(hConsole, PURPLE);		else if (choice == "14")			SetConsoleTextAttribute(hConsole, YELLOW);		else if (choice == "15")			SetConsoleTextAttribute(hConsole, WHITE);		else if (choice == "q" || choice == "Q")			finished = true;		else			std::cout << "Invalid option!" << std::endl;	}	return 0;}void displayMenu(){	std::cout << "--------------------------------------------" << std::endl;	std::cout << "1. Dark Blue" << std::endl;	std::cout << "2. Dark Green" << std::endl;	std::cout << "3. Teal" << std::endl;	std::cout << "4. Burgundy" << std::endl;	std::cout << "5. Violet" << std::endl;	std::cout << "6. Gold" << std::endl;	std::cout << "7. Silver" << std::endl;	std::cout << "8. Grey" << std::endl;	std::cout << "9. Blue" << std::endl;	std::cout << "10. Green" << std::endl;	std::cout << "11. Cyan" << std::endl;	std::cout << "12. Red" << std::endl;	std::cout << "13. Purple" << std::endl;	std::cout << "14. Yellow" << std::endl;	std::cout << "15. White" << std::endl;	std::cout << "Q. Quit" << std::endl;	std::cout << "\nPlease select a colour to display your menu:" << std::endl;	std::cout << "--------------------------------------------" << std::endl;}std::string getInput(){	std::string choice;	std::cout << "> ";	std::getline(std::cin, choice, '\n');	return choice;}

(Using strings was the only way I could think of to allow for both numbers and letters in the menu)

Looking for a little help here.

Can't seem to get windows.h to load due to some of the reasons listed in the chapter 7 thread.

But, if at the end of the day I can't get that to load I'm ok with that, as the point of exercise #2 seems to be the understanding the of switch statement. Others have already questioned how to get our enum variable to accept both integer and character selections, and I am stumped on this as well. The one submitted program uses strings to get around this, which IMO is great, but I'm not that cool/skilled just and really just want to come to understand switch and how to manipulate it correctly:)

If I create the following enum variable:

enum selection { DarkBlue = 1, DarkGreen, Teal, Burgundy, Violet, Gold, Silver, Gray, Blue, Green, Cyan, Red, Purple, Yellow, White, Q };

Should my switch statements refer to the names (DarkGreen, Teal, etc.) of the colors or the value of those color constants (1, 2, etc.)? Or does either one work?

Here is my code:
#include <iostream>using namespace std;int main(){	bool exit = false;	enum selection { DarkBlue = 1, DarkGreen, Teal, Burgundy, Violet, Gold, Silver, Gray, Blue, 						Green, Cyan, Red, Purple, Yellow, White, Q };	selection input;	while (true)			{		cout << "--------------------------------------------" << endl;		cout << "1. Dark Blue" << endl;		cout << "2. Dark Green" << endl;		cout << "3. Teal" << endl;		cout << "4. Burgundy" << endl;		cout << "5. Violet" << endl;		cout << "6. Gold" << endl;		cout << "7. Silver" << endl;		cout << "8. Gray" << endl;		cout << "9. Blue" << endl;		cout << "10. Green" << endl;		cout << "11. Cyan" << endl;		cout << "12. Red" << endl;		cout << "13. Purple" << endl;		cout << "14. Yellow" << endl;		cout << "15. White" << endl;		cout << "Q. Quit" << endl << endl;		cout << "Please select a color to display your menu:" << endl;		cout << "--------------------------------------------" << endl;		cin >> input;		switch (input)		{ 			case 1: cout << "You've selected option 1!" << endl;					break;			case 2: cout << "You've selected option 2!" << endl;					break;			case 3: cout << "You've selected option 3!" << endl;					break;			case 4: cout << "You've selected option 4!" << endl;					break;			case 5: cout << "You've selected option 5!" << endl;					break;			case 6: cout << "You've selected option 6!" << endl;					break;				case 7: cout << "You've selected option 7!" << endl;					break;			case 8: cout << "You've selected option 8!" << endl;					break;			case 9: cout << "You've selected option 9!" << endl;					break;			case 10: cout << "You've selected option 10!" << endl;					break;			case 11: cout << "You've selected option 11!" << endl;					break;			case 12: cout << "You've selected option 12!" << endl;					break;			case 13: cout << "You've selected option 13!" << endl;					break;			case 14: cout << "You've selected option 14!" << endl;					break;			case 15: cout << "You've selected option 15!" << endl;					break;			case 16: exit = true;						break;			default: cout << "Invalid Selection. Please enter again." << endl;					 break;		}		if exit == true			break;	}	return 0;}


And I'm getting two errors:

c:\documents and settings\compaq_administrator\my documents\visual studio 2005\projects\deleteme\deleteme\deleteme.cpp(34) : error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'main::selection' (or there is no acceptable conversion)

c:\documents and settings\compaq_administrator\my documents\visual studio 2005\projects\deleteme\deleteme\deleteme.cpp(73) : error C2061: syntax error : identifier 'exit'

Not too worried about the 2nd error, I think I can figure that one out but the first one worries me, it makes me believe I'm not understanding something about the basics of switch. Again, I'd appreciate any help I can get:)




First, the enum associate symbolic names to literal values. Symbolic names are better for code readability, while litteral values are a bit cryptic. Switch will handle both correctly, but symbolic names would be better.

Second, there is nothing wrong in you switch, but you forgot some basic principle of C++: it can handle only the things he knows.

Your first error is linked to the "cin >> input;" line. It tells you that the operator >> can't understand how to put something in the "input" variable. The error cause is "input"'s type ("selection"), and the fact that the compiler can't automagically promote an integer value to a value of type selection (even if he can do the inverse operation).

<advanced>
You'll learn later that you can use some techniques to do what you want to do (namely, you'll have to overload operator>> to act on a istream and a value of type "selection"). As of today, consider that you can't do this :)
</advanced>

To correct your problem, you have to put cin's output in something that the compiler will correctly handle, for example an "int". Then you can transform this integer value to a "selection" value using an explicit type promotion (type cast).

The other solution is to forget about the selection type completely and to handle only integers.

Your second error is fired because you forgot the syntax of the "if" statement:
if (condition) statement

I emphasized the parenthesis on purpose [smile].

Note that you can use a real condition in the while statement as well. Exercise: I suggest you to remove this "if" statement and to modify the "while" condition accordingly.

HTH,
Mr. Deloget,

First of all, thank you for the kind response. Rating++:)

I am, however, still a bit confused.
Quote: To correct your problem, you have to put cin's output in something that the compiler will correctly handle, for example an "int". Then you can transform this integer value to a "selection" value using an explicit type promotion (type cast).

Have we discussed type casting yet? I did some research on this and couldn't find it anywhere in the first 7 chapters. Have I missed it somewhere?

After some googling, I was able to get the following code to compile, with the line input = (enum selection) DisplayMenu(); getting me past my first error on my first compile. I'm not totally sure why this works, I think it's because I'm still a little shady on type casting.

When I compile this it seems to run fine when I enter entries for options 1-15, but when I enter 'Q' or any value not listed in my enum datatype, my menu displays over and over again, and I have to ctrl-break to get out of the pgm.

Is this because I haven't type-casted correctly, perhaps? And as another question, what happens when I try to plug in a value not listed as a possible enum value into my variable?

Pretty sure this all has to deal with the fact that I'm returning an int from my menu function, which somehow isn't translating correctly when I enter actual characters such a 'Q'. How can we get around this? Again, thank you so much for the help!


#include <iostream>using namespace std;int main(){	int DisplayMenu();		bool exit = false;	enum selection { DarkBlue = 1, DarkGreen, Teal, Burgundy, Violet, Gold, Silver, Gray, Blue, 						Green, Cyan, Red, Purple, Yellow, White, Q };	selection input;	while (true)			{		input = (enum selection) DisplayMenu();		switch (input)		{ 			case DarkBlue: cout << "You've selected option 1!" << endl;					break;			case DarkGreen: cout << "You've selected option 2!" << endl;					break;			case Teal: cout << "You've selected option 3!" << endl;					break;			case Burgundy: cout << "You've selected option 4!" << endl;					break;			case Violet: cout << "You've selected option 5!" << endl;					break;			case Gold: cout << "You've selected option 6!" << endl;					break;				case Silver: cout << "You've selected option 7!" << endl;					break;			case Gray: cout << "You've selected option 8!" << endl;					break;			case Blue: cout << "You've selected option 9!" << endl;					break;			case Green: cout << "You've selected option 10!" << endl;					break;			case Cyan: cout << "You've selected option 11!" << endl;					break;			case Red: cout << "You've selected option 12!" << endl;					break;			case Purple: cout << "You've selected option 13!" << endl;					break;			case Yellow: cout << "You've selected option 14!" << endl;					break;			case White: cout << "You've selected option 15!" << endl;					break;			case Q: exit = true;						break;			default: cout << "Invalid Selection. Please enter again." << endl;					 break;		}		if (exit == true)			break;	}	return 0;}int DisplayMenu(){		int option;		cout << "--------------------------------------------" << endl;		cout << "1. Dark Blue" << endl;		cout << "2. Dark Green" << endl;		cout << "3. Teal" << endl;		cout << "4. Burgundy" << endl;		cout << "5. Violet" << endl;		cout << "6. Gold" << endl;		cout << "7. Silver" << endl;		cout << "8. Gray" << endl;		cout << "9. Blue" << endl;		cout << "10. Green" << endl;		cout << "11. Cyan" << endl;		cout << "12. Red" << endl;		cout << "13. Purple" << endl;		cout << "14. Yellow" << endl;		cout << "15. White" << endl;		cout << "Q. Quit" << endl << endl;		cout << "Please select a color to display your menu:" << endl;		cout << "--------------------------------------------" << endl;		cin >> option;		return option;}
Quote: Original post by Palejo
Mr. Deloget,

First of all, thank you for the kind response. Rating++:)

I am, however, still a bit confused.
Quote: To correct your problem, you have to put cin's output in something that the compiler will correctly handle, for example an "int". Then you can transform this integer value to a "selection" value using an explicit type promotion (type cast).

Have we discussed type casting yet? I did some research on this and couldn't find it anywhere in the first 7 chapters. Have I missed it somewhere?

No, type casting has not been discussed yet - I just mentionned it as an alternative, but forgot to put <advanced> tags around it.

Quote: Original post by Palejo
After some googling, I was able to get the following code to compile, with the line input = (enum selection) DisplayMenu(); getting me past my first error on my first compile. I'm not totally sure why this works, I think it's because I'm still a little shady on type casting.

C++ is using a different syntax for type casting than C. I won't go in the details right now (you'll be able to figure out the exact code when you'll read the corresponding chapter). To simplify, let's say that in your case, the simplest way (but not truly correct froma C++ point of view, as you'll learn later) is
input = (selection) DisplayMenu();

The enum keyword is optional.

Quote: Original post by Palejo
When I compile this it seems to run fine when I enter entries for options 1-15, but when I enter 'Q' or any value not listed in my enum datatype, my menu displays over and over again, and I have to ctrl-break to get out of the pgm.

Is this because I haven't type-casted correctly, perhaps?

No. This is because "cin >> option;" expect you to type an integer (since option is an int), and "Q" is not an integer. The operator >> cannot tranform "Q" to an integer, so it fails, and the "Q" letter is not removed from the stream (meaning that you effectively created an infinite loop). This is the fun part of the exercise, but I'll give you a hint: strings are your friends.

Quote: Original post by Palejo
And as another question, what happens when I try to plug in a value not listed as a possible enum value into my variable?

In your code, if you type an integer which cannot be represented by one of your enum value, the "invalid selection" string will be displayed (try 55 for example).

Quote: Original post by Palejo
Pretty sure this all has to deal with the fact that I'm returning an int from my menu function, which somehow isn't translating correctly when I enter actual characters such a 'Q'. How can we get around this? Again, thank you so much for the help!


You're welcome [smile]

Your assumption is nearly correct, but the problem really lies in the "cin >> option;" line, not in the fact that you are returning an integer value. Try this: change the type of option to std::string. Check if option is "Q" - if it is the case, return the Q enum value. If not, try converting it to an int using this line of code:
// convert the option string to an integerint result = std::atoi(option.c_str());

atoi will return 0
* if the option string contains 0
* if the option string doesn't contain an integer (for example "blah")
To be able to use std::atoi(), you will have to #include <cstdlib>.
There are other ways to handle the same problem - read the std::istream documentation for further information (about ignore() and the >> operators). If you find the doc frightening (admitedly, they are not easy to decipher) just stick to the solution I described - it works well and you can even ignore the type cast:
// I am allowed to create an anonym eumaration, but I can // also specify the enum type name - it won't change anything to // the code belowenum { DarkBlue = 1, DarkGreen, Teal, Burgundy, Violet,        Gold, Silver, Gray, Blue, Green, Cyan, Red,        Purple, Yellow, White, Q };...int input = DisplayMenu();switch (input){// I can still use the enum values as a comparison token (input will // be compared to the numerical value which is represented by this// symbolic constant)case DarkBlue: ...; break;...};


HTH,
I would like to ask wether each color is connected with a particular number.

If i right this for example

SetConsoleTextAttribute(hConsole,12);

text turns into bright red.
If i change the number i get a different color.
Here are my answers and codes.

1. Loops a statement as long as the condition is true.
2. Goes back to the top of the loop and checks it again.
3. Ends the loop.
4. A forever loop/infinite loop
5. do....while loop
6. initialize, test and perform
7. yes, for(int i = 0, int j = 0; i < 10; i++, j++)
8. All of them
9. Within the loop only
10. any c++ expression
11. it falls through to the default statement, if no default it falls through the switch statement and ends.
12. to test for errors

Guessing game
#include <iostream>#include <cstdlib>#include <ctime>using namespace std;int main(){	srand ((unsigned)time(NULL));	int theNumber = (rand() % 100) + 1;	int tries = 0, guess;	cout << "Welcome to Guess My Number Game!!" << endl;	do	{		cout << "Enter a guess: " << endl;		cin >> guess;		++tries;		if (guess > theNumber)			cout << "Too high, try again" << endl;		if (guess < theNumber)			cout << "Too low, try again" << endl;	} while (guess != theNumber);	cout << "That's it! You got it in " << tries << " guesses!" << endl;	system("PAUSE");		return 0;}


Color Menu:
#include <iostream>#include <cstdlib>#include <windows.h>#include <ctime>using namespace std;unsigned short ColorMenu();enum input { DarkBlue = 1, DarkGreen, Teal, Burgundy, Violet, Gold, Silver, Grey, Blue,        Green, Cyan, Red, Purple, Yellow, White, Quit };int main(){	HANDLE hConsole = GetStdHandle( STD_OUTPUT_HANDLE );	input choice;	bool fQuit = FALSE;	while (!fQuit)	{		choice = (enum input) ColorMenu();		switch (choice)		{		case DarkBlue:			SetConsoleTextAttribute(hConsole, DarkBlue);			break;		case DarkGreen:			SetConsoleTextAttribute(hConsole, DarkGreen);			break;		case Teal:			SetConsoleTextAttribute(hConsole, Teal);			break;		case Burgundy:			SetConsoleTextAttribute(hConsole, Burgundy);			break;		case Violet:			SetConsoleTextAttribute(hConsole, Violet);			break;		case Gold:			SetConsoleTextAttribute(hConsole, Gold);			break;		case Silver:			SetConsoleTextAttribute(hConsole, Silver);			break;		case Grey:			SetConsoleTextAttribute(hConsole, Grey);			break;		case Blue:			SetConsoleTextAttribute(hConsole, Blue);			break;		case Green:			SetConsoleTextAttribute(hConsole, Green);			break;		case Cyan:			SetConsoleTextAttribute(hConsole, Cyan);			break;		case Red:			SetConsoleTextAttribute(hConsole, Red);			break;		case Purple:			SetConsoleTextAttribute(hConsole, Purple);			break;		case Yellow:			SetConsoleTextAttribute(hConsole, Yellow);			break;		case White:			SetConsoleTextAttribute(hConsole, White);			break;		case Quit:			fQuit = TRUE;			break;		default:			cout << "Error in choice, Please choose again." << endl;			break;		}	}	return 0;}unsigned short ColorMenu(){	int choice;	cout << "Color Menu" << endl;	cout << "(1) Dark Blue" << endl;	cout << "(2) Dark Green" << endl;	cout << "(3) Teal" << endl;	cout << "(4) Burgundy" << endl;	cout << "(5) Violet" << endl;	cout << "(6) Gold" << endl;	cout << "(7) Silver" << endl;	cout << "(8) Gray" << endl;	cout << "(9) Blue" << endl;	cout << "(10) Green" << endl;	cout << "(11) Cyan" << endl;	cout << "(12) Red" << endl;	cout << "(13) Purple" << endl;	cout << "(14) Yellow" << endl;	cout << "(15) White" << endl;	cout << "(16) Quit" << endl;	cin >> choice;	return choice;}
Both week 5 and 6 looks good.
Chapter 7.

1) What does a while-loop cause your program to do?
A) A while-loop causes your program to repeat a sequence of statements as long as the starting condition remains true.

2) What does the "continue" statement do?
A) The continue statement jumps back to the top of the loop.

3) What does the "break" statement do?
A) The break statement immediately exits the loop, and program execution resumes after the closing brace.

4) What is it called when you have a loop in which the exit condition can never be met?
A) They are called "eternal" loops.

5) What loop device do you use if you want to ensure the loop executes at least once, regardless of teh success/failure of the test condition?
A) You use a do ... while loop.

6) What are the 3 parts to a for-loop header?
A) They are: - initialization
- test
- action

7) Can you initialize, test, or perform more than one action within a loop header? If so, what does the syntax look like?
A) Yes you can do this, an example would be: for (int i = 0, j = 10; i < 10; i++, j--)

8) Which of the three components of a for-loop header can be left out?
A) All can be left out.

9) According to the new ANSI standard, what is the scope of variables declared in the for-loop header?
A) The scope of the declared variables in the for-loop is limited to the block of the for-loop itself.

10) What types of expressions can be used in a switch statement?
A) Any legal C++ expression that evaluate(or can be unambiguously converted to) an integer value.

11) What happens if there is no 'break' statement at the end of a switch case?
A) Then the execution falls through to the next statement.

12) Why is it a good idea to always have a default case in a switch statement?
A) Because this way, you can have a default way of letting the user know his input was wrong, inaccurate, out of range, ... This can be a tremendous aid in debugging for the programmer himself.

/*1. Guessing Game: */#include <ctime>#include <cstdlib>#include <iostream>void Menu();void guessNumber();void Quit();int main(){	// Call this ONCE, in your main function to seed the random number generator	srand( (unsigned)time( NULL) );	bool play = true;	int wish;	while (play == true)	{		Menu();		std::cout << "\t\tEnter your Wish: ";		std::cin >> wish;		switch(wish)		{		case 1: guessNumber();			break;		case 2:			break;		case 3: Quit();			play = false;			break;		default:			std::cout << "Wrong choice, pick again!\n\n";			break;		}	}	return 0;}void Menu(){	std::cout << "\t****************Menu***************\n";	std::cout << "\t(1) Wish to play a game?  Pick N°1:\n";	std::cout << "\t(2) Wish to see the menu? Pick N°2:\n";	std::cout << "\t(3) Wish to Quit?         Pick N°3:\n";}void guessNumber(){	bool exit = true;	int number, guesses = 1;	int secretNumber = (rand() % 100) + 1;	std::cout << std::endl << std::endl;	std::cout << "\t\tWelcome to the guessing game!\n\n\n";	std::cout << "\tPlease enter a number between 1 and 100:\n";	while (exit)	{		std::cout << "\t\tYour guess is number: ";		std::cin >> number;		if (number < secretNumber)		{			std::cout << "The number is smaller then the secret number!" << std::endl;			guesses++;		}		else if (number > secretNumber)		{			std::cout << "The number is bigger then the secret number!" << std::endl;			guesses++;		}		else		{			std::cout << "You've guessed the secret number, it is: " << secretNumber << std::endl;			std::cout << "You've guessed it in " << guesses << " tries!\n\n\n";			exit = false;					}	}}void Quit(){	std::cout << "Thank you for playing this game. Goodbye!" << std::endl;}


/*2. Color Menu:  */#include <iostream>#include <string>#include <windows.h>int Menu();int PickColor();bool PrintColor(const int color);int main(){	bool exit = true;	int color;	while(exit == true)	{		color = Menu();		exit = PrintColor(color);			}	return 0;}int Menu(){	std::cout << "1.  Dark Blue.\n";	std::cout << "2.  Dark Green.\n";	std::cout << "3.  Teal.\n";	std::cout << "4.  Burgundy.\n";	std::cout << "5.  Violet.\n";	std::cout << "6.  Gold.\n";	std::cout << "7.  Silver.\n";	std::cout << "8.  Gray.\n";	std::cout << "9.  Blue.\n";	std::cout << "10. Green.\n";	std::cout << "11. Cyan.\n";	std::cout << "12. Red.\n";	std::cout << "13. Purple.\n";	std::cout << "14. Yellow.\n";	std::cout << "15. White.\n";	std::cout << "Q.  Quit.\n";	std::cout << "Please select a color to display your menu:\n";	std::cout << "-------------------------------------------\n\n";	return PickColor();}int PickColor(){	std::string choice;	std::cout << "Color number: ";	std::cin >> choice;		if (choice == "1")		return 1;	else if (choice == "2")		return 2;	else if (choice == "3")		return 3;	else if (choice == "4")		return 4;	else if (choice == "5")		return 5;	else if (choice == "6")		return 6;	else if (choice == "7")		return 7;	else if (choice == "8")		return 8;	else if (choice == "9")		return 9;	else if (choice == "10")		return 10;	else if (choice == "11")		return 11;	else if (choice == "12")		return 12;	else if (choice == "13")		return 13;	else if (choice == "14")		return 14;	else if (choice == "15")		return 15;	else if (choice == "Q" || choice == "q")		return 16;	else	{		std::cout << "Wrong number! Pick again!\n";		return PickColor();	}}bool PrintColor(const int color){	// In function, call the following line ONCE, to get the handle to the console window	HANDLE hConsole = GetStdHandle( STD_OUTPUT_HANDLE );	enum COLOR { DARK_BLUE = 1, DARK_GREEN, TEAL, BURGUNDY, VIOLET, GOLD, SILVER,			  GREY, BLUE, GREEN, CYAN, RED, PURPLE, YELLOW, WHITE };	switch(color)		{		case 1:			SetConsoleTextAttribute( hConsole, DARK_BLUE); // where color is the color code to set it to			break;		case 2:			SetConsoleTextAttribute( hConsole, DARK_GREEN);			break;		case 3:			SetConsoleTextAttribute( hConsole, TEAL);			break;		case 4:			SetConsoleTextAttribute( hConsole, BURGUNDY);			break;		case 5:			SetConsoleTextAttribute( hConsole, VIOLET);			break;		case 6:			SetConsoleTextAttribute( hConsole, GOLD);			break;		case 7:			SetConsoleTextAttribute( hConsole, SILVER);			break;		case 8:			SetConsoleTextAttribute( hConsole, GREY);			break;		case 9:			SetConsoleTextAttribute( hConsole, BLUE);			break;		case 10:			SetConsoleTextAttribute( hConsole, GREEN);			break;		case 11:			SetConsoleTextAttribute( hConsole, CYAN);			break;		case 12:			SetConsoleTextAttribute( hConsole, RED);			break;		case 13:			SetConsoleTextAttribute( hConsole, PURPLE);			break;		case 14:			SetConsoleTextAttribute( hConsole, YELLOW);			break;		case 15:			SetConsoleTextAttribute( hConsole, WHITE);			break;		case 16:			return false;		default:			std::cout << std::endl;		}	return true;}


Edit: altered function names, added the enum to the 2nd exercise and improved input checking, hopefully for the better.

[Edited by - J0Be on May 31, 2007 8:48:42 AM]

This topic is closed to new replies.

Advertisement