Lab 1: C++ Overview & Comparison to Java

Complete the following lab by Thursday, January 27. Create a lab1 directory for your work and tar the files in the directory and send the tar file to me ingram@roanoke.edu.

Getting Started: Create a directory for this lab. You can either download the example programs to your directory from the Web as you go through this (go to the course web page at http://cs.roanoke.edu/Spring2011/CPSC270A to get this web page) OR just copy them all to your directory using cp as follows (assuming you are in your directory for this lab):

      cp ~cpsc/public_html/Spring2011/CPSC270A/lab1/*.java .
      cp ~cpsc/public_html/Spring2011/CPSC270A/lab1/*.cc .
    

Basic Structure

Input/Output

C++ input and output is done using objects and operators in the C++ library. For standard I/O the functions are in the iostream library files. C++ also has a language mechanism for grouping declarations of identifiers. This mechanism is called a namespace. An identifier declared within a namespace can be directly accessed by statements within the namespace. Other statements must indicate what namespace is being used. Identifiers in the iostream library are declared in the std namespace. Basic I/O in a C++ program is done as follows:

Compiling and Linking

Compilation in C++ results in an executable file (unlike Java where the result is bytecode which must then be interpreted). The compile command is g++. There are options that can be included: Exercise: The file hello.cc contains the "Hello World!" program from above. Compile it in the two stages and create an executable named hello. Run the program.

Data Types and Basic Syntax

  • C++ uses the same identifiers for basic data types: int, float, double, long, short.

  • The syntax of basic programming constructs such as assignment statements, expressions, if statements, switch statements, and loops (for, while, and do) is the same in C++ and Java.

  • Exercise: Modify hello.cc to input the number of times the user wants to print the "Hello World!" message then print the message that many times. Number the messages - 1.Hello World, 2. Hello World...). Compile and run the program.

  • Booleans in C++ are very different! In C++ zero means false and any non-zero value means true. This can get you into trouble! Consider the following:
          if (n = 0)
            ...
    
    What would happen in Java if you had this in your program? How would it be interpreted in C++?

    Exercise: See if you were correct by examining the behavior of JavaIf.java and CPlusIf.cc.

    1. Examine the code for each - same program, different languages.
    2. Compile and run the Java program (javac JavaIf.java then java JavaIf). What happened? Why?
    3. Compile the C++ program. Run it. Try different input values (including 0) and see what it does. What is happening? Why is it happening? Describe what happens when the code is executed and why that gives the observed behavior.

    Type bool: Even though zero means false and any nonzero value means true in C++, most implementations of C++ have added type bool which includes identifiers true and false. This type should be used in programs rather than using integers. However be aware that underneath booleans are still integers - true is actually stored as 1 and false is 0.

    The boolean operators in C++ are the same as in Java: &&, ||, !

    Functions and Parameter Passing

    Good programming dictates that we divide our program into logical tasks and use functions (or methods) to carry out each task. The syntax for a function definition in C++ is similar to that in Java in that there is a header and a body. The following is a function that finds and returns the area of a rectangle given the length and width.
    
         int area (int length, int width)
         {
            return length * width;
         }
    

    The default mode of parameter passing in C++, as in Java, is pass by value. Parameters passed this way are not changed by the function (method) because the value of the actual parameter is copied into the formal parameter and the formal parameter is what the function uses. But in Java, because the "value" of an object variable is a reference, the reference isn't changed but the object it refers to can be changed. Java has no provision for passing a parameter that is a primitive data type in a way that lets the method change the actual parameter but C++ does allow passing by reference.

    To pass a parameter by reference in C++ you use the ampersand symbol (which denotes the address of a variable) in the header for the function. So, the following would pass the first two parameters by reference and the third one by value:

         void doStuff (int& a, int& b, int c)
         {
            c = c * 2;
            a = a + c;
            b = b - c;
         }
    
    A call to the function would just use the int variables for the actual parameters - the address of the first two would be passed. For example,
           int m = 150;
           int n = 100;
           int p = 5;
           doStuff(m,n,p);
    

    Placement of Functions in a File

    In C++ a function has a declaration (just the header) and a definition (the header plus the body). Unlike Java, a function must be physically declared before it can be used. Often declarations are in a separate file (called a header file) that is included in the file that uses the function. Most of the time we will use separate header files but for simple programs you can put your functions in one file with the main function. There are two options for doing this.

    Method #1: Define the function before it is used. The file ReferenceParameters1.cc uses this method for the doStuff function above.

    Method #2: Declare the function near the beginning of the file; define it after main. When you do this it is standard practice to just list the type of each parameter in the declaration (when it is separate from the definition). In this example the declaration would be:

          void doStuff (int&, int&, int);
    

    The file ReferenceParameters2.cc is the same program as above but using this method.

    Exercise:

    1. Study, compile, and run both versions to make sure you understand how the functions are declared and defined, what happens and how reference and value parameters differ.
    2. In the second version comment out the declaration of doStuff at the top of the file. What happens when you compile? Why?

    Final Exercises:

    1. Create a C++ program to find the reciprocal of a nonzero integer using the following code (type it as is).
          int n;
          double x;
      
          cout << "Enter a nonzero integer: ";
          cin >> n;
      
          while (n = 0)  {
            cout << "0 is not valid - try again: ";
            cin >> n;
          }
      
          // ASSERT: n is not zero - it is safe to divide
          x = 1 / n;
      
          cout << "The reciprocal of " << n << " is " << x << endl;
      
      
      1. Compile and run the program with the following input for n: 0, 5, -20. For each input, what output does the program produce?
      2. Explain what is going on to produce the output shown. That is, describe exactly how the computer is executing each statement. (NOTE: Don't just say what is wrong with the code! Explain how the computer is executing the incorrect code.)
      3. Correct the code.

    2. Write a C++ program that implements the Euclidean algorithm given in the book (so use a loop not recursion). Add a counter to count the number of times the loop executes. Print the GCD and the number of times the loop executes (the number of divisions).

    3. Write a C++ program to implement the algorithm for computing the floor of the square root of n (problem #4 on page 8) just using basic arithmetic (no built in functions - just add, subtract, multiply, divide as needed). Your algorithm should be as simple as possible! Your program should use a function to compute and return the floor. Use the method of placing the function declaration before main and the function definition after.