Skip to main content
GameDev.net gamedev.net
🔒 Locked

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

Started by JWalsh Jul 16, 2006 at 12:58 PM 22 replies 11.6k views
Original Post
JWalsh
JWalsh

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!
mike223
mike223
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)

Palejo
Palejo
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:)




Emmanuel Deloget
Emmanuel Deloget
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).


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 :)


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,
Palejo
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?

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;}
Emmanuel Deloget
Emmanuel Deloget
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 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 .
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,
gparali
gparali
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.
DeadlyVirus
DeadlyVirus
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;}
me_minus
me_minus
Both week 5 and 6 looks good.
J0Be
J0Be
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]
shawnre
shawnre
Again I would like to ask one of the tutors from this workshop to post their interpretation of the "correct" way to do the extra credit exercises. I notice alot of people who posted code just put all the code into basically one file. Is that the "correct" way to do it? I was trying to use a class to handle just about everything. Is the main not supposed to be pretty much bland and calling functions defined in classes? Maybe I am trying to read too much into it, but, since we have learned classes and functions and such, should we not use that info, or for these exercises does it not matter?

Thanks,

Shawn
Alpha_ProgDes
Alpha_ProgDes
J0be, a shortcut for you (in loops).

We know that loops check for the condition to give the boolean values of true OR false.

for instance,
while (true){    cout << "I ain't neva gonna leave!!!";}// orwhile (false){   cout << "Don't worry you won't see because the false in the loop won't let you.";}


now we know that if bool play = true, then the variable play will always evaluate to true (as long as it isn't changed).

so...
while (play){    cout << "See I'm still playing!";}// no need for thiswhile (play == true){    //this is basically saying    //while (true == true)    //silly ain't it :)}
Beginner in Game Development?  Read here. And read here.  
J0Be
J0Be
I understand what your trying to say Alpha_ProgDes, but, my idea was that when I left it out, it would be more difficult for others to know what the variable actually was, by writing (play == true), you know that play is a bool variable.

I know with these small programs, it won't matter that much, but, if you have bigger programs, doesn't this then make it more obvious?


@jwalsh,
Will alter Exercise 2 to use classes and multiple files.

[Edited by - J0Be on May 31, 2007 2:43:26 PM]
Alpha_ProgDes
Alpha_ProgDes
Quote:
Original post by J0Be
I understand what your trying to say Alpha_ProgDes, but, my ideas was that when I left it out, it would be more difficult for others to know what the variable actually was, by writing (play == true), you know that play is a bool variable.

I know with these small programs, it won't matter that much, but, if you have bigger programs, doesn't this then make it more obvious?


If people who are starting out, then you are absolutely right. Just to point out, I never said what you're doing was wrong. That's why I called it a shortcut [smile]. Keep up the good work!
Beginner in Game Development?  Read here. And read here.  
J0Be
J0Be
Nono, don't get me wrong Alpha_ProgDes, I love the fact that people like you take there time and help us, not only with debugging our code and giving hints on how we should do it, but, give feedback to how we can improve our programs to become better programmers.

Quote:
Keep up the good work!


Thanks, for that, really appreciated !!!

Have to go now, will work on Exercise 2 coming week-end. Have most part of it done by now, only have to add the whole char to integer thing which is bugging me big time. Got this at the moment:

int Menu::CharToInt(const char chColor[3]){	int iColor = 0;	if (isalpha(chColor))	{		iColor = int(chColor - 48);	}	else	{		iColor = atoi (chColor);	}	return iColor;}

But, it's not doing what I want, .... just yet

[Edited by - J0Be on May 31, 2007 3:18:20 PM]
Alpha_ProgDes
Alpha_ProgDes
Quote:
Original post by J0Be
Nono, don't get me wrong Alpha_ProgDes, I love the fact that people like you take there time and help us, not only with debugging our code and giving hints on how we should do it, but, give feedback to how we can improve our programs to become better programmers.

Oh!
**shines BatLight for Zahlman and Toorhvyk** [grin]
point taken.

Quote:
Keep up the good work!


Thanks, for that, really appreciated !!![/quote]

Beginner in Game Development?  Read here. And read here.  
nobodynews
nobodynews
Quote:
Original post by J0Be
I understand what your trying to say Alpha_ProgDes, but, my idea was that when I left it out, it would be more difficult for others to know what the variable actually was, by writing (play == true), you know that play is a bool variable.

I know with these small programs, it won't matter that much, but, if you have bigger programs, doesn't this then make it more obvious?


@jwalsh,
Will alter Exercise 2 to use classes and multiple files.


There is a term that, when applied to programming, means that there are certain agreed upon conventions you can use when seeing a bit of code. These are known as idioms and when you write code using these idioms it is called 'idiomatic' code.

You can't tell by looking what the type of the variable is, but you don't really need to know the type as long as you understand what the code means. This is where good variable names come in. I think for this case that 'playing' may be a better name than 'play'. Which reads more like a sentence? "while play" or "while playing"?

Lastly, even if you Did need to know the type you can select the variable, right click, and select 'go to definition' (in visual c++ 2005). Tada, you know the type.

Another thing, even if the variable Isn't a bool, you can still write while (x == true)--at least, I'm pretty sure it's legal c++. For example, this
#include <iostream>int main(){	int alpha = 10;	bool beta = true;	if(alpha == true)	{		std::cout << "alpha is true!" << std::endl;	}	if(beta == true)	{		std::cout << "beta is true!" << std::endl;	}}
compiles with only a warning (in Visual C++ 2005 with warnings turned on all the way). It only prints the second statement, however. This just means you Still can't assume that just because you put "variable == true" that the variable is of type bool just by reading it. You need to at least compile to get the information (which may or may not be a problem from the compiler's point of view).

