In-class Examples for CISC-1600-E01 and CISC-1610-E01

Definitions:
computer, program, language, superset, subset

A computer is a machine that follows instructions. The list of instructions you put into the computer is called a program. In the future, it will be possible to write programs in English. But that day hasn’t come yet, so for the time being we write programs in simpler languages such as C++. This is a course in writing, reading, executing, and debugging programs in C++. This language is an extension of the earlier language C. In other words, C++ is a superset of C, and C is a subset of C++.

CISC-1600 will cover the C subset of C++, except for pointers, structures, and pointers to structures. The rest of C++, including the techniques for object-oriented programming, will be covered in CISC-2000.

Output

Our first C++ programs must tell the computer to produce output; otherwise we would never know if the programs were executed correctly, or even if they were executed at all.

dime1.C:

  1. A program is written as one or more files (documents). On our Fedora Linux server storm.cis.fordham.com, the filename ends with .C (uppercase); on other machines, the filename might end with .CPP or .CXX.
  2. A C++ program is case-sensitive: it makes a difference if you write in uppercase or lowercase.
  3. Produce output to verify that the program ran.
  4. std::cout means “the outside world, considered as a destination for output”. This output will be a stream of characters; that’s what the c in cout stands for. A namespace is a family of things that share the same last name, in this case the name std. Last name first, first name last. No space between the two colons. #include a header file.
  5. The << (“put to”) operator points towards the destination. No space between <’s; type it exactly the way I do.
  6. "double-quoted" strings and the invisible newline (\n). 24 characters, followed by the newline character, followed by the terminating zero character.
  7. Semicolon (;) at the end of each statement.
  8. A C++ program consists of sections called functions. Even if you have no desire to divide the program into functions, the program must still consist of one big function. The one big function must be named main. The lines
    int main()
    {
    
    mark the start of the main function; the line
    }
    
    marks the end. The body of the function is the statements between the two curly braces. Conventional to indent the body of the function by one tab. The parentheses will not be used until later; we still have to write them even though they’re empty.
  9. Return an int from the main function to the operating system: EXIT_SUCCESS for success, EXIT_FAILURE for failure. Another header file.
    1. Unix Korn and Bash shells (including Macintosh Terminal): echo $?
    2. Unix C shell: echo $status
    3. Windows Command Prompt: echo %errorlevel%
    Windows: system("PAUSE");
  10. Header files, where to find them on storm.cis.fordham.edu:
    1. /usr/include/c++/14/iostream
    2. /usr/include/c++/14/cstdlib for EXIT_SUCCESS
    We have verison 14.2.1 of the C++ compiler:
    c++ -v
    Search for a file with a given name on storm.cis.fordham.edu:
    find / -type f -name iostream 2> /dev/null
  11. Comments:
    1. // for single-line
    2. /* */ for multi-line
  12. What happens if you accidentally omit a semicolon, double quote, comment delimiter, etc.?
  13. Log into the Fedora Linux server storm.cis.fordham.edu and explore your account. See below.
  14. variations on dime1.C:
    1. dime2.C no newlines
    2. dime3.C double spaced
    3. dime4.C using namespace std (p. 52)
    4. dime5.C perform all output with one statement (only one semicolon)
    5. dime6.C one multi-line statement
  15. Homework: flag.C: Put in a using directive to get on a first-name basis with cout. Do all the output with only one statement, not ten statements. Run the program and deposit the output into a file named flag.txt. Copy the program and flag.txt into your public_html directory so everybody can see these two files.
  16. Exercise: invisible characters (pp. 53–54). Can your hear three beeps when you run the following program? Turn up the volume if necessary.
    	//This is only one statement, not a complete C++ program.
    	//Output three copies of the ASCII "alarm" character.
    
    	std::cout << "\a\a\a\n";
    
  17. Exercise. Unreachable code. What happens if you insert a statement after the return?
    	//Not a complete C++ program.
    
    	return EXIT_SUCCESS;
    	std::cout << "Never reaches this point.\n";
    }
    

Connect to storm.cis.fordham.edu from room 317 Keating

You will need your Fordham credentials, i.e., your Fordham email name and password. If you’ve never gotten them, go to my.fordham.edu and click on the red “New user: Claim account”.

    Roll the wheel on the mouse to wake up the screen. It will say
    Fordham University Access Warning.
    Press the OK button because you belong to Fordham.

    Then log in with your Fordham credentials, i.e., your Fordham email name and password.
    User name:
    Password:
    It will say Preparing Windows.

    At lower left, it will say Type here to search: cmd
    It will say Command Prompt System
    At right, click on Open.
    It will say Microsoft Corporation. All rights reserved.

    Launch the “secure shell” by typing
    ssh jsmith@storm.cis.fordham.edu
    It will say Are you sure you want to continue connecting? yes
    jsmith@storm.cis.fordham.edu’s password: type your temporary four-word password
    You should now be connected to the Fedora Linux server storm.cis.fordham.edu. It will ask you to change your password. When you’re finished changing your password, try a few simple Linux command such as date or cal.

