C++ Hardest New Concept

I teach C++ programming to beginners. All of them seem to quickly understand simple programs like “Hello World.” They can get the logic down fairly well in simple flow charts. But where they seem to have the most struggles is with loops, especially “for” Loops. The odd thing, they seem to understand while loops and do-while loops more quickly than for loops. They understand that while loops will skip the execution of the code within the while loop if the condition is false. One gave the example of checking the chemicals in a pool to a do-while loop. You need to check the chemical level at least once. If the level is not within the specified “safe” range, then the system will do something to fix the problem and then retest. This will repeat until the chemical levels are within the “safe” parameters.

Students seem to understand that within the while(condition) statement (either at the beginning or end of the loop), the looping will continuing as long as the condition is true. The for loop is like a while loop, except it has all three main parts within the for statement:

  1. the initialization of the variable, like int i = 0
  2. the check the value of the variable to make sure that it meets the condition to continue the loop.
  3. the change of the variable by the desired amount, usually incrementing or decrementing the variable.

A for-loop looks like:

for (initialization, condition, change)

where the condition is the test to see if the looping needs to continue, identical to the condition in a while or do-while loop. a for loop may look like:

for (int i = 0; i < 5; i++) {
    // Do something 5 times.
}

The three parts of a for statement are separated by semi-colons (;), just like at the end of a C++ statement. In the above for-loop:

  1. i is specified as an integer and set to 0.
  2. The condition for the loop to continue is i being less than 5.
  3. At the end of each loop, i is incremented by one.

I tell my class that the only way they can fully understand and appreciate for loops is to write code that uses them, when they need to loop through a specific set of code a specific number of times. The first code I give them to use a for loop is to create a 12×12 multiplication table. Of course, then they want to learn about formatted printing, but that is another story.

This entry was posted in C++, Code Reviews, Computers, Do, Mentor, Software, Uncategorized. Bookmark the permalink.