Hope that helps.

edit: A 'true' value can be converted to an integer. In this case, the compiler converted true to 1, and then compared 10 to 1 and found they weren't equal. Lesson? Don't compare integers to booleans :)

[Edited by - nobodynews on May 31, 2007 4:50:35 PM]
C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) ,
shawnre
shawnre
Guessing Game:

//Number Guessing Game#include <iostream>#include <stdlib.h>#include <time.h>using namespace std;int main(){	unsigned short Guess, RandomNumber, Attempts=0;	bool Playing = true;	srand((unsigned)time(NULL));		RandomNumber =(rand() % 100) + 1;	while (Playing)	{		Attempts +=1;		cout<<"Please enter your guess (1-100): ";		cin>>Guess;		if (Guess==RandomNumber)		{			cout<<"You guessed correctly!!"<<endl;			cout<<"It took you "<<Attempts<<" tries."<<endl;			Playing = false;		}		if (Guess<RandomNumber)		{			cout<<"Your guess is low"<<endl;		}		if (Guess>RandomNumber)		{			cout<<"Your guess is high"<<endl;		}	}}
shawnre
shawnre
#2 Color Menu

Interpretaion I implemented. I have a couple problems with it, firstly the if statement in the main and also, wasnt sure how to implement the enum of the colors even though it is in there.

Any suggestions would be appreciated.


*Edit* - All 3 programs listed in the one source listing below

//Menu Class Declaration//MenuClass.h#include <iostream>using namespace std;class Menu{	public:	void DisplayMenu();							//Function to display the menu	unsigned short GetInput();					//Function to get users input	void ChangeColor(unsigned short);			//Function to change the color	void ValidateInput(unsigned short);						//Function to check the users input		enum MenuColor {DarkBlue=1, DarkGreen, Teal, Burgundy, Violet, Gold, Silver, Gray, Blue, Green, Cyan, Red, Purple, Yellow, White, Quit};  //Enumerated Constant with values starting at 1};//This file is the definitions of the MenuClass.h//MenuFunctions.cpp#include "MenuClass.h"#include <iostream>#include <windows.h>using namespace std;//The following defines ChangeColor of class Menu	void Menu::ChangeColor(unsigned short color)	{		HANDLE hConsole = GetStdHandle( STD_OUTPUT_HANDLE );		SetConsoleTextAttribute( hConsole, color ); // where color is the color code to set it to			}//This will display the menu	void Menu::DisplayMenu()	{		cout<<"Please enter a choice for your color"<<endl;		cout<<endl<<"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;	}//Function to get the users input	unsigned short Menu::GetInput()	{		unsigned int choice;		cout<<endl;		cin>>choice;		return choice;	}//Function to validate the users input	void Menu::ValidateInput(unsigned short choice)	{		if ((choice<1) || (choice>16))		{			cout<<"Error, choice must be between 1 and 16"<<endl;		}	}		//Main for the Menu system#include <iostream>#include "MenuClass.h"using namespace std;int main()	{		unsigned short Choice;		bool Exit=false;						while (!Exit)		{		Menu UserMenu;		UserMenu.DisplayMenu();		Choice=UserMenu.GetInput();		UserMenu.ValidateInput(Choice);		if (Choice==16)		{			Exit=true;		}		else		{			UserMenu.ChangeColor(Choice);		}		}	}


