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

C++ Workshop - Looping & Switch Statements (Ch. 7)

Started by JWalsh Jul 10, 2006 at 11:33 AM 48 replies 40.5k views
Original Post
JWalsh
JWalsh

Welcome to the GDNet C++ Workshop – Ch. 7

For a complete introduction to this workshop, please look here. Workshop Overview This workshop is designed to aid people in their journey to learn beginning C++. This workshop is targeted at highly motivated individuals who are interested in learning C++ or who have attempted to learn C++ in the past, but found that without sufficient support and mentoring they were unable to connect all the pieces of this highly complex but powerful programming language. This is a 'guided' self-teaching C++ workshop. Each student is responsible for taking the time to read the material and learn the information. The community and tutors that arise out of this workshop are here for making the learning process run more smoothly, but are not obligated to baby-sit a person's progress. Because everyone will be working from the same textbook (Teach Yourself C++ in 21 days 5th Ed.), students may find it easier to get answers to the specific questions they might have. There is no minimum age requirement, and there is no previous programming experience required. Additionally, this workshop does not attempt to defend C++ as a language, nor does it attempt to demonstrate that C++ is either more or less useful then other programming languages for any particular purpose. People who intend to start a discussion about the differences between C++ and ANY other languages (except as are relevant to a particular discussion), are encouraged to do so elsewhere. This workshop is for educational, not philosophical discussions. Quizzes & Exercises Each week will have quizzes and exercises posted in the weekly threads. Please try and answer them by yourself. As well, please DO NOT post the answers to Quizzes and Exercises within this thread. Once it becomes acceptable to post the answers to quizzes and exercises, an additional thread will be created each week specifically for the purpose of posting quiz answers. If you try with reasonable effort but are unable to answer the questions or complete the exercises, feel free to post a clarification question here on the thread. Tutors, myself, or others will do the best we can to point you in the right direction for finding the answer.

Chapter 7 – More on Program Flow

Introduction In general there are two methods to change the flow of execution in C++. The first is branching, which we covered back in chapter 4, and includes the if, else, and switch statements. The second method is iteration. This includes the for, while, and do-while statements. By the end of this chapter you will have learned all the basic building blocks for controlling the flow of execution within a program. Additionally, you've learned how to declare variables, write expressions, create and call functions, and from last week - declare and use your own custom data types in the form of classes and objects. After this week we move on to what might be considered the more intermediate features of the language - such as pointers, operator overloading, inheritance, and polymorphism. This chapter is roughly 25 pages - shorter than the average chapter. Which is why this week is a good week to introduce your first programming project. More details on this will follow later in the week. Outline of the Reading - Chapter 7
  1. Looping
  2. Using while Loops
  3. Implementing do...while Loops
  4. Using do...while
  5. Looping with the for Statement
  6. Summing Up Loops
  7. Controlling flow with switch statements

Good Luck!

[Edited by - jwalsh on May 30, 2007 5:32:50 PM]
Fruny
Fruny

Please do not hesitate to ask questions.



  • If something is unclear to you, it is probably unclear to somebody else as well.
  • You might very well have found an error in the book that needs to be corrected.
  • It is the only way we have to judge participation, and keeps our interest up.


I had expected more questions last week: classes are a big topic. I also expect quite a few this week: control flow can be tricky.




Please do not hesitate to ask questions.


"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
simesf
simesf
Having now read some of the chapters of the book I would urge any fellow students who are using the online version to consider getting the book. I tried learning from the online version 2 years ago and I've noticed the later version of the book contains signiicantly more good information than the older online version.

The section on advanced for loops threw up a question for me. They reminded me of 'Accelerated C++' by Koening & Moo which many people swear by but I found some of the code too dense. A line of code that does one thing I find much easier than a line of code that does 4 things. But I gather there is the notion of elegant, compact code which accomplishes more things with fewer lines, which if I'm guessing right started in the days when there was precious little RAM & storage space so it had to be tight. But things have moved on and today's computers have squigglies more power & resources. So my question is; is compact / elegant / harder to read code still always favoured over looser / verbose / easier to read code? I ask this in these days of long development times, Object Oriented languages and teams of programmers as opposed to individual coders. Or is it a case of certain areas of code benefitting from dense programming while others from a clearer syntax. I'm assuming both types would be //commented.

simesf
Oluseyi
Oluseyi
Quote:
Original post by simesf
So my question is; is compact / elegant / harder to read code still always favoured over looser / verbose / easier to read code?

No.

It used to be that the primary purpose of code was to communicate your instructions to the machine, in which case conciseness and efficiency were paramount. Today, however, the primary purpose of code is to communicate with other programmers. There's a reason we've continually adopted mnemonic languages with greater abstraction from the physical hardware.

Further, today's compilers are extremely good at squeezing additional performance out of the code we write, so there's no need to go overboard trying to avoid a prefetch cache miss in your sorting routine. There's a balance to be found, of course, between expressivity and efficiency; if a piece of code is the "inner loop" of a routine, getting called potentially thousands of times per second, then efficiency in that code makes the whole program more efficient and responsive. Look for a book titled Inner Loops by Rick Booth for far more detail on the subject.