Explore the directories in storm.cis.fordham.edu:
cd, pwd, ls -l

The
@storm:~$
or the
jsmith@storm:~/public_html$
that keeps reappearing is the prompt. Case counts.

jsmith@storm:~$ date
jsmith@storm:~$ cal

jsmith@storm:~$ cd                (Go to your personal "home" directory on storm.cis.fordham.edu)
jsmith@storm:~$ pwd               (Make sure you arrived there.)
jsmith@storm:~$ ls -l             (See what's there.  Ignore the "total".)

jsmith@storm:~$ cd public_html    (Go down to your public_htm directory; space before public_html, with underscore _)
jsmith@storm:~/public_html$ pwd
jsmith@storm:~/public_html$ ls -l

jsmith@storm:~/public_html$ cd ..             (Go one level upstairs; space before, but not in between, the two periods.)
jsmith@storm:~$ pwd
jsmith@storm:~$ ls -l

Go on an expedition to the top of the tree of directories.

Download, compile, and execute a C++ program

“Compiler” means “translator”. Out compiler c++ will translate your C++ program into terms that storm.cis.fordham.edu can understand and execute. The compiler will place the translation into a new file named a.out.

jsmith@storm:~$ cd
jsmith@storm:~$ pwd
jsmith@storm:~$ ls -l

jsmith@storm:~$ wget https://markmeretzky.com/fordham/1600/src/dime/dime1.C
jsmith@storm:~$ ls -l
jsmith@storm:~$ cat dime1.C      (See what's in the new file dime1.C.)

jsmith@storm:~$ c++ dime1.C
jsmith@storm:~$ ls -l            (There should be a new file named "a.out".  Do not cat this file.)
jsmith@storm:~$ ./a.out          (Execute the a.out file in the current directory.)

jsmith@storm:~$ ./a.out > dime1.txt     (Execute the a.out file and deposit its output into dime1.txt)
jsmith@storm:~$ ls -l            (See if there's a new file named "dime1.txt" in the current directory.)
jsmith@storm:~$ cat dime1.txt    (See what's in the new file dime1.txt.)

See the C++ program and its output on the web

jsmith@storm:~$ cd
jsmith@storm:~$ pwd
jsmith@storm:~$ ls -l

jsmith@storm:~$ cp dime1.C public_html      (Copy the file dime1.C into your public_html directory.)
jsmith@storm:~$ cp dime1.txt public_html    (Copy the file dime1.txt into your public_html directory.)

jsmith@storm:~$ cd public_html
jsmith@storm:~$ pwd
jsmith@storm:~$ ls -l                       (Are there two new files in the public_html directory?)

To see the two files dime1.C and dime1.txt that you just copied into your public_html directory, point your web browser at
https://storm.cis.fordham.edu/~jsmith/dime1.C
https://storm.cis.fordham.edu/~jsmith/dime1.txt
Or you can simply click on your loginname at
https://markmeretzky.com/fordham/1600/students.html

Clean up (if desired)

jsmith@storm:~$ cd            (Go to the directory that holds the file you want to remove, in this case your own home directory.)
jsmith@storm:~$ pwd
jsmith@storm:~$ ls -l

jsmith@storm:~$ rm dime1.txt  (Remove the dime1.txt that's in your home directory)
jsmith@storm:~$ ls -l         (Make sure the file dime1.txt is gone.)

Practice using the Linux vi (“visual”) editor

There’s even an O’Reilly book and pocket reference about vi.

jsmith@storm:~$ cd
jsmith@storm:~$ pwd
jsmith@storm:~$ ls -l

jsmith@storm:~$ wget https://markmeretzky.com/fordham/1600/src/xanadu.txt
jsmith@storm:~$ ls -l

jsmith@storm:~$ vi xanadu.txt
jsmith@storm:~$ ls -l        (Is the number of bytes in xanadu.txt different now?)

A minimal set of vi commands.
When in doubt, press the ESCape key in the upper left corner of the keyboard, to make sure you’re not in “insert mode”.

  1. Move the cursor around with the four arrow keys;     10G
  2. Delete individual character(s) with x, 4x
  3. Delete entire line(s) with dd, 4dd
  4. Insert character(s) with i (before) or a (after the cursor).
    Stop inserting with the ESCape key.
  5. Insert entire line(s) with lowercase o (below) or uppercase O (above the cursor).
    Stop inserting with the ESCape key.
  6. Write the file to disk with (lowercase) :w
  7. Quit vi with (lowercase) :q

Logging out in room 317 Keating

  1. Type
    jsmith@storm:~$ exit
    
    to log off from storm.cis.fordham.edu.
  2. Type another exit to log off from the black Microsoft cmd window.
  3. Click on the white windowpanes in the lower left corner and select “Sign out” to log off from Microsoft Windows.

Variables and input

A variable is a container inside the computer that can contain a value such as

Four definitions:

  1. variable1.C: define, declare, and initialize a variable all in one statement. Then output the contents of the variable.
    What goes wrong if you try to output the content of the variable (i.e., the number 10) this way?
    	cout << "The variable contains price.\n";
    
  2. variable2.C: Assign a new value to the variable.
    That’s why it’s called a “variable”—its content can vary.
    Information always travels from right to left across an equal sign.
  3. variable3.C: Old-fashioned (pre-2011) way to define a variable.
  4. variable4.C: What’s the biggest number this type of variable can hold?
    maxInt is “camel case”, EXIT_SUCCESS and numeric_limits are “snake case”.
    Note that the number 2,147,483,647 isn’t arbitrary:
    231 = 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = 2,147,483,648
    (pronounced “2 billion, 147 million, 483 thousand, and 648”).
    Check this with bc, the Linux “binary calculator”. The keystroke control-d tells bc that you’re not planning to type in any more arithmetic problems for it.
    jsmith@storm:~$ bc -l
    2^31
    2147483648
    control-d
    jsmith@storm:~$ 
    
    See Why do the possible values for an int go from -2,147,483,648 to +2,147,483,647?
  5. variable5.C: input a value from the outside world and store it into a variable. Check that the input was successful.
    jsmith@storm:~$ cd
    jsmith@storm:~$ pwd
    jsmith@storm:~$ ls -l
    
    jsmith@storm:~$ wget https://markmeretzky.com/fordham/1600/src/variable/variable5.C
    jsmith@storm:~$ c++ variable5.C
    jsmith@storm:~$ ls -l
    
    jsmith@storm:~$ ./a.out
    Please type the price and press RETURN.
    13
    The variable contains 13.
    jsmith@storm:~$ echo $?
    0                  (EXIT_SUCCESS stands for this number.)
    
    jsmith@storm:~$ ./a.out
    Please type the price and press RETURN.
    hello
    Sorry, that wasn't an acceptable number.
    jsmith@storm:~$ echo $?
    1                  (EXIT_FAILURE stands for this number.)
    
    Exercise. What happens if you try to input an out-of-bounds value such as 2147483648 or -2147483649 into the variable? What is the invisible exit status number?
  6. Feed input into the C++ program (variable5.C) from an input file (thirteen.txt), instead of from the keyboard. First create a very small file containing the two digits 13 and a newline, a total of just three characters. We could create this little file with vi, but it’s easier to create it with echo.
    jsmith@storm:~$ cd
    jsmith@storm:~$ pwd
    jsmith@storm:~$ ls -l
    
    jsmith@storm:~$ echo 13        (echo is the Linux "print" command.)
    13
    
    jsmith@storm:~$ echo 13 > thirteen.txt
    jsmith@storm:~$ ls -l          (There should be a new file named "thirteen.txt".)
    
    jsmith@storm:~$ cat thirteen.txt
    13
    
    jsmith@storm:~$ ./a.out < thirteen.txt
    Please type the price and press RETURN.
    The variable contains 13.
    
    jsmith@storm:~$ ./a.out < thirteen.txt > variable5.txt
    jsmith@storm:~$ ls -l
    
    jsmith@storm:~$ cat variable5.txt
    Please type the price and press RETURN.
    The variable contains 13.
    

The other built-in data types

  1. integer.C. Define (i.e., create) variables of the other signed integer data types. Exercises. What is 263? What is 215? Why am I asking about these powers?
  2. double.C. Define variables of types that can hold a number with a fraction.
  3. format.C. Output more (or fewer) of the digits of a double.
    Compile with the command line option -std=c++20 because std::format is a new feature available in the C++20 version of the language C++.
  4. bool.C. A variable of type int can hold one of 4,294,967,296 different values, from -2,147,483,648 to 2,147,483,647 inclusive.
    A variable of type bool can hold one of only 2 different values.
    Exercise. Change true to false in this program.
  5. char.C. On storm.cis.fordham.edu, a variable of type char can hold the code number of a single ASCII character.
    That’s all it can hold: one number, representing one character.
  6. string.C. A variable of type std::string can hold a string (series) of characters.

Expressions, and how to compute their value

Definitions.

  1. places.C: three places where we can write an expression in a C++ program.
  2. An expression could be built out of literals
    	int i {10 + 20}; //i is born holding 30
    
    or out of variables that are currently holding a value:
    	int j {10};      //j is born holding 10
    	int k {j + 20};  //k is born holding 30
    
    Don’t do this:
    	int j;           //j is born containing unpredictable garbage
    	int k {j + 20};  //k is born containing bigger unpredictable garbage
    
    And the following snippet will be totally rejected by our C++ compiler c++. The program won’t even “compile”.
    	int k {j + 20};  //The computer doesn't know yet what "j" means.
    	int j {10};
    
  3. precedence.C:
    * (multiplication, line 5) has higher precedence then + (addition, line 6).
    - (negative, line 3) has higher precedence then - (subtraction, line 6).
    See lines 5 and 6 of this table.
    Note that - (negative, line 3) is a unary operator, while - (minus, line 6) is a binary operator. That’s how you tell them apart.
  4. associativity.C: addition and subtraction have left-to-right associativity.
    See line 6 of this table (the rightmost column).
  5. lobster.C. Example of an expression.
     

    Then you bank the heat and let the kettle simmer—ten minutes for the first pound of lobster, then three minutes for each pound after that. (This is assuming you’ve got hard shell lobsters, which, again, if you don’t live between Boston and Halifax is probably what you’ve got. For shedders [soft-shell], you’re supposed to subtract three minutes from the total.)

     
    David Foster Wallace, Consider the Lobster

Division, quotient, and remainder

  1. byzero1.C. Another warning: do not divide by zero. Attempts to perform double and int division by zero behave differently. On storm.cis.fordham.edu, a C++ program that attempts to perform int division by zero is assassinated by the operating system with a little bullet called a signal. An assassinated program never lives long enough to return EXIT_SUCCESS.
    jsmith@storm:~$ cd
    jsmith@storm:~$ pwd
    
    jsmith@storm:~$ wget https://markmeretzky.com/fordham/1600/src/division/byzero1.C
    jsmith@storm:~$ ls -l        (Make sure there is a new file named byzero1.C)
    
    jsmith@storm:~$ c++ byzero1.C
    byzero1.C: In function ‘int main()’:
    byzero1.C:10:20: warning: division by zero
    jsmith@storm:~$ ls -l        (Make sure there is a new file named a.out)
    
    jsmith@storm:~$ ./a.out
    inf
    The above quotient was infinity.
    
    Floating point exception (core dumped)
    jsmith@storm:~$ echo $?
    136     (This number is not EXIT_SUCCESS.  Subtract 128 to find out the cause of death.)
    
    There are many types of signals, each with its own identifying number. 136 − 128 = 8. Signal number 8 is SIGFPE, the “floating point exception” signal. It means that the C++ program was assassinated while attempting arithmetic.
  2. byzero2.C. Use an if statement to guard against attempted division by zero.
  3. division.C. Warning: int division “truncates” (get chopped down to the next integer).
  4. remainder.C. Introducing the remainder operarator %. Even though int division truncates, you might still want to do it together with int remainder.
  5. Quotient and remainder exercises.
    1. 1613 pennies is 16 dollars and 13 cents.
      (1 dollar = 100 cents.)
    2. 27 bottles is 4 sixpacks and 3 bottles.
      (1 sixpack = 6 bottles.)
    3. 400 minutes is 6 hours and 40 minutes.
      (1 hour = 160 minutes.)
    4. 35 ounces is 2 pounds and 3 ounces.
      (1 pound = 16 ounces.)
    5. 7 quarts is 1 gallon and 3 quarts.
      (1 gallon = 4 quarts.)

Operators that have a side effect

We are used to thinking of the four symbols   +   -   *   /   as the only operators.
But other symbols, such as   =   <<   >>   ++   --   are also operators.
This means that an entire statement such as

	i = j + k;
is actually one big expression, consisting of two operators (+ and =) and three operands (i, j, k).

Some operators do nothing more than compute a value.
An example is the + operator when applied to ints:                                  y + x     10 + 20
Other operators also have side effects. For example,

  1. precedence2.C.
    * (multiplication, line 5) has higher precedence than = (assignment, line 16).
    * (multiplication line 5) has higher precedence than << (output, line 7).
    See lines 5, 16, and 7 of this table.
  2. associativity2.C.
    << (output, line 7) and >> (input, line 7) have left-to-right associativity.
    = (assignment, line 16) has right-to-left associativity. See lines 5, 7, and 16 of this table.
  3. assignment.C. The assignment operators:     +=     -=     *=     /=     etc.
  4. increment.C. The increment and decrement operators:     ++     --     (that’s two dashes)
    This is how the C++ language got its name: it’s a little better than the older language C.

Expression homework

Invent something like the following. Each program will get input from cin, and, if the input was successful, will store the input into one or more variables. Decide if each variable should be an int or a double, and pick a good name for each variable, Write an expression to compute the answer. Store the value of the expression into another variable, and then feed this other variable to cout.

  1. [1 human year = 7 dog years.
    Good names for the two variables might be humanYears and dogYears.]
    How old are you? 20
    That’s 140 dog years!
  2. [Cook the turkey for 13 minutes per pound.]
    How many pounds does the turkey weigh? 12
    Then you have to cook it for 146 minutes.
    That’s 2 hours and 26 minutes.
  3. [Define four variables to hold the four input numbers.]
    How many pennies do you have? 3
    How many nickles do you have? 5
    How many dimes do you have? 10
    How many quarters do you have? 6
    Then you have a total of 268 cents.
    That’s 2 dollars and 68 cents.
  4. [Dolbear’s law: chirps per 15 seconds, plus 40, equals Fahrenheit.]
    How many times did the cricket chirp in 15 seconds? 30
    Then the temperature is 70 degrees Fahrenheit.
    That’s 21.1111 degrees Celsius.
  5. How many quarters do you need for the washer? 20
    How many quarters do you need for the dryer? 5
    Then you need a total of 25 quarters.
    That’s 6 dollars, and maybe some change.
    [If we had already covered if statements, I could ask you to put the “and maybe some change” into an if statement because we don’t always want to output this phrase. But we haven’t, so I can’t.]
  6. [1 degree = π/180 radians.]
    What is the size of your angle in degrees? 90
    Then the size of your angle in radians is 1.5708
  7. [The New York City taxi fare (not counting the various surcharges) is three dollars, plus 70¢ for each 1/5 mile.]
    How many miles are you going? 3
    The taxi ride will cost 13.5 dollars.

Control Structure: the most important part of the course

Loops: while, for, do-while

  1. nottoprogram.C: how not to program.
    Conventional to count from 0 to 9 inclusive, not from 1 to 10 inclusive, because “array subscripts” will start at 0.
  2. while.C: while loop has same (parentheses) and {curly braces} braces as the if statement. Prefix increment operator ++.
    1. 0 to 9 (inclusive) by 1’s: the < operator
    2. 10 to 20 (inclusive) by 1’s
    3. 10 to 20 (inclusive) by 2’s: the three vital statistics
    4. 1 to 1,024 = 210 (inclusive), doubling each time.
      Humans like to see a column of strings left justified, a column of numbers right justified.
         1     John
         2     Joe
         4     Joey
         8     Jacob
        16     Jake
        32
        64
       128
       256
       512
      1024
      
      #include <iomanip>    //for setw (means "set width")
      
      		cout << setw(4) << "\n";   //right justify
      
    5. count down from 9 to 0 (inclusive): the prefix decrement operator -- (two minus signs, no space between them)
    6. How long does it take to loop a billion times (e.g., from 0 to 999,999,999 inclusive)? Don’t output the numbers.
      jsmith@storm:~$ time ./a.out
      
    7. iterate zero times
  3. for loops:
    1. for1.C. Put all three vital statistics on the same line: start, end, stride.
    2. for2.C: make the induction variable i local to the for loop.
    3. beer.C: A Hundred Bottles of Beer on the Wall.
      Interrupt the C++ program with the keystroke control-c.
    4. stylesheet1.C and stylesheet1.html. Direct the output into an output file named stylesheet1.html
      jsmith@storm:~$ cd
      jsmith@storm:~$ pwd
      
      jsmith@storm:~$ wget https://markmeretzky.com/fordham/1600/src/loop/stylesheet1.C
      jsmith@storm:~$ ls -l        (There should be a new file named stylesheet1.C)
      jsmith@storm:~$ c++ stylesheet1.C
      
      jsmith@storm:~$ ./a.out > stylesheet1.html
      jsmith@storm:~$ ls -l        (There should be a new file named stylesheet1.html)
      jsmith@storm:~$ cp stylesheet1.html public_html
      
      Then point your web browser at
      https://storm.cis.fordham.edu/~jsmith/stylesheet1.html
      where jsmith is your Fordham login name.
    5. infinite.C: an infinite loop.
      Interrupt the C++ program with the keystroke control-c.
    6. pierogies.C: needs only one variable, h.
    7. thruway.C: needs only one variable. Typical sign.
    8. Add up all the integers from 1 to 100 inclusive. (The sum should be 5,050.)
      1. sum1.C: do it all with one big expression.
      2. sum2.C: do it with a series of small expressions
      3. sum3.C: write the small expression only once, inside a for loop.
      Now modify sum3.C to add up all the integers from 1 to 1,000,000 inclusive. The sum should be 500,000,500,000—about five hundred billion—well beyond the maximum capacity of a variable of data type int. You will therefore have to change the data type of the variable sum from plain old int to the long int that we saw here. (For the expression (n + 1) * n / 2 you will also have to change the data type of the variable n from int to long int.) What will happen if you don’t?
    9. Make an investment grow at 6% per year annually for 10 years.
      1. product1.C: do it all with one big expression. pow
      2. product2.C: do it with a series of small expressions.
      3. product3.C: write the small expression only once, inside a for loop.
      Exercise. Let the user input the principal (into a double variable named principal), the number of years (into an int variable named nyears), and the rate of interest (into a double variable named rate).
      	double rate {0.0};
      	cout << "What is the interest rate?\n";
      	cin >> rate;
      
      	if (!cin) {
      		//Ouput an error message to cerr and return EXIT_FAILURE
      	}
      	//Also make sure the rate is a reasonable (e.g., positive) number.
      
      	//Each year, multiply the principal by the following factor.
      	//For example, if rate is 6, then factor will be 1.06
      	double factor {1.00 + .01 * rate};
      
    10. organ.C: Make a one-octave set of organ pipes.
    11. converge.C: converge on the value of
      π = 4/1 − 4/3 + 4/5 − 4/7 + 4/9 − 4/11 + 4/13 …
  4. dowhile.C: do-while loop has test at the bottom. Always iterates at least once.

Nested loops

  1. lucy1.C and lucy2.C produce exactly the same output. Lucy in the Sky With Diamonds.
    Exercise. Could you output the 25 lowercase a’s with a for loop?
  2. line.C and rectangle.C.
  3. Graph paper. Exercise: add the missing right and bottom edges.
    1. graph1.C: no loop, hardwired to do 10 rows and 10 columns
    2. graph2.C: one loop, inputs the number of rows, hardwired to output 10 columns.
    3. graph3.C: nested loops, inputs the number of rows and columns.
    4. Homework. Let the user input the following four numbers when outputting graph paper. For simplicity, allow the right and bottom edges to remain ragged. Here are two examples:
      How many rows of boxes? 2
      How many columns of boxes? 4
      How many rows of blanks in each box (e.g., 1)? 1
      How many columns of blanks in each box (e.g., 3)? 4
      
      +----+----+----+----
      |    |    |    |
      +----+----+----+----
      |    |    |    |
      
      How many rows of boxes? 2
      How many columns of boxes? 4
      How many rows of blanks in each box (e.g., 1)? 3
      How many columns of blanks in each box (e.g., 3)? 8
      
      +--------+--------+--------+--------
      |        |        |        |
      |        |        |        |
      |        |        |        |
      +--------+--------+--------+--------
      |        |        |        |
      |        |        |        |
      |        |        |        |
      
  4. solid.C: Make a solid colored flag.
    jsmith@storm:~$ cd
    jsmith@storm:~$ wget https://markmeretzky.com/fordham/1600/src/nested/solid.C
    jsmith@storm:~$ ls -l      (Should be a new file named solid.C)
    
    jsmith@storm:~$ c++ solid.C
    jsmith@storm:~$ ls -l      (Should be a new file named a.out)
    
    
  5. factor.C: find the prime factors of an integer. Only need to chack factors that are less than or equal to factor <= sqrt(n), so #include <cmath>

if statements

  1. if.C: An if statement.
  2. else1.C and else2.C: if-else statement.
  3. if_in_then1.C and if_in_then2.C: put a smaller if into the then section of a larger if that has no else.
  4. if_in_else1.C and if_in_else2.C: put a smaller if into the else section of a larger if.
  5. Chains of else-if:
    1. threeway.C: steer the computer in one of three possible directions.
    2. chance.C: keep giving the user another chance to enter valid input.
    3. The Metro-North evacuation instructions:
      1. Remain inside the train if possible. If not …
      2. Go to next car through end doors. If Unable …
      3. Open side door and get out. If you can’t …
      4. Go out emergency windows.
      if (it is possible to remain inside the train) {
      	remain inside the train;
      } else if (you are able to go to next car through end doors) {
      	go to next car through end doors;
      } else if (you can open the side door and get out) {
      	open the side door and get out;
      } else {
      	go out emergency windows;
      }
      
    4. leap.C: steer the computer in one of four possible directions.
    5. ordinal1.C and ordinal2.C: steer the computer in one of five possible directions. && means “and”.
  6. else-if inside a loop
    1. toolow.C, the dowhile.C guessing game with hints. break out of an infinite loop.
    2. range.C: for (;;) loop containing three-way if. Make sure input was successful and value in range. Also &&, and break.
    3. flag gateway: three-way if
    4. sine.C and sine.gif: three-way if. Plot sine curve in front of axes. Scale it vertically and horizontally.
    5. Mandelbrot set: mandelbrot.C and mandelbrot.gif.
  7. switch and case: can be used only if all the comparisons are for equality to integral values (int, char, bool, etc.) that are constants, not variables.
    1. switch1.C: if-else.
    2. switch2.C: switch, case, break.
    3. switch3.C: remove the break’s.

Data types

  1. integer.C: The four types of integers: signed char, short, int, long. Use signed char for a small integer, char for a character. Integer division truncates; don’t divide by zero. By default, signed char prints as a character; cast (i.e., convert) it to int with static_cast to see it as a decimal integer. One single-quoted character stands for the code number of that character in the local character set.
  2. limits.C: Include the header file <climits> for the macros CHAR_BIT, SCHAR_MIN, etc. (Better yet, we will eventually include the header file <limits> for the template class numeric_limits.) A data type used as the operand of sizeof must be in parentheses. On my platform, the minimum and maximum values, inclusive, are as follows.
    signed char:                –128 to                       127
    short:                   –32,768 to                    32,767
    int:              –2,147,483,648 to             2,147,483,647
    long:             –2,147,483,648 to             2,147,483,647
    
  3. char1.C: and char2.C: use the data type char to hold a character. (What it really holds is the character’s code number.) char1.C works only for ASCII; char2.C works for any character set that can be held in a char (e.g., EBCDIC). The cast prevents the char argument of isprint from sign extending as it is converted to int.
  4. wchar_t.C: a wide characters is 4 bytes on my machine. Bloodshed does not recognize the object wcout. In g++ on i5.nyu.edu, wcout stops outputting when you feed it a wchar_t containing a number >= 256.
  5. bool.C: A bool can hold one of exactly two possible values.
  6. float1.C: float, double, long double. Format with fixed and setprecision; see Chapter 4, pp. 355–356.
  7. float2.C: minimum and maximum values.
  8. float3.C: static_cast.
  9. Examples of double arithmetic:
    1. gallon.C: double division does not truncate. if-else containing an assignment statement. numeric_limits gives value of ∞. We could have initialized mpg with a ?: expression:
      	const double mpg = gallons == 0
                      ? numeric_limits<double>::infinity()
                      : miles / gallons;
      
    2. interest.C and the approximation 72.C (see the Rule of 72): how many years does it take for the principal to double? double arithmetic for money, do-while loop, natural log function.
      1.06 × 1.06 × 1.06 × … = 2
      1.06y = 2
      (eln 1.06)y = eln 2
      (ln 1.06)y = ln 2
      y =
      ln 2
      ln 1.06
    3. organ.C: organ pipes spanning one octave. Raise a number to a power with the pow function.
    4. Random numbers, needed for pi.C:
      1. random1.C: the rand function returns random integers in the range 0 to RAND_MAX inclusive.
      2. random2.C: the srand function. Different random numbers each time you run the program. Convert the return value of time from time_t to unsigned.
      3. random3.C: random integers in the range 0 to 99 inclusive.
      4. random4.C: random fractions in the range 0 to 1 inclusive.
    5. ../../../INFO1-CE9264/src/pi.C: compute π by the Monte Carlo method. Seed the random number generator with time and srand. Eliminate the call to the sqrt function by squaring both sides of the inequality. For double absolute value, call fabs in C, abs in C++.
  10. mother.C: search for a small string in a big one. The data type string string (short for basic_string of chars) is not built into the language; must include the header file <string>. npos has the last name string, just as cout has the last name std.

Arrays

  1. array1.C and array2.C: array of int’s. Initial value for each array element. Use the data type size_t for a variable that holds the number of elements in an array, or that holds an array subscript. It is probably unnecessary to include the header file <cstddef> for size_t, since one of the other header files probably includes that one.
  2. array3.C: an array of string’s
  3. monkey1.C: the Year of the Monkey. Use % to compute the subscript of an element in an array of string’s.
    monkey2.C: same program, but with if statements instead of array.
    monkey3.C: same program, but with switch.
  4. plot.C: from the Movie Plot Generator book.
  5. dependents1.C and dependents2.C: number of dependents, without and with an array.
  6. date.C: pretend that there is no such thing as a leap year in the following homework. Don’t worry about time and localtime; we’ll do them after we do structures, functions, and pointers.
    1. Break distance into years and days, where days is in the range 0 to 364 inclusive. (Break distance down the same way we broke 205 minutes into 3 hours and 25 minutes, or 205 cents into 2 dollars and 5 cents. You fail the course if you break distance down like this:
      	int years = distance / 365 * 365;
      	int days = distance - 365 * years;
      
      ) For the time being, assume that the user will input a non-negative distance. You can then add years to year, leaping in a single bound to within one year of the destination.
    2. Now allow the user to input a negative distance. Break distance into years and days as above. Then if days turns out to be negative (as a result of a negative distance), add 365 to days to make days non-negative (guaranteeing that days will now be in the range 0 to 364 inclusive), and compensate for the addition by subtracting 1 from years. For example, on some machines a distance of –367 days will break down into a quotient of –2 years and a remainder of 363 days (two years backwards and 363 days forwards). On other machines, a distance of –367 days will break down into a quotient of –1 year and a remainder of –2 days (one year backwards and an additional 2 days backwards). If your machine breaks –367 down into a quotient of –1 year and a remainder of –2 days, change it to a quotient of –2 years and a remainder of 363 days. Making days non-negative will make your loop much simpler. You get no credit if there is more than one loop. For example, do not write two loops, one to go forward and one to go back.
    3. Make the loop stride the rest of the way to the destination one month at a time, not one day at a time. You get no credit if there is more than one loop. For example, do not write two loops, one to go forward and one to go back.
  7. Output the lyrics to a song whose verses get longer and longer:
    1. The Twelve Days of Christmas
    2. Green Grow the Rushes, O
    3. There’s a Hole in the Bottom of the Sea
    4. אֶחָד מִי יוׄדֵעַ
      Output Unicode character codes in hexadecimal (e.g., the eight characters &#x05D0; are א) and display the output file in a web browser.
    5. etc.
  8. bubblesort.C: sort in increasing and decreasing order. Right justify with setw. bubblesortstrings.C: sort strings in alphabetical order.
  9. howrandom.C: how random are the random numbers we get from srand and rand? Write into an uninitialized array, and then read from it.
  10. twod.C: a two-dimensional array.
  11. sudoku.C: If the top row of a Sudoku has exactly one missing number, fill it in.
    1. Do the same for each of the other eight rows.
    2. Do the same for each of the nine columns.
    3. Do the same for each of the nine 3 × 3 regions.
    4. Repeat all of the above as long as progress is being made.
    5. After you break out of the loop, print the puzzle.
  12. Manhattan street numbers: street1.C (no array), street2.C (one-dimensional array), street3.C (two-dimensional array).
  13. avenue.C: Manhattan Avenues

Structures and Arrays Thereof

  1. struct.C: a structure containing two fields. Define the structure data type outside of main, even though we don’t need to yet.
  2. single1.C: a single array of structures instead of the two parallel arrays in parallel.C or avenue.C
  3. Make plot.C smart enough to know that a singular subject (“A single mom”) takes a singular verb (“fights crime”), while a plural subject (“Three naughty nurses”) takes a plural verb (“fight crime”). You’ll be able to get rid of all those parenthesized letters (“fight(s) crime”). Change subject from an array of strings to an array of structures. Each structure will have two fields: a size_t (0 for singular, 1 for plural) and a string giving the subject of the sentence. Change predicate from a one-dimensional array of strings to a two-dimensional array of strings (30 or more rows and 2 columns). Column 0 will contain predicates with a singular verb ("fights crime"). Column 1 will contain the corresponding predicates with plural verbs ("fight crime"). You can use the idiom sizeof arrayname / sizeof arrayname[0] to get the number of rows in the predicate array. Print out the predicate that agrees in number with the subject. No if statements are required for this homework. If you write if statements, your code is unnecessarily complicated. Entertain me by inventing additional subjects, predicates, and modifiers.
  4. rose.C: two-dimensional array of structures draws this picture of sine in polar coördinates.

Functions, arguments, and return values

  1. function1.C and function2.C: consolidate repeated chunks of code, with a loop if consecutive, with a function otherwise. Function must be declared before it is otherwise mentioned. Secret Agent Man: audio.
  2. automatic.C: a variable defined in a function (factorial) is automatically allocated: it lives only while we are within the {curly braces} of the function. Factorial is the number of permutations.
  3. argument.C: pass an argument by value to a function.
  4. retval.C: return a value from a function. The main function has been returning int all along.
  5. static.C: a statically allocated variable is immortal.
  6. weekday.C: a function that is called from only two places. Package code as a function to divide the program into cleanly separated sections.
  7. Functions are how a C++ program communicates with the underlying operating system:
    1. Microsoft Windows input
    2. time.C. We saw the time and localtime functions in date.C.
  8. How to do recursion.
    1. Do the work in a separate function, not in the main function.
    2. The function should do only the first part of the job (e.g., print the first number, perform the first multiplication).
    3. The function should call itself to do the rest of the job. Remember to scrape off the part of the job that has already been done.
    4. The call to itself must be inside an if that does the call only if there is still part of the job remains undone.
  9. Examples of recursion.
    1. rprint.C: print the integers from 1 to 10 inclusive. The starting point is passed as an argument; the ending point 10 and the stride 1 are hard-wired into the recursive function.
    2. end.C: pass the ending point as a second argument.
    3. stride.C: pass the stride as a third argument.
    4. factorial.C: compute the factorial of a number without a for loop.
    5. macguffin.C and macguffin1.C: search without a loop.
    6. gcd.C: can you write this without a loop? Use GCD to find aspect ratio of screen: 1027 × 768.

Scope

  1. samename.C: a global variable, and a global variable with the same name as a local variable. The unary scope resolution operator ::.
  2. Define a variable (const or non-const) or a function (inline or non-inline) in one .C file, and mention it in another.
    1. without a header (.h) file
    2. with a header file. A header should contain declarations, not definitions. Only static variables and functions can be defined in a header. #ifndef to prevent a .C file from including the same header twice.
    3. static global variables and functions. A const global variable is static by default.

Pointers and References

  1. Pointer to a variable that is not an element of an array: Chapter 1, p. 44
  2. reference.C: pass-by-value vs. pass by reference. One motivation for pointers is to allow a function to change the value of its argument.
  3. pass_array.C: an array is always passed by reference. This array is one-dimensional.
  4. pass_array2.C: pass a two-dimensional array to a function.
  5. pp.C: a pointer to a pointer
  6. Pointer to a variable that is an element of an array: Chapter 1, p. 46. Another motivation for pointers is to loop through an array faster than with a size_t subscript in square brackets.
  7. moving.C: compute the moving average of a series of numbers. Replace i and j with two pointers named p and q as in the above bubblesort.C and the sort.C in Chapter 1, p. 48.
  8. Pointer to a variable that is a structure: Chapter 1, p. 49
  9. Pointer to a structure in an array of structures: single1.C and single2.C
  10. Const Pointers: Chapter 1, p. 51
  11. References: Chapter 1, p. 72

Improvements to Functions

Chapter 1, p. 81. Global functions and variables, extern, header files.

TCP/IP

  1. Echo server and client
  2. A primitive web browser that downloads one web page.
  3. The same program, for Microsoft Windows with Bloodshed Dev-Cpp.

SQLite database

Next time

Things to do differently, next time I teach this course:

  1. When data types are first introduced, introduce only int and double.
  2. Use Avogadro’s number to show the difference between fixed and scientific notation.