[Edited by - shawnre on June 1, 2007 8:47:41 PM]
J0Be
J0Be
Reviewed Exercise 2.

// Menu.h file#include <iostream>#include <windows.h>class Menu{public:	Menu();	~Menu();	enum COLOR { DARK_BLUE = 1, DARK_GREEN, TEAL, BURGUNDY, VIOLET, GOLD, SILVER,			  GREY, BLUE, GREEN, CYAN, RED, PURPLE, YELLOW, WHITE };	void ColorMenu();	int CharToInt(char arrColor[3]);	bool PrintColor(const int color);private:	HANDLE m_hConsole;	COLOR m_Color;};


// Menu.cpp file#include "Menu.h"#include <cstdlib>Menu::Menu() {	// Call the following line ONCE, to get the handle to the console window	m_hConsole = GetStdHandle( STD_OUTPUT_HANDLE );	m_Color = WHITE; // set color to your preference to start with.	SetConsoleTextAttribute(m_hConsole, m_Color);}Menu::~Menu() {}void Menu::ColorMenu(){	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";}int Menu::CharToInt(char chColor[3])					{	int iColor = 0;	std::cin.getline(chColor, 3);	std::cout << std::endl;	if (isalpha(chColor[0])) // check wether first letter in string is an	{			 // alphabetical value		if (chColor[0] == 'Q' || chColor[0] == 'q')		{			return iColor = 16;		}		else		{			return iColor = 99;		}	}	else													{		iColor = atoi (chColor);// if not, use ASCII to integer to alter value.	}	return iColor; }bool Menu::PrintColor(const int color){	switch(color)		{		case DARK_BLUE:			SetConsoleTextAttribute( m_hConsole, DARK_BLUE);			break;		case DARK_GREEN:			SetConsoleTextAttribute( m_hConsole, DARK_GREEN);			break;		case TEAL:			SetConsoleTextAttribute( m_hConsole, TEAL);			break;		case BURGUNDY:			SetConsoleTextAttribute( m_hConsole, BURGUNDY);			break;		case VIOLET:			SetConsoleTextAttribute( m_hConsole, VIOLET);			break;		case GOLD:			SetConsoleTextAttribute( m_hConsole, GOLD);			break;		case SILVER:			SetConsoleTextAttribute( m_hConsole, SILVER);			break;		case GREY:			SetConsoleTextAttribute( m_hConsole, GREY);			break;		case BLUE:			SetConsoleTextAttribute( m_hConsole, BLUE);			break;		case GREEN:			SetConsoleTextAttribute( m_hConsole, GREEN);			break;		case CYAN:			SetConsoleTextAttribute( m_hConsole, CYAN);			break;		case RED:			SetConsoleTextAttribute( m_hConsole, RED);			break;		case PURPLE:			SetConsoleTextAttribute( m_hConsole, PURPLE);			break;		case YELLOW:			SetConsoleTextAttribute( m_hConsole, YELLOW);			break;		case WHITE:			SetConsoleTextAttribute( m_hConsole, WHITE);			break;		case 16:			return false;		default:			std::cout << "Wrong value, select again!\n\n\n";		}	return true;}


//Main.cpp#include "Menu.h"int main(){	Menu mColor;	bool exit = true;	char arrColor[3] = "";	while(exit)	{		mColor.ColorMenu();		int numVal = mColor.CharToInt(arrColor);		exit = mColor.PrintColor(numVal);	}	return 0;}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.