Lab #6, Friday, 2/23

The purpose of this lab is to give you more recursion practice and introduce you to command line arguments.

1)  Write a program that implements problem #3 from the midterm. In this problem you were asked to write the isSorted function so that it recursively returns true if the first n elements of the array are sorted, and false otherwise. You should not need to change any code in main for your function to operate. You should also not use any global variables.

Here is a sample call:
  int test1[] = {1,2,3};
  int test2[] = {6,2,4};

  cout << isSorted(test1,3) << endl; // Outputs 1 for true
  cout << isSorted(test2,3) << endl; // Outputs 0 for false


2) In C++ we can specify the following for main:

       int main(int argc, char *argv[])            

These parameters are used when the program is invoked from the command line. The parameter argc tells us how many arguments are used in invoking the program. This includes the program name itself. For example if we run the program using:

Then argc would equal 1 because the only parameter is the program name of ./a.out.  If we run the program using:
       ./a.out 45 10            
Then argc would equal 3 because there are three parameters (./a.out, 45, and 10). The argv parameter is an array of char pointers (i.e. cstrings). argv[0] points to a cstring that represents the first argument (e.g. ./a.out), argv[1] points to a cstring that represents the second argument (e.g. 45) and so on.  Here is an example program that outputs all of the command line arguments.  We haven't covered pointers yet, but you can think of this as basically an array of strings. You will probably want to run this on the unix machine or some other place where it is easy to supply command line arguments:
#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[])
  for (int i = 0; i < argc; i++)
    cout << argv[i] << endl;
  return 0;

Modify this program so that it multiplies all of the numbers sent in on the command line.  It should take an arbitrary number of values.  You can assume they are all integers.  For example, here is a sample run:

[kjmock@transformer test]$ ./a.out 2 4 6

To convert a cstring into an integer, you can use the atoi function.  For example, atoi("20") returns back the integer 20.


Show your programs to the lab assistant for credit, or email to by midnight for lab credit.