C++ Lab 2 - The Basics, An Overview

Copy the example programs from the course home page to your directory for this lab as follows (assuming you are currently in the directory):
    cp ~cpsc/public_html/Spring2009/CPSC270A/lab2/*.cc .

More about booleans

We saw last time that in C++ zero means false and any nonzero value means true. However, 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 true is actually stored as 1 and false is 0.

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

Strings in C++

A string in C++ is an array of characters (type char) that has the null character (escape sequence \0) at the end. The null character is automatically added to the characters in a string when the string is read in or is assigned as a literal. The program StringBasics.cc gives an example. This program uses two functions provided by C++ - the sizeof function can be applied to any variable to find out how much space (number of bytes) the variable occupies. The function strlen is a function in the standard library that gives the number of characters in the string.

Compile and run the program. Note that for the string literal the number of bytes is one more than the number of characters - that accounts for the null character. For the string you typed in, the number of bytes is the number declared for the array.

Exercise:

  1. See what happens when you try assigning strings. There is already a declaration for string3 in the program. Add an assignment statement to assign string3 to be the same as string1. Try compiling and see what the error message is.

  2. Now change your assignment to assign string3 to be the same as string2. Try compiling. This is a more general error message that applies to any type of array in C++.

  3. Add code to the program to print the second string backwards. To do this you need to process the array character by character using usual array indexing (no "charAt" method!).

NOTE: Modern versions of C++ also have a string type that we will examine later. It has much more flexibility.

Reading in Strings

If you didn't already do it run the program above again entering a string with more than one word. Do it again putting several white space characters in front of the sentence. What happened?

You should have noticed that cin skips over whitespace and stops reading at whitespace. So it doesn't work to read a whole line that may contain spaces. To do that you need to use one of the functions get or getline that operate on cin.

The program ReadStrings.cc reads in two lines of text and prints them. Note the alternate syntax for using get and getline.

Exercise:

  1. Study the code then compile and run the program.
  2. Comment out the line that adds the null character. Run the program at least twice:
    1. Enter a shorter string for the second input than the first. What happened?
    2. Enter a longer string for the second but less than the maximum length. What happened?

The point - if you create your own string character by character you must explicitly add the null character to the end.

Char

Variables and literals of type char can be manipulated just as in Java. Casting to an int gives the ASCII code and casting an int to char gives the character. The program Frequency.cc reads in a string character by character and determines the frequency of each letter in the alphabet. Study the code to be sure you understand it. Compile and run.

Using Files

The program FileIO.cc shows how to open files, use them (read from and write to), and close them. It reads a list of integers and finds the sum and average. It prints the number of integers read, the sum, and the average to another file. Note that the file stream must explicitly be closed.

Exercise:

  1. Study the program to see what is going on.
  2. Create an input file the meets the specifications - include at least 5 integers for the data. Run your program then examine the output file.
  3. Run the program entering the name of a non-existent file for the input file. What happens?
  4. Delete a data integer from your input file. Run the program to see what happens.
  5. Change the parameter type to the function processInput from ifstream to istream. In the C++ library, an ifstream is derived from an istream; that is, an ifstream is an istream. Compile the program. What is the error and what does it mean?
  6. Now, move the statement inFile.close() from inside the function processInput to main just before the call to the function writeOutput. Compile the program. Why are there no errors this time? Link and run the program to make sure it is correct.

Homework

  1. Euclidean Algorithm - Again
        // GCD finds the greatest common divisor of two non-negative
        // integers m and n, not both 0
        GCD(m,n) 
          while (n is not 0) do
            if (m > n)
              m <- m - n
            else
              n <- n - m
          // ASSERT:  n is 0; m is the gcd 
          return m
    
    
    Understand why this is the same as the algorithm in the book except it repeatedly subtracts instead of dividing.

  2. Figure out a formula for the number of "moves" (numbers that can be written as the difference of two numbers already on the board) that can be made in Euclid's game as follows:
    1. Write the numbers that can be written starting with 13 and 2. Write these in the order they would be played. (One way to do this is to start with Euclid's algorithm.)
    2. Do the same thing starting with 12 and 5.
    3. Do the same thing starting with 24 and 9.
    4. Do the same thing starting with 18 and 10.
    5. Find a formula for the number of numbers that can be written if you start with m and n.
    6. Based on your formula conclude when you should go first and when you should go second.

  3. Redo: For #1 on page 23-24, carefully trace the algorithm for the following list: 601, 35, 602, 98. For your trace explicitly show the contents of Count after each pass for i (i = 0, i = 1, etc.). Also show exactly how S is formed (follow the algorithm in the order S is formed). Then answer part (b).

  4. Write a C++ program that implements the string-matching algorithm referred to in problem #3 on page 24. Use a function that is called from main for your algorithm. In particular your program should take in a line of text and another string (which may contain spaces). It should return the index of the first character in the string if the string is found in the text or -1 if the string is not in the text. Note: You only need to find the first instance of the string in the case that it appears more than once.

  5. Write a C++ program that implements an anagram checking algorithm (problem #10 on page 39). You may assume the two strings have no whitespace.