Key syntax elements for lab 3

The C++ feature we will focus on for lab 3 covers pass-by-reference, recursion, and basic loops. (Refer back to the course notes or to the lab 2 syntax examples for refreshers on the syntax used earlier.)


Pass-by-reference

Remember that regular parameter passing simply passes a copy of a value, whereas pass-by-reference allows the called function to access/change the original variable passed to it.

This is done by adding the & symbol before the parameter name in the formal parameter list (in the prototype and declaration of the function).

For example, in the program below the negate function switches the passed parameter between positive and negative.
#include <iostream>
using namespace std;

void negate(float &orig);

int main()
{
    int x = 3;
    negate(x);
    // x has now been changed to -3
    cout << x << endl;
}

void negate(float &orig)
{
   // replace the original value with the opposite
   orig = - orig;
}


Recursion

The appropriate use of recursion is to have an if statement that checks for a base case (or stopping condition), and otherwise issues a recursive call with a slightly different parameter list.

For example, the sum function below adds all the integers from M to N, and returns the result:

int sum(int M, int N)
{
   // base case: if M > N return 0
   if (M > N) {
      return 0;
   }

   // general case, M must be <= N,
   //    so compute the sum from (M+1) to N,
   //       add M to that,
   //    and return the result
   int result = M + sum(M+1, N);
   return result;
}

So if our main routine contained something like
    x = sum(5,9);
then the sequence of events would be

 1. sum(5,9) calls sum(6,9) and waits for an answer
 2.    sum(6,9) calls sum(7,9) and waits for an answer
 3.       sum(7,9) calls sum(8,9) and waits for an answer
 4.          sum(8,9) calls sum(9,9) and waits for an answer
 5.             sum(9,9) calls sum(10,9) and waits for an answer
 6.                now in sum(10,9), M > N so it returns 0
 7.             now sum(9,9) can return 9+0, i.e. 9
 8.          now sum(8,9) can return 8+9, i.e. 17
 9.      now sum(7,9) can return 7+17, i.e. 24
10.    now sum(6,9) can return 6+24, i.e. 30
11. now sum(5,9) can return 5+30, i.e. 35


Loops

The C++ syntax we will focus on for lab 5 covers while loops, do-while loops, and for loops.