Finally, Dennis Ritchie (co-inventor of C) is alleged to have said, "You need to be twice as clever to debug a piece of code as to write it in the first place. So if you write the cleverest piece of code you can, you are by definition too dumb to debug it!" (paraphrased) [smile]
BlueShizz
BlueShizz
Quote:
Original post by OluseyiFinally, Dennis Ritchie (co-inventor of C) is alleged to have said, "You need to be twice as clever to debug a piece of code as to write it in the first place. So if you write the cleverest piece of code you can, you are by definition too dumb to debug it!" (paraphrased) [smile]

That is very true :)

Zahlman
Zahlman
[OPINION]
You should actually almost always prefer easier to read code. However, note that compact code is often *more* readable, because you're not distracted by extra syntactic details. In particular, while there's something to be said for giving a name to a subexpression (by assigning it to a variable), it's pretty hard to defend nonsense like:

if (foo.isBar()) {  return true;} else {  return false;}


when you could simply write:

return foo.isBar();

[/OPINION]

There are lots of possible factors that make code "compact" or "verbose". Even the indentation style matters, as far as first impressions go. (Pick what you like best, for your own code, and be consistent.)

Also note that "compact" code doesn't necessarily run any faster, or even compile to something different from a more "verbose" alternative, if you're doing things in basically the same way.

Some examples of what you found "hard to read" might be useful.
simesf
simesf
Well there's a wealth of information here that makes things so much clearer. Thank you.

Quote:
Original post by Zahlman

Some examples of what you found "hard to read" might be useful.


I wouldn't want to cause offence to any writers (or highlight my own lack of grey matter) by directly quoting them. But here's a small sample that slowed me down (variable names changed):

for (vehicle = 0; vehicle < vehicles; vehicle++)

for (int car = 0; car < cars; cars++)
grade[vehicle][car] = roadArray[vehicle][car];

I find the naming of vehicle & vehicles to be too close together and I lose track of which is which. Also vehicles & cars were declared a few lines earlier so I find myself backtracking to double check them. Once I've double checked what 'vehicles' is supposed to be I've overwritten in my memory the value of 'vehicle'. But they are named logically and are both more clear as individual names than i or j. Finally I have this little ritual where I hold up my left hand & say 'so this is what's in grade[vehicle][car] and its going into roadArray[vehicle][car]' (holds up right hand & waggles it about a bit in a desperate attempt to visualise.) My monitor screen now has lots of little fingermarks where I point at it with two fingers trying to figure out the program flow.

In general I've found that the more undigested new material there is in a section of code the harder it is to work it out. I also get the most confused when I'm trying to store more than 2 or 3 variable names & what they stand for / their current values to work out one expression. Multiple dimension arrays are fun too. In such a case I believe the way to do it is to work from the innermost brackets/parentheses/square brackets outwards. Is this right?

Do any of you mentors sit down with a pencil & piece of paper to work out a section of code you are not familiar with? Do you start drawing lines on the code to work out program flow? I think I would, along with little bubbles close to variables with an example value inside to picture what's happening at a particular stage. I'd try & run through with what I perceived to be the minimum & maximum values as well. Would this be a bad practice? Also I once heard a programmer at the now defunct Microprose say 'Where's my calculator?... Oh God! Look at that! A programmer without a calculator - that's not right!' Was he just having a joke? Come to think of it, I've also known another programmer who held the attitude that if you're smart enough you can read any code. In fact he was rather arrogant about it & dismissive of lesser mortals who couldn't. Is this a rare attitude or do you find a competitive element in some programmers?

I appreciate that these questions are not so much to do with understanding of code, but as a learner the thing I miss most is to physically sit next to an experienced coder and watch them in action.
RinusMaximus
RinusMaximus
For the example you give I would always use

for (i = 0; i < vehicles; i++) {   for (int j = 0; j < cars; j++) {      grade[j] = roadArray[j];   }}


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.

Although I'm only a C++ student in this course, I'm an experienced Java developer and I can say this about program flow. Once you'll start writing your own programs you'll also start to recognize the program flow by looking at a piece of code. The first time I tried to understand a two-dimensional array I had a hard time too (and it became only harder for four-dimensional arrays, because those don't look like anything in real life), but when I started to work with them it became easier to understand.

Just try to program as many things as you can. You can only become a good programmer by writing loads of code.
CondorMan
CondorMan
That's excellent advice about using i, j, k etc. in loops. I agree that the amended code is a lot easier to understand than the original with vehicle, vehicles etc. I'll incorporate this technique into my own style as it's still in it's infancy!
Oluseyi
Oluseyi
Don't make the use of i, j and k as index variables a universal dictum. In some instances you are not iterating over indices, but over values.
for (int x = 0; x < horzLimit; ++x){  // x is a horizontal displacement}...for (int cars = 10; cars < 100; ++cars){  // cars is the NUMBER of cars being used in some algorithm}

In the above two cases, i, j and k would have detracted from comprehension, not added to it.

[opinion]
Name your variables, including loop counters, according to their function - what they are used for and what they do. In fact, this should apply to all identifiers (classes, functions, etc), not just variables.
[/opinion]
simesf
simesf
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?
RinusMaximus
RinusMaximus
[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]

RinusMaximus
RinusMaximus
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.

Zahlman
Zahlman
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.)
Silvo
Silvo
[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!
simesf
simesf
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?
kimi
kimi
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
}
}


Zahlman
Zahlman
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).
JWalsh
JWalsh
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!

simesf
simesf
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.

Topic Locked

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

Sign in to reply to this topic.