INFO1-CE9264 Source Code
(a.k.a X52.9264 and Y12.1003)

Definitions:
computer, program, language,
project, file, function

A computer is a machine that follows instructions. A program is the list of instructions for the computer to execute. Someday programs will be written in English. Until then, programs are written in simpler languages such as C or C++.

Printing

  1. http://oit2.scps.nyu.edu/~meretzkm/INFO1-CE9264/src/hello.C:
    1. A program is written as one or more files (documents). On my Fedora Linux box oit2.scps.nyu.edu, the filename ends with .C (uppercase); on your machine, the filename might end with .CPP or .CXX. On some systems, the files that make up the program are held in a project. A C++ program is case-sensitive: it makes a difference if you write in uppercase or lowercase.
    2. Produce output to verify that the program ran. "double-quoted" strings and the newline (\n).
    3. Two built-in destinations for characters:
      1. std::cout for standard output (the output producted by the program)
      2. std::cerr for standard error output (error messages)
      A namespace is a family of things that share the same last name, in this case std. No space between colons.
    4. The << operator points towards the destination. No space between <’s; type it exactly the way I do.
    5. Semicolon at end of each statement.
    6. 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. Conventional to indent the body of the function one tab. The parentheses will not be used until later; we still have to write them even though they’re empty. This pattern will appear often:
      keyword (parentheses) {curly braces}.
    7. Return an int from the main function to the operating system: EXIT_SUCCESS for success, EXIT_FAILURE for failure.
      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");
    8. Header files, showing where to find them on i5.nyu.edu:
      1. /opt/gcc453/include/c++/4.5.3/iostream for cout, cerr, <<
      2. /opt/gcc453/include/c++/4.5.3/cstdlib for EXIT_SUCCESS
    9. Comments:
      1. // for single-line
      2. /* */ for multi-line
    10. What happens if you omit a semicolon, double quote, etc.?
    11. Run in Bloodshed, Windows command prompt, and Unix. cerr is immune to >, so send input prompts to cerr when the standard out is directed into a file. If you said system("PAUSE");, you will have to press any key to continue.
      1. prog.exe > output.txt
      2. prog.exe 2> errors.txt
      3. prog.exe > output.txt 2> errors.txt
      4. prog.exe > both.txt 2>&1
  2. using.C: A namespace is a family of things that share the same last name. using gets us on a first-name basis with all the members of a namespace.
  3. Newlines: dime1.C and dime2.C.
  4. flag.C: 10 lines of output. Later we’ll do all the output in a single statement:
    	cout << "* * * * * * =====================\n"
    	     << " * * * * *  =====================\n"
    	     << "* * * * * * =====================\n"
    	     << " * * * * *  =====================\n"
    	     << "* * * * * * =====================\n"
    	     << "=================================\n"
    	     << "=================================\n"
    	     << "=========E pluribus unum=========\n"
    	     << "=================================\n"
    	     << "=================================\n";
    
  5. batman.bmp. My friend tried it and came up with “Cat Woman”.

Variables

  1. variable.C: create int variables and give them an initial value. Send several items to the same destination in a single statement; retrofit this technique into flag.C.
  2. minimum.C: the minimum and maximum value that can be held in an int may be different on each platform. INT_MIN, INT_MAX. The header file climits (known as limits.h in the languge C) has its own Wikipedia article.
  3. expression.C: An expression is made of operands and operators. The operands could be literals (10, 20, 30) or variables (i, j, k). The operators could be + * / etc. Override operator precedence and associativity with parentheses. Table of precedence and associativity on page 6 of Chapter 1. Examples of different associativities:
    //left-to-right associativity
    a + b + c		//order doesn't matter: you get the same sum either way
    cout << a << " " << b << " " << c << "\n";	//order does matter
    
    //right-to-left associativity
    c = b = a = 10;
    ++*p
    *++p
    a ? b : c ? d : e
    
    Expressions where some of the operators are executed in an unpredictable order:
    a * b + c * d	//can't predict which multiplication is performed first
    f() + g()	//can't predict which function is called first
    
    int a[100];
    int i = 10;
    a[i] = ++i;	//puts the value 11 into either a[10] or a[11]
    
  4. remainder.C: division and remainder. Integer division truncates. Unportable results for negative numbers. Unpredictable behavior for division by zero; what is the exit status?
  5. assign.C: Assign a new value to a variable. The new value can be an expression, possibly mentioning the same variable. Integer overflow. Can’t assign to a const variable.
  6. jobdone1.C: when will the job be done? An i/o manipulator that takes an argument (setfill, setw) requires <iomanip>.
  7. input.C: std::cin is the standard input. Check for input failure (e.g., a word instead of a whole number; an integer that is too big or too small to fit in an int; premature end-of-input; or hardware failure). if statement has same (parentheses) and {curly braces} braces as the main function. EXIT_FAILURE; check the exit status.
    1. prog.exe < input.txt
  8. Input in Microsoft Windows.
  9. Homework: age.C, wait.C, cents.C, turkey.C, change.C.
    1 human year = 7 dog years.
     

    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

Control Structure

Loops: while, for, do-while

  1. nottoprogram.C: how not to program. Idiom is to count from 0 to 9 inclusive, not from 1 to 10 inclusive.
  2. while.C: while loop has same (parentheses) and {curly braces} braces as the main function and the if statement. Conventional to count from 0 to 9 inclusive, not 1 to 10 inclusive, because array subscripts will start at 0. Prefix increment operator ++.
    1. 0 to 10 by 1’s: the <= operator
    2. 10 to 20 by 1’s
    3. 10 to 20 by 2’s: the three vital statistics
    4. 1 to 536,870,912 = 229 (the next-to-largest power of 2 that will fit in a 32-bit integer), doubling each time
    5. count down: prefix decrement operator –– (two minus signs, no space between them)
    6. How long does it take to loop through all four billion (232 = 4,294,967,296) integer values?
    7. iterate zero times
  3. for1.C: put all three vital statistics on the same line.
  4. for2.C: make i local to the loop. How long does it take to loop a billion times?
  5. beer.C: A Hundred Bottles of Beer on the Wall
  6. infinite.C: an infinite loop
  7. pierogies.C: needs only one variable
  8. thruway.C: needs only one variable
  9. dowhile.C: do-while loop has test at the bottom. Always iterates at least once.

Nested loops

  1. lucy1.C: and lucy2.C: Lucy in the Sky With Diamonds
  2. line.C and rectangle.C. A Scratch script rectangle.sb.
  3. Graph paper. Add the missing left 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 do 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. factor.C: find the prime factors of an integer. Only need to loop as far as factor <= sqrt(n).

if statements

  1. if.C: if statement
  2. Examples of if:
    1. input.C: we already checked the health of cin.
    2. isprime.C. if to verify that input was sucessful. do-while loop until input is correct.
  3. else1.C and else2.C: if-else statement.
  4. 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.
  5. if_in_else1.C and if_in_else2.C: put a smaller if into the else section of a larger if.
  6. 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”.
  7. 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.
  8. 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. 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