🎉 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 - Looping & Switch Statements (Ch. 7)

Started by
48 comments, last by Dbproguy 16 years, 1 month ago
Quote: Original post by RinusMaximus

I always use i, j, k etc. for my loops. This way it is always clear to me that this variable is only valid in the scope of the loop, so I would never confuse these with other variables.


That, coupled with the later bit of advice from Oluseyi is just the kind of real world stuff I love to hear about. Thanks!


Quote: Just try to program as many things as you can. You can only become a good programmer by writing loads of code.


You know, one reason I like Dietel & Dietel's 'C++ How to Program' is the sheer number of exercises it has at the end of each chapter. You sometimes feel you'll never get through all of them but it really hammers home the principles in the chapter; either that or it hammers home that you haven't understood the principles & need a reread.

I'm hoping that some experienced programmers will be able to remember the first programs they wrote after they had learned some of the basics & could say what they were. Or is there a website that deals with relatively simple programming exercises so that people can practice their syntax & structure without getting confused over the complexity of the problem itself?
Advertisement
[opinion]
I agree with Oluseyi on that one. When you don't use your variables to iterate over indices, your better off with clear names.

I also think that you should not write loops in which span more than one screen e.g. so many lines of code that you can't see the beginning of the loop when you have scrolled to the end of the loop.

And that you should use constants for every constant value in your code. So
for (int cars = 10; cars < 100; ++cars){  // cars is the NUMBER of cars being used in some algorithm}


will be

for (int cars = 10; cars < MAX_NUMBER_OF_CARS; ++cars){  // cars is the NUMBER of cars being used in some algorithm}


[/opinion]

Quote: Original post by simesf
Or is there a website that deals with relatively simple programming exercises so that people can practice their syntax & structure without getting confused over the complexity of the problem itself?


I think this week we will be given a programming exercise which will be a good practice for all the the stuff you have learned so far.

It's commonly suggested that the length of variable names should be in rough proportion to the variable scope. The theory is that because shorter-lived variables are used (in the source code) less often, there's less chance of name collision, so you would save the effort for the long-lived things instead.

It has also been suggested to 'double up' single letter variables used for counters, e.g. 'for (int ii = 0; ii < some_limit; ++ii)'. The idea being that 'ii' is a lot easier to search for in the source code than 'i'. [OPINION]Personally I think this is ridiculous; it's not popular anyway, and why would you *want* to search for the counter variable? Even if you had the convention of always using 'ii', you might search for it and find that there are hundreds of such for-loops in your program, so you'd still have difficulty finding the part you were interested in. Find the loop by looking for the variable for the limit value, instead.[/OPINION]

Anyway, it's fairly common to see "paired" variable names like that, but if 'vehicle' vs. 'vehicles' throws you off, maybe 'vehicle' vs. 'vehicle_count' (or vehicleCount, according to your conventions) would work better? (Some people write num_of_vehicles or even number_of_vehicles, but that doesn't really carry any more information.)

Also, you'll really need to get used to just looking at short for-loops and envisioning them as a single process, rather than trying to envision the loop in your head. C++ does offer prettier ways to create this abstraction, but they're not in as common use as they might be; anyway, when understanding code, you generally want to be focussed on process, not details. (You focus on details when *writing* code :) And then, try to write stuff in the usual, "idiomatic" ways, so that when you read it later, you *can* focus on process rather than details.)
[opinion]

Let me add my limited experience to this, after a very short while, for loops become an extra sense, because (unless the loop is really long) you look at it and say "this stuff (the code being looped) is being looped this many times (here is when you look at the for loop's initialisation)". To me, for loops are so much more readable than while loops.

I completly agree that having two variables named vehicle and vehicles is absolutly rediculous. When you are programming, you don't differentiate between variables like that. There is only "the array" and "the counter", by the names of vehicle and vehicle. Um.. wait, let me scroll up. Oh...... vehicle is the array, and vehicles the counter... Now what was I doing???

Not good.

But yes, I do find myself cycling through loops and function calls and things like that - especially when debugging - which is often a result of either a poorly designed loop, or poorly named variables, or an extreme state of hunger. It is so much clearer to have x and y or i and j in loops than having long confusing names. However, sometimes having a properly named variable/object is better than having something called i, especially if the loop is long or complex.

[/opinion]

Have a good time!
By now I'm getting the feeling that whether to name variables i (not ii) or using longer names is a judgement call which takes into account the need to share code, your philosophy on the matter, and mindful of the particular situation. But above all it needs the 3 'c's - clear, consistent, commented. Is that a basis for my own philosophy?
Hi all, I have read the lesson but haven't practise much. I have done flow control programs but have doubts.

When is exit used? I read continue will go back to condition and run again. Break will come out of loop. Are continue,exit used together. Can someone tell with eg.


I have only tried switch case using break statment.What about continue and exit, can we use these in looping statments.

switch(option)
{
case 1:
{
stat1
stat2
break;
}
case 2:
{
stat1
stat2
break;
}
default:
{
stat1
}
}


exit() is a function. There is no exit *keyword*. exit() does magic that terminates the *entire program*, usually not very cleanly. You should probably try not to use it very much if ever. The normal way to exit a program is to reach the end of main().

'continue' skips the rest of the loop body, but may allow for the loop to keep going (it will do any post-loop stuff - like the last part of a for statement - and then evaluate the loop condition and decide if the loop should keep going as usual). 'break' inside a loop skips the rest of the loop body and also terminates the loop (i.e. the loop condition will not be evaluated and the loop is exited no matter what).
Greetings All!

It's once again QUIZ TIME!!! That's right, listed below are a set of quiz questions to help you test your knowledge and understanding of the material contained in chapters 7.

In addition to the questions and exercises below, make sure that as you're reading the book you enter the examples into your compiler, build the program, and run the executable. I know this is a time consuming process, but the repeat use of keywords, syntax, and semantics will help ingrain the information into your long-term memory. My advice is to create a simple "driver" project with a function main. As you read, enter the examples into function main, test it, and then erase it for use again in the next example.

PLEASE DO NOT POST THE ANSWERS TO THESE QUESTIONS OR EXERCISES. If you are unable to answer these questions, please ask for assistance, but DO NOT POST THE ANSWERS. Any question which is not marked with [Extra Credit] can be answered by reading your textbook. Questions which are marked [Extra Credit] either have been answered in the thread previously, or can be answered by doing a bit of research.

I will create an answer thread for these questions immediately, so that people will have a chance to get the answers more quickly.

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 windowHANDLE 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
I'm sorry to post this on this thread but there is no thread for week 6 exercises yet. Also if it's something I couldn't know about from the work we've been doing so far then maybe it would concern other learners. I'm getting the error message:

1>.\main.cpp(1) : fatal error C1083: Cannot open include file: 'windows.h': No such file or directory

I'm using Visual C++ 2005 Express Edition on XP, SP2 & working with Project: General, empty project.

If it's something I should know about then once again I'm sorry & it's time for a reread of my notes.

edit - I tried the same source code adapted to a Win32 Console Application, default settings and got a slightly different version of the same answer.

This topic is closed to new replies.

Advertisement