Source Code. Projects. Nerd Stuff. Art Stuff.

Lesson 6: Loops

Loops

Loops

  • loop – a way of repeating a block of code while a specified condition is true. Use a loop when you want to repeat a task.
  • “while” loops have two main formats:
    • Condition evaluated at beginning, loop body executes only if condition is true:
            while( <condition> )
            {
              <loop body>
            }
    • Condition evaluated at end, loop body always executed at least once, then repeated only if condition is true:
            do
            {
              <loop body>
            }while( <condition> );
  • Notice the placement of semi-colons above.
  • Beware of infinite loops!
  • Notice that “do” cannot stand alone. “do” is only used at the beginning of a do…while loop.
  • Rules regarding use of curly braces “{” and “}” – If you want more than one line of code in the result/body of an if-statement, else-statement, or loop, then that result/body code must be enclosed by curly braces. They define a block of code with its own scope (We’ll learn more about this later.)

Examples of while loops

  • InvestLoop.cpp: Here’s a program that uses a loop to add up interest on an investment over time
  • In-class exercise: Write a program that outputs “hello” to the user as many times as specified. So ask the user how many times to repeat the greeting, then use a loop to output it that many times. For an extra challenge, alternate between captial and lower-case words, such as:
      How many times should I say hello? 5
      hello HELLO hello HELLO hello
  • HelloLoop.cpp: Solution to above exercise.
  • InvestAgain.cpp: Variation of above Invest program that allows user to repeat the calculation as many times as user wants.
  • Retire.cpp: another example which calculates results of monthly retirement savings
  • Eclipse and other IDEs allow you to stop at a breakpoint and step through your code, facilitating debugging.

Advanced Loop Control: break and continue

  • break – a C++ statement that is used only inside a loop or switch structure, to exit that structure and move on with what follows it.
  • continue – a C++ statement that is used only inside a loop, to skip the rest of the loop body, and test the loop condition again, starting a new iteration if the condition is true.
  • NestedControlStructure.cpp inputs and shows student info with if-else-if inside loop
  • NestedAlt.cpp: Alternate version of above using “break”
  • In-class exercise: Write a program that inputs numbers from the user, using -1 to terminate the input. The program should then display the average of all the numbers, and how many were entered.
  • averageNumbers.cpp: Solution to above in-class exercise to average and count numbers input by user

For-loops

  • A for-loop is another loop structure. All loops could be written using while as you’ve already learned, but some loops are easier to write with a for-loop structure (especially counting loops).
  • Here is the general template of a for-loop. It consists of 3 parts separated by semi-colons, and a loop body:
    for(<initialization expression> ; <loop condition> ; <update expression>)
    {
      <loop body>
    }
  • initialization expression – This code is executed only once, before any other part of the loop. Often used to initialize a counting variable, e.g.
    1
    i = 0

  • loop condition – This code is executed after the initialization expression. If it evaluates to true then the loop body is executed. If it’s false then the loop is finished and the program continues with the next line after the loop’s closing curly brace } . Often used to express the boundary for the counting variable, e.g.
    1
    i &lt; 10

  • update expression – This code is executed after the loop body each time the loop body is executed. It’s often used to increment a counting variable, e.g.
    1
    i++

    Just after the update expression, the loop condition is evaluated, and maybe the loop continues or maybe it stops, depending on the condition’s truth or falsehood.

  • loop body – just like in a while-loop, this is the code that is repeated as long as the condition is true. If there are no curly braces {} then the loop body is the one line of code after the closing parenthesis, ending with a semi-colon. The curly braces allow the loop body to have as many lines as you wish.
  • So the following code would produce identical behavior to the above loop, using while:
        <initialization expression>;
        while(<loop condition>)
        {
          <loop body>
          <update expression>;
        }
  • As our programs get more complicated, indentation, formatting, and comments/documentation become more important. Please make sure to follow those standards.
  • In-class exercise: Change the program InvestLoop.cpp to make it use a for-loop instead of a while loop. (Look closely at the output that’s inside the loop!)
  • InvestFor.cpp: Solution to above in-class exercise. Same as InvestLoop.cpp, but using a for-loop instead of a while-loop.

Nested Loops

  • Loops can be nested, one inside another, as in the InvestAgain.cpp program shown above. If an outer loop repeats x times, and it has an inner loop that repeats y times, how many times does the loop body of the inner loop repeat?
  • AddMoney.cpp demonstrates nested switch statements, for loops, and boolean varaibles
  • In-class exercise: Write a program with nested loops that outputs a rectangle made of a character the user enters, with 5 lines of a width entered by the user:
      Please enter a character: +
      Please enter the width of the rectangle: 3
      +++
      +++
      +++
      +++
      +++
  • Rectangle.cpp: Solution to above exercise

File Input Until End of File, including Error Detection

Recall that to work with file i/o we need to include the fstream library with the statement:

1
  #include &lt;fstream&gt;

This allows us access to the ifstream class for input from a file, and the ofstream class for output to a file. We declare an input file stream with the following statement:

1
  ifstream file_in;

Then we open the file and verify that it opened correctly:

1
2
3
  file_in.open("scorefile.txt"); // Your filename here
if (!file_in)
// handle it, e.g. tell user we couldn't open file, exit program

Once a file stream is open we use it in much the same way as we use cin and cout. So to input a value from a file that is whitespace-delimited, we write:

1
2
  float one_score;
file_in &gt;&gt; one_score;

Or to input the next line of text including spaces or anything else, we write:

1
2
  char line[100];
file_in.getline(line, 100);

To test whether we’ve attempted to go past the end of the file yet, we use the member function eof:

  file_in.getline(line, 100);  // Get a line to start with
  while (!file_in.eof()) // Loop while we haven't passed end of file
  {
    cout << line << endl;    // Output the line to the screen
    file_in.getline(line, 100);   // Get the next line from the file
  }

The above code will display on the screen the exact contents of the file, including whitespace. (Assuming each line has fewer than 100 characters)

Another way of detecting the end of the file is to use the input expression as our loop condition. So to output all the numbers from a whitespace-delimited file onto the screen:

  while(file_in >> one_score)
    cout << one_score << " ";

Example program: gradeStats.cppdemonstrates basic file I/O of numeric data, with loops and error checking

In class exercise: Write a program to output the largest number from a file such as this:

bash-2.04$ aCC -AA FileLoop.cpp
bash-2.04$ a.out
Unable to open scorefile.txt
bash-2.04$ pico scorefile.txt
           // I entered scorefile.txt here.  So now:
bash-2.04$ cat scorefile.txt
50 75 100
75 85 65
bash-2.04$ a.out
The highest number in scorefile.txt is: 100
bash-2.04$

BiggestInFile.cpp:Solution to above in-class exercise outputing the largest number from a file.