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

Started by
48 comments, last by Dbproguy 15 years, 11 months ago

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]
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

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

[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.
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.
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.
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!
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]

This topic is closed to new replies.

Advertisement