\documentclass{article}
\usepackage{alltt}
\usepackage{geometry}
\geometry{right=2in, left=1in, top=1in, bottom=1in}
\newcommand{\code}[1]{\texttt{#1}}
\newcommand{\newcode}[1]{\texttt{#1}\marginpar{\centerline{\textit{#1}}}}
\newcommand{\term}[1]{\textit{#1}\marginpar{\centerline{\textit{#1}}}}
\newenvironment{sourcecode}{\begin{quote}\tt}{\end{quote}}
\newenvironment{coutput}{\begin{quote}\tt}{\end{quote}}
\newcommand{\imply}[1]{\texttt{\textit{#1}}}
\newcommand{\bs}{\char92}
\newcommand{\n}{\bs{}n}
\newcommand{\cout}[1]{\texttt{#1}}
\newcommand{\Smile}{\texttt{:)}}
\newcommand{\kbd}[1]{\texttt{\textit{#1}}}
\newcommand{\filename}[1]{\texttt{#1}}
\newcommand{\calckey}[1]{\texttt{#1}}
\newcommand{\book}[1]{\textit{#1}}
\begin{document}
   \title{Linux Users' Group of Davis\\C Programming Basics, Part II}
   \author{Speaker: Mark K.~Kim}
   \date{December 6, 1999}
   \maketitle

   \tableofcontents
   \listoftables

   \section{Recap}
      We learned to write simple C programs in our last discussion.
      More specifically, we learned to:
      \begin{itemize}
         \item compile C programs,
         \item print text and numbers to the screen,
         \item read numbers from the keyboard,
         \item repeat a block of codes many times,\\
            (using the \code{while} keyword,)
         \item branch off to different parts of the program
            depending on the program state,\\
            (using the \code{if} keyword,)
         \item and write customized functions.
      \end{itemize}
      In addition, we also learned to use various C functions.

      Now, we're ready to learn various features of C
      (a.k.a.\ the ``details.'')
      We'll also learn to use several useful C functions
      not mentioned in our last discussion.


   \section{Variables---Places to store values}
      We often need to store things in memory;
      perhaps a string of text or numbers.

      In~C, you generally do not access the memory directly.
      Instead you tell C what you want to store in memory,
      and what you want to call that part of the memory.
      Then you can access the memory using that name.

      These names you use to access the memory are called \term{variables}.
      \emph{What} you want to store in the memory---text or number
      or whatever---are called \term{data types}.

      \subsection{Characters, integers, and real numbers---and many more}
         \begin{table}
            \begin{center}
            \begin{tabular}{|c|c|p{2.5in}|}
               \hline
               \bf Data type & \bf Range & \bf Description\\
               \hline
               \code{void}   & N/A           & ``No type'' type\\
               \code{char}   & $-2^7$ to $2^7-1$       & Character\\
               \code{int}    & $-2^{31}$ to $2^{31}-1$ & Integer\\
               \code{float}  & $\approx 6$ digits of precision & Real number
                  (decimal point numbers)\\
               \hline
               \code{short}  & $-2^{15}$ to $2^{15}-1$ & Integer\\
               \code{long}   & $-2^{31}$ to $2^{31}-1$ & Integer\\
               \code{double} & $\approx 10$ digits of precision & Real number\\
               \hline
            \end{tabular}
            \end{center}
            \caption{Commonly used data types and their sizes in memory.}
            \label{table:variables}
         \end{table}
         You can store various types of variables in memory.
         The most common types of data types
         are listed in table~\ref{table:variables}.

         \begin{table}
            \begin{center}
            \begin{tabular}{|c|p{4in}|}
               \hline
               \bf Qualifier   & Description\\
               \hline
               \code{unsigned} & Doubles the capacity of
                  integers and real numbers,
                  but you lose the ability to store negative numbers.\\
               \code{signed}   & Undoes the effect of \code{unsigned}.\\
               \code{const}    & Prevents the variable from changing.\\
               \hline
            \end{tabular}
            \end{center}
            \caption{Simple qualifiers.}
            \label{table:simplevarmods}
         \end{table}
         In addition to the data types, you can also add \term{qualifiers}
         to slightly modify the behavior of the data types.
         Some of the simple qualifiers are listed in
         table~\ref{table:simplevarmods}.

      \subsection{Creating many, many variables at once---arrays}
         Sometimes you want to create many variables at once.
         Like when you create a database.
         Or if you are dealing with a vector of numbers or something.

         In those cases, it's tedious to create many variables
         one by one:
         \begin{sourcecode}
            \begin{alltt}
int age\_of\_lugod\_member1;
int age\_of\_lugod\_member2;
int age\_of\_lugod\_member3;
 \vdots
int age\_of\_lugod\_member\imply{N};\end{alltt}
         \end{sourcecode}
         That's a lot of work!

         Instead, C can create many variables for you.
         It's called an \term{array} and it looks like:
         \begin{sourcecode}
            \begin{alltt}
int age\_of\_lugod\_member[\imply{N}];\end{alltt}
         \end{sourcecode}
         Then you can read from or write to any of the \term{elements}
         of the array by changing the \term{index} number inside
         the brackets, like this:
         \begin{sourcecode}
            \begin{alltt}
age\_of\_lugod\_member[\imply{0}] = 18;
age\_of\_lugod\_member[\imply{1}] = 21;
age\_of\_lugod\_member[\imply{2}] = 19;
 \vdots
age\_of\_lugod\_member[\imply{N-1}] = 20;\end{alltt}
         \end{sourcecode}
         Notice the first index starts at 0 and the last index
         is one less than the size of the array.

         The arrays are most useful when you are trying to
         initialize the entire element or print the entire element.
         For example,
         \begin{sourcecode}
            \begin{alltt}
int i = 0;

/* Set everyone's default age to 20 */
while(i < N) \{
   age\_of\_lugod\_member[i] = 20;
   i = i + 1;
\}

/* I know I'm 21 */
age\_of\_lugod\_member[7] = 21;

/* Print everyone's ages */
i = 0;
while(i < N) \{
   printf("Member \%i is \%i years old.\n", i, age\_of\_lugod\_member[i]);
   i = i + 1;
\}\end{alltt}
         \end{sourcecode}
         You do have to be careful when you use arrays.
         Because C trusts the programmer to know what s/he is doing,
         it lets the programmer access elements beyond the maximum
         array length;
         the effect is usually either corrupted memory or
         program crash (ever heard of ``general protection fault?'')
         But this technique can be used to your advantage
         if you are careful at using it.

      \subsection{String of text}

         If you have an array of characters---it's just like having
         a string of text.
         In C, you treat character arrays as strings of text
         (strings of text are often referred to as \term{strings}.)

         So, you can do:
         \begin{sourcecode}
            \begin{alltt}
char s[80] = "Hello, LUGOD!";
printf("\%s\n", s);\end{alltt}
         \end{sourcecode}
         (\code{\%s} can be used to print strings with printf.)

         Notice a few things:
         \begin{itemize}
            \item Because strings are actually arrays,
               you generally cannot copy strings by
               using the \code{=} operator,
               and you cannot compare two strings
               by using the \code{==} (or any other test-condition)
               operator.
               Instead, you usually have to copy them
               character-by-character
               (and there are bunch of functions you
               can use for that---we'll look at those later.)

               There is one exception, however---at the very beginning,
               when you create the variable,
               like we did above.

            \item With the above program, the string \code{s}
               cannot be more than 80 characters in length.
               If you do, you'll corrupt the memory,
               and possibly crash the program.
         \end{itemize}


      \subsection{Pointers}
         Pointers are a little difficult to explain so I'd like to
         use an analogy.

         Let's say you and your friend are sitting on the couch,
         watching the television.
         Then your friend asks you where the remote control is.
         You tell your friend where it is by pointing to it.
         Your friend stands up, walks up to the remote control,
         grabs it, then comes back to the couch.
         She/he then changes the channel on the television.

         Now, you could have fetched the remote control for
         your friend but you didn't.
         It's so much easier for you to point than to actually
         fetch it.
         If there were no such thing as ``pointing,''
         you could probably live without it,
         but you wouldn't want to because it makes your life
         so much easier.

         The same applies to C.
         The pointer in C exists to point to other variables.
         And then it allows you to access other variables
         through a single pointer.

         Pointers are not necessary to write programs,
         but they makes your life easier from time to time\ldots.

         Anyway, the pointer uses two operators---the
         \term{pointer to} operator~(\code{*}),
         and the
         \term{address of} operator~(\code{\&}).
         Here is an example program:
         \begin{sourcecode}
            \begin{alltt}
int i;   /* Integer */
int* ip; /* Integer pointer */

i = 5;   /* Assign value to i */
ip = &i; /* Point to i */

printf("ip points to \%i\n", *ip);\end{alltt}
         \end{sourcecode}
         First, you create an integer pointer~\code{ip}
         (\code{int*} is equivalent to `pointer-to-int.')
         It can point to any integer variable.

         Then~\code{ip} needs something to point to,
         like the memory address of a integer variable.

         So you find out the address of the~\code{i}
         variable using the address-of operator~(\code{\&})
         and assign that address to~\code{ip}.
         Now~\code{ip} contains the memory address of~\code{i}.

         Now, to access the variable~\code{i} via~\code{ip},
         like printing the integer~\code{ip} points to,
         you need to find out the value of the integer it points to.
         So you use the \emph{pointer-to} operator (use it like~\code{*ip})
         to find out what \code{ip} points to,
         then you can print that, assign new values to it, read it,
         do whatever.

         You can also have pointer to functions.
         We won't go into that topic since it's
         an advanced topic.

      \subsection{Mixing pointers and arrays}

         You can also mix pointers with arrays.
         You can do this by pointing to the beginning of the array,
         then accessing the array via the pointer.

         With this technique, you can access any portion of the array.

         To make a pointer point to the beginning of the array,
         you do something like:
         \begin{sourcecode}
            \begin{alltt}
int iarray[10];  /* Array */
int* ip;         /* Pointer */

ip = iarray;     /* Point to the array */\end{alltt}
         \end{sourcecode}
         Then to access different parts of the array,
         type:
         \begin{sourcecode}
            \begin{alltt}
*ip = 0;     /* same as iarray[0] = 0 */
*(ip+1) = 1; /* same as iarray[1] = 1 */
*(ip+2) = 2; /* same as iarray[2] = 2 */
 \vdots\end{alltt}
         \end{sourcecode}


   \section{Operators}

      C has several types of operators.
      There are the ones used to do math operations
      (\code{+}, \code{-}, \code{*}, \code{/}, \code{\%},)
      then there are the ones used to do test conditions
      (\code{==}, \code{!=}, \code{<}, \code{<=}, \code{>}, \code{>=},)
      both of which we've already looked at during our last talk.

      Then there are what's known as the \term{logical operators},
      that are used for compound test conditions
      (we've looked at a couple of them already---\code{\&\&} and \code{||});
      and there is also what's known as the \term{bitwise operators},
      that are used to manipulate the memory bit-by-bit.

      We'll look at these two different operators.
      We will also look at some shortcut operators.


      \subsection{Logical operators}

         Logical operators are used in compound test conditions.
         We've already looked at \code{\&\&} and \code{||} operators.
         We'll now look at how logical operation is done in C,
         then look at the \code{!} operator

         \subsubsection{How logical operations work}

            When we perform test conditions like ``\code{flag == 1},''
            we produce a result value.
            The resulting value is an integer---1~if the test
            condition is true (if \code{flag} is indeed~1,)
            or 0~if the test condition is false (if \code{flag} is not~1.)

            So you can do things like this:
            \begin{sourcecode}
               \begin{alltt}
int result;
result = (0 == 2);   /* result = 0 */
result = (1 == 2);   /* result = 0 */
result = (2 == 2);   /* result = 1 */
result = (3 == 2);   /* result = 0 */
 \vdots\end{alltt}
            \end{sourcecode}
            So if you really wanted to, you can do things like:
            \begin{sourcecode}
               \begin{alltt}
int flag = (2 == 2);
if(flag) \{
   printf("This always gets printed.\n");
\}
if(1) \{
   printf("Me too!\n");
\}
if(0) \{
   printf("But not me :(\n");
\}\end{alltt}
            \end{sourcecode}
            In addition, C treats any number that \emph{isn't}~0
            to be true.  So you can use any number in place of~1:
            \begin{sourcecode}
               \begin{alltt}
int flag = -3;
if(flag) \{
   printf("This always gets printed.\n");
\}
if(10) \{
   printf("Me too!\n");
\}
if(0) \{
   printf("But not me :(\n");
\}\end{alltt}
            \end{sourcecode}
            But notice you can't do things like:
            \begin{sourcecode}
               \begin{alltt}
int test1 = (2 == 2);
int test2 = 3;
if(test1 == test2) \{
   printf("This doesn't get printed.\n");
\}\end{alltt}
            \end{sourcecode}
            Although you'll probably never write any
            code like that,
            it's been known to happen in a complex program.

            So if you ever want to compare two test conditions,
            you have to use something other than
            test conditions to test the test conditions.
            You use logical operators.

         \subsubsection{The AND and OR operators}
            The logical operators are called that because
            it fits our logical concepts.
            Let's use an analogy that uses logical concepts
            to illustrate.

            Say I own one dog but no cat.
            If a guy named Linus says
            ``Mark owns one dog \emph{and} one cat''
            he would be telling a \emph{lie}
            because only the first part of the statement is true
            (I own one dog)
            but not the first part \emph{and} the second part
            (I don't own one cat.)
            But if he says ``Mark owns one dog \emph{and} zero cats''
            then he would be telling the \emph{truth}
            because both the first part of the statement
            (I own a dog) \emph{and}
            the second part (I own zero cats) are true.
            He can also say ``Mark owns zero dogs and one cat''
            and ``Mark owns zero dogs and zero cats''
            and the result would be both false
            because for ``and,'' both the first part and the
            second part of the statement must be true.

            You can also ask the same questions
            for ``or'':
            If Linus says ``Mark owns one dog \emph{or} one cat,''
            he'd be telling the \emph{truth}
            because for ``or,'' only one of the statements
            need to be true (that I own a dog.)
            You can ask three more questions and you'd
            end up with two true's and one false.

            You can make a table out of this.
            It's called the \term{truth table}
            and it looks like table~\ref{table:analandor}
            \begin{table}
               \begin{center}
               \begin{tabular}{|c|c|c|}
                  \hline
                     & \bf Mark has no dog\ldots & \bf Mark has one dog\ldots\\
                     & \bf (false statement)     & \bf (true statement)\\
                  \hline
                  \bf \ldots and one cat  & false & false\\
                  \bf (false statement)   &       &      \\
                  \hline
                  \bf \ldots and no cat   & false & true\\
                  \bf  (true statement)   &       &     \\
                  \hline
               \end{tabular}\\
               \vspace{2mm}
               \begin{tabular}{|c|c|c|}
                  \hline
                     & \bf Mark has no dog\ldots & \bf Mark has one dog\ldots\\
                     & \bf (false statement)     & \bf (true statement)\\
                  \hline
                  \bf \ldots or one cat  & false & true\\
                  \bf (false statement)  &       &      \\
                  \hline
                  \bf \ldots or no cat   & true  & true\\
                  \bf  (true statement)  &       &     \\
                  \hline
               \end{tabular}
               \end{center}
               \caption{AND and OR truth tables for the dog/cat analogy.}
               \label{table:analandor}
            \end{table}

            Using 1's~and~0's (as truths are represented in C,)
            you get the table that looks like
            table~\ref{table:andor}
            \begin{table}
               \begin{center}
               \begin{tabular}{|c|cc|}
                  \hline
                  \code{\&\&} & \bf 0 & \bf 1\\
                  \hline
                  \bf       0 &     0 &     0\\
                  \bf       1 &     0 &     1\\
                  \hline
               \end{tabular}
               \begin{tabular}{|c|cc|}
                  \hline
                  \code{||} & \bf 0 & \bf 1\\
                  \hline
                  \bf     0 &     0 &     1\\
                  \bf     1 &     1 &     1\\
                  \hline
               \end{tabular}
               \end{center}
               \caption{AND and OR truth tables for C}
               \label{table:andor}
            \end{table}
            Note that AND operator results in true
            if and only if both statements
            are true;
            and the OR operator results in true
            if either statements are true.

            So you can use the table to look-up what the result
            of a \code{\&\&} or \code{||} operation is.

         \subsubsection{The NOT operator}

            You can also negate the results of a logical operation.
            For example, ``not true'' is false, and ``not false'' is true.

            The operator that presents the concept of ``not'' logic
            is the \code{!} operator.
            Here's an example:
            \begin{sourcecode}
               \begin{alltt}
int flag = 0;  /* flag is false */
if(!flag) \{
   printf("This always gets printed!\n");
\}\end{alltt}
            \end{sourcecode}


      \subsection{The bitwise operators}

         Bitwise operators are similar to logical operators---it has
         the AND operator (\code{\&},)
         the OR operator (\code{|},)
         the NOT operator (\code{\~},)
         and a few more operators that have no logical operator
         equivalents.

         The difference is that the truth-table operations are done
         bit-by-bit.

         Say you have an integer 12 (1100 in binary\footnote{
            If you don't know what a binary number is,
            you probably won't use bitwise operators.
            But you can easily convert to/from binary
            numbers using your scientific calculator---punch
            in your number in ``normal'' decimal integer,
            then press the ``BIN'' key (3rd-$\times$ on my TI-36X.)
            To convert back, press the ``DEC'' key (3rd-EE on my TI-36X.)
         }) and you AND it with 10 (1010 in binary.)
         The result is 8 (1000 in binary)
         because the 8's digits in 12 and 10 are both 1's
         (remember true \emph{and} true is true for the \emph{and}
         operation---see table~\ref{table:andor});
         the 4's digits in 12 and 10 are 1 and 0, respectively
         (1 \emph{and} 0 is 0;)
         the 2's digits in 12 and 10 are 0 and 1, respectively
         (0 \emph{and} 1 is 0;)
         and the 1's digits in 12 and 10 are 0 and 0, respectively
         (0 \emph{and} 0 is 0.)

         If you summarize this to a math-arithmetic-looking form,
         it looks like this:
         \begin{center}
         \begin{tabular}{cc}
                      & \code{1100}\\
            \code{\&} & \code{1010}\\
            \hline
                      & \code{1000}
         \end{tabular}
         \end{center}
         Similarly, with the OR operator:
         \begin{center}
         \begin{tabular}{cc}
                     & \code{1100}\\
            \code{|} & \code{1010}\\
            \hline
                     & \code{1110}
         \end{tabular}
         \end{center}
         And the one's-complement operator
         (I previously called this the ``bitwise not operator''):
         \begin{center}
         \begin{tabular}{cc}
            \code{\~} & \code{\ldots00001010}\\
            \hline
                     & \code{\ldots11110101}
         \end{tabular}
         \end{center}
         (Be careful since it negates all the preceding zeros.)

         Your scientific calculator should have the bitwise
         AND, OR, and NOT operator keys.

         \subsubsection{Shift operators}

%            In addition to the above operators that have logical-operator
%            equivalents,
%            there are several bitwise operators without logical operator
%            equivalents.
%
%            These are several other bitwise operators:
%            The exclusive OR operator (\code{^}) and the shift operators.
%
%            The exclusive OR, often abbreviated XOR,
%            does the following operation:
%            \begin{center}
%            \begin{tabular}{cc}
%                         & \code{1100}\\
%               \code{\^} & \code{1010}\\
%               \hline
%                         & \code{0110}
%            \end{tabular}
%            \end{center}
%            Note that XOR operation results in true if
%            one of the bits are true, but not both.
%
%            Your calculator should also have the XOR operator key,
%            along with perhaps one or two others
%            (my calculator also has the XNOR operator key,
%            which negates the numbers before XOR-ing.)
%
%            In addition to the XOR operator, there are also
%            bit-shift

             In addition to the above bitwise operators,
             there are also shift operators
             that ``shift'' the bits either to the left or right.
             The result is equivalent to
             multiplying or dividing the number by 2
             with a few exceptions.

             To shift bits to the left, you use the \code{<<}
             operator;
             For example, to shift the number `12' 3 bits to the left,
             you type \code{12 << 3}.  The result is 96,
             equivalent to $12 \times 2^3$.
             \begin{center}
             \begin{tabular}{cr}
                          & \code{1100}\\
                \code{<<} & \code{3}\\
                \hline
                          & \code{1100000}\\
             \end{tabular}
             \end{center}
             If the bits shift too far to the left, you will
             lose any bits that goes over the maximum limit.
             For example, integers are 32-bits on
             Linux systems, so you can only have up to 32-bits
             using integers;
             beyond that, you will lose the bits.

             To shift bits to the right, you use the \code{>>}
             operator.
             If the bits shift too far to the right,
             you'll also lose those bits as well.

             By the way,
             because the left-most bit represents the
             negative-ness of the number,
             you'll get weird numbers if you left-shift
             1's into the left-most bit.
             You'll also get an unpredictable result
             if you right-shift a negative number
             because the way negative numbers shift to the
             right is undefined by the ANSI~C standard.
             The best way to shift numbers, therefore,
             is to use positive numbers only
             by making use of the \code{unsigned} keyword.

      \subsection{Shortcut operators}

         Because programmers are such lazy group of people,
         we have shortcut operators for the most commonly
         done tasks.

         \subsubsection{Increment/decrement operators}
            To increment or decrement a variable by one,
            you use the \code{++} and \code{--} operator, respectively:
            \begin{sourcecode}
               \begin{alltt}
int c = 1;

++c;  /* Now 'c' is 2 */
--c;  /* Now 'c' is back to 1 */
c++;  /* Now 'c' is 2 again */
c--;  /* Now 'c' is 1 again */\end{alltt}
            \end{sourcecode}
            When you place \code{++} \emph{before} the name of a variable
            (this operator is called the \term{pre-increment operator},)
            the value increments;
            and then the whole expression becomes the incremented value.
            When you place \code{++} \emph{after} the name of a variable
            (this operator is called the \term{post-increment operator},)
            the expression becomes that value then increment after.
            Compare the differences:
            \begin{sourcecode}
               \begin{alltt}
int c=1, d=1;
int a, b;

a = ++c;  /* c=2, a=2 */
b = d++;  /* d=2, b=1 */\end{alltt}
            \end{sourcecode}
            The same idea applies to the decrement operator.

         \subsubsection{Self modifying operators}
            In C, a code like
            \begin{sourcecode}
               \begin{alltt}
int c = 1;

c = c + 5;\end{alltt}
            \end{sourcecode}
            can be shortened to
            \begin{sourcecode}
               \begin{alltt}
int c = 1;

c += 5;\end{alltt}
            \end{sourcecode}
            You can also use the same idea for the
            following operators:
            \code{-}, \code{*}, \code{/}, \code{\%},
            \code{<<}, \code{>>}, \code{\&}, \code{|}.
            (You can also use it for the \code{\^} operator,
            which we didn't talk about and won't talk about
            because it's not used very much.)

   \section{More branch statements (alternatives to \code{if})}

      When you want to \term{branch} to different parts
      of the program, you can use the \code{if} statement.

      But there is another statement that allows you to
      branch.
      It's the \newcode{switch} statement.

      It's just like the \code{if} statements except the
      syntax is different.
      \code{switch} can't do everything \code{if} can
      (if you ever get stuck using switch, you'll
      know what I mean,)
      but you can use \code{switch} to make your code look better.

      The syntax is:
      \begin{sourcecode}
         \begin{alltt}
switch(\imply{value-or-test-condition}) \{
 case \imply{case1}:
   \imply{statements}
   break;
 case \imply{case2}:
   \imply{statements}
   break;
 \vdots
 case \imply{caseN}:
   \imply{statements}
   break;
 default: /* default action */
   \imply{statements}
\}\end{alltt}
      \end{sourcecode}
      The \imply{value-or-test-condition} is compared with each
      \imply{caseN}, then the statements are executed if
      they are equivalent.

      You can use \code{switch} to make your program look more organized.
      Also, sometimes the compiler can optimize \code{switch} statements
      better than it can optimize \code{if}.


   \section{More loops (alternatives to \code{while})}

      There are also a few alternatives to the \code{while}
      statement.
      The two are \newcode{do} and \newcode{for} statements.

      \subsection{\code{do}}
         The \code{do} loop does exactly what the \code{while} loop
         does, except it runs the code inside the loop
         once before checking the test condition.

         Its syntax looks like:
         \begin{sourcecode}
            \begin{alltt}
do \{
   \imply{statements}
\} while(\imply{test-condition});\end{alltt}
         \end{sourcecode}
         We won't go into the details since I know of very few
         program that use the \code{do} loop.
         But \emph{I} like it \Smile

      \subsection{\code{for}}
         The \code{for} loop is designed to simplify
         \code{while} loop that looks like this:
         \begin{sourcecode}
            \begin{alltt}
\imply{statement1}
while(\imply{test-condition}) \{
   \imply{statements}

   \imply{statement2}
\}\end{alltt}
         \end{sourcecode}
         into this:
         \begin{sourcecode}
            \begin{alltt}
for(\imply{statement1}; \imply{test-condition}; \imply{statement2}) \{
   \imply{statements}
\}\end{alltt}
         \end{sourcecode}
         It may seem redundant to have the \code{for} loop,
         but it simplifies things.
         Think of it as a shortcut.

         The most common \code{for} loop looks like:
         \begin{sourcecode}
            \begin{alltt}
for(i = 0; i < \imply{some-number}; i++) \{
   \imply{statements}
\}\end{alltt}
         \end{sourcecode}
         which makes things look nice because all the terms
         involving \code{i} is on the first line of the loop.


   \section{Grouping variables---\code{struct}s}

      Sometimes it's good to group several variables together
      to give an appearance of ``togetherness.''
      Like if you want to make a database of LUGOD members,
      you'd want to group all information for a single person
      together.

      The keyword used for this purpose is \code{struct}.
      First, you tell C what the grouping looks like
      (you place this code before \code{main}):
      \begin{sourcecode}
         \begin{alltt}
struct \imply{Group-name} \{
   \imply{variable-type1} \imply{variable-name1}
   \imply{variable-type2} \imply{variable-name2}
   \vdots
   \imply{variable-typeN} \imply{variable-nameN}
\};\end{alltt}
      \end{sourcecode}
      and then you can create new variables based on this structure
      like this:
      \begin{sourcecode}
         \begin{alltt}
struct \imply{Group-name} \imply{variable-name};\end{alltt}
      \end{sourcecode}
      Member variables are accessed via the \term{member-of}
      operator, the period (\code{.}).
      If you have a pointer to the structure,
      you can use the operator \code{->}

      Please refer to \filename{struct.c} for an example.

   \section{Reading options and arguments}

      You sometimes give arguments to a program.
      Like the \kbd{-a} option you give the
      \code{ls} program.

      Your C program can read these options and arguments.
      To do that, you modify \code{main}
      to look like this:
      \begin{sourcecode}
         \begin{alltt}
int main(int argc, char* argv[]) \{
   \ldots
\}
         \end{alltt}
      \end{sourcecode}
      When your program runs, \code{argc}
      contains the number of arguments on the command line;
      and \code{argv}, a string array, contains the argument.

      For example, if you run your program like this:
      \begin{coutput}
./myprog -la
      \end{coutput}
      then \code{argc} is~2,
      \code{argv[0]} is "./myprog",
      and \code{argv[1]} is "-la".
      In addition, \code{argv[2]} becomes \newcode{NULL}
      (\code{argv[2] == NULL} is true.)\footnote{
         \code{NULL} is a predefined pointer
         you can use to indicate that a pointer
         points nowhere.
         Usually, it points to memory location \code{0}
         so you can do an operation like
         \code{if(pointer)} to determine whether
         a pointer points anywhere valid
         (somewhere other than 0.)
      }

      On GNU~C, there is a command \code{getopt}
      that parses the command line for you so you don't
      have to worry about parsing it yourself.
      Please read the man page for further information.

   \section{Interfacing with shell scripts}
      The \code{main} function also \code{return} an
      integer value to the operating system
      (i.e.\ \code{return 0;}).
      The same is true when you use the \code{exit}
      function to exit the program
      (i.e.\ \code{exit(1);}).

      You can read this value,
      called exit code,
      from shell scripts
      to do different things.
      Please refer to Peter's shell script talk notes for
      further information.

      A note of caution:
      Most shell scripts assume 0~to be a normal exit code,
      and other values to be some kind of error.
      Programs like \filename{make} stops processing
      when one of the programs it runs returns a non-zero code.
      So be careful when you exit with non-standard exit codes.

   \section{Using headers and libraries}

      There are various headers and libraries
      you can use with C.
      There are several standards:
      \begin{itemize}
         \item ANSI/ISO C standard
         \item POSIX standard

            The standard used to program for
            UNIX-like operating systems.

         \item GNU extensions

            GNU includes several extensions to make
            open-source and cross-platform programming
            easier.
            The \code{getopt} function, for example.

         \item BSD UNIX extensions
         \item OpenGroup UNIX extensions
         \item platform-based standard

            Platforms like DOS includes \filename{dos.h}
            header file that contains all DOS-based extensions.
            X~Window includes \filename{xlib.h} for
            X~Window programming.
      \end{itemize}
      Due to time constrains, we'll only briefly discuss
      some of the ANSI/ISO C standard functions.\footnote{
         Most of the information here was carefully extracted
         from \book{The C Programming Language}
         by Brian~W.\ Kernighan and Dennis~M.\ Ritchie,
         second edition, published by Prentice Hall.
         ISBN~0-13-110362-8.
         It is consider to be the bible of the C language
         and I highly recommend it.
         You can purchase a copy at the UC~Davis bookstore.}

      There are only several commonly-used functions listed here,
      with just the names and brief descriptions.
      Please refer to the man page, section 2 or 3
      (depends on the usage; check both), for the details.

      \subsection{Functions for I/O}

         The I/O functions can be used to print to the screen,
         read from the keyboard,
         or print/read to/from a file.

         Here are some functions you can use to read from /
         write to the console:
         \begin{center}
         \begin{tabular}{|c|p{4in}|}
            \hline
            \multicolumn{2}{|c|}{\bf Console I/O (\filename{stdio.h})}\\
            \hline
            \code{printf} & Used to print to the screen\\
            \code{scanf}  & Used to read from the keyboard\\
            \hline
         \end{tabular}
         \end{center}
         To read from / write to a file,
         you must first open the file,
         then close the file after you're done
         using it.

         While you're accessing the file, you don't
         access the file via its filename.
         But rather, you access the file via a
         pointer to a \code{struct} named {FILE},
         that contains various necessary information
         about the file.
         (The pointer to \code{FILE}, \code{FILE*} is called
         the \term{file handle} because you use the handle
         to ``hold onto'' the file while it's open.)

         Here are the commonly used functions used for file I/O:
         \begin{center}
         \begin{tabular}{|c|p{4in}|}
            \hline
            \multicolumn{2}{|c|}{\bf File I/O (\filename{stdio.h})}\\
            \hline
            \code{fopen} & Used to open a file for reading/writing\\
            \code{fclose} & Used to close a file after done reading/writing\\
            \code{fprintf} & Used to print to a file\\
            \code{fscanf} & Used to read from a file\\
            \code{feof}   & Used to check whether you've reached the end of file\\
            \hline
         \end{tabular}
         \end{center}
         Because UNIX treats everything as files
         (including the screen and the keyboard,)
         you can use the file I/O functions also as
         screen/keyboard I/O functions.
         To use file I/O functions with the screen/keyboard,
         use the file handle \code{stdin}
         when you want to read from the keyboard,
         and use the file handle \code{stdout}
         when you want to write to the screen.
         You can also use the file handle \code{stderr}
         if you wish to write to the standard output
         (also the screen by default.)
         Please refer to notes on the shell talk for details
         on how one can use standard error.
         You need not close these handles because C
         does it automatically.

      \subsection{String functions}

         In C, all string access must be done character-by-character.
         C~makes that chore a little easier by providing several
         built-in functions:
         \begin{center}
         \begin{tabular}{|c|p{4in}|}
            \hline
            \multicolumn{2}{|c|}{\bf String operations (\filename{string.h})}\\
            \hline
            \code{strcpy} & Used to copy strings\\
            \code{strcat} & Used to append one string to another\\
            \hline
            \code{strncpy} & Used to copy strings up to N characters\\
            \code{strncat} & Used to append strings up to N characters\\
            \hline
            \code{strlen} & Returns the length of the string\\
            \code{strcmp} & Compares two strings\\
            \hline
            \code{strchr} & Finds a character in a string\\
            \code{strstr} & Finds a string within a string\\
            \hline
         \end{tabular}
         \end{center}

      \subsection{Math functions}

         C also provides several basic math functions.
         In addition to including \filename{math.h},
         you also must use the \kbd{-lm} option
         when you compile your program.

         All trigonometric functions use the radian coordinate system.
         \begin{center}
         \begin{tabular}{|c|p{4in}|}
            \hline
            \multicolumn{2}{|c|}{\bf Math functions (\filename{math.h})}\\
            \hline
            \code{sin}  & Used to find the sine of an angle\\
            \code{cos}  & Used to find the cosine of an angle\\
            \code{tan}  & Used to find the tangent of an angle\\
            \hline
            \code{asin} & Used to find the inverse sine of a real number\\
            \code{acos} & Used to find the inverse cosine of a real number\\
            \code{atan} & Used to find the inverse tangent of a real number\\
            \code{atan2} & Used to find the inverse tangent of a real number,
               compensating for the 2nd and 3rd quadrants\\
            \hline
            \code{pow}  & Used to find the power of some number\\
            \hline
            \code{exp}  & Used to find $e^n$\\
            \code{log}  & Used to find the natural log ($\ln$)\\
            \code{log10} & Used to find $\log_{10}$\\
            \hline
            \code{abs} & Takes the absolute value of an integer\\
                       & (This function is in \filename{stdlib.h})\\
            \code{labs} & Takes the absolute value of a long integer\\
                       & (This function is in \filename{stdlib.h})\\
            \code{fabs} & Takes the absolute value of a real number\\
            \hline
            \code{ceil} & Rounds up a real number\\
            \code{floor} & Rounds down a real number\\
            \hline
         \end{tabular}
         \end{center}
         You can round numbers by adding $.5$ to the real number,
         then taking its \code{floor}.

      \subsection{Dynamic memory allocation functions}

         In C, the size of all arrays must be know before you
         compile the program.
         If you do not know the size of the array before
         you compile it, you must dynamically create
         memory at runtime,
         then use a pointer to read from and write to the memory.

         Here are functions that allows you to do that:
         \begin{center}
         \begin{tabular}{|c|p{4in}|}
            \hline
            \multicolumn{2}{|c|}{\bf Dynamic memory functions (\filename{stdlib.h})}\\
            \hline
            \code{malloc} & Create new memory of size \imply{N}
               and returns its address\\
            \code{realloc} & Resizes an existing memory, either by
               extending the memory (if possible)
               or by creating new memory as necessary\\
            \code{free}   & Destroys the memory so you can use it
               for something better\\
            \hline
         \end{tabular}
         \end{center}
         \code{malloc} and \code{realloc} will return \code{NULL}
            if you run out of memory,
            so you should check to make sure these functions
            return \code{NULL} or not.
            Otherwise you could either corrupt memory or crash
            your program.

      \subsection{Conversion functions}
         You can convert between strings to numbers,
         numbers to strings,
         a number to a character,
         a character to a number, etc.
         Here are the functions to let you do that:
         \begin{center}
         \begin{tabular}{|c|p{4in}|}
            \hline
            \multicolumn{2}{|c|}{\bf Conversion functions (\filename{stdlib.h})}\\
            \hline
            \code{atoi} & Convert from string to integer\\
            \code{atof} & Convert from string to real number\\
            \code{atol} & Convert from string to long\\
            \hline
            \code{sprintf} & Convert from integers or real numbers to string\\
                           & (This function is in \filename{stdio.h})\\
            \hline
         \end{tabular}
         \end{center}

      \subsection{Randomization functions}
         You can produce a series of random-ish numbers
         in C.
         Here are the functions to do that:
         \begin{center}
         \begin{tabular}{|c|p{4in}|}
            \hline
            \multicolumn{2}{|c|}{\bf Randomizing functions (\filename{stdlib.h})}\\
            \hline
            \code{srand} & You must give the randomization function a
%               \term{seed} with this function.
               ``seed'' with this function.
               Otherwise you'll get the same series of number every time
               you use the \code{rand} function
               (this is useful if you're running a simulation and want
               to be able to reproduce the simulation.)
               Most people use the computer's internal clock to randomize
               the the seed.\\
            \code{rand} & This function returns a random-ish integer,
               between 0 and \code{RAND\_MAX}.\\
            \hline
         \end{tabular}
         \end{center}

      \subsection{Date and time functions}
         Keeping track of the time is useful when you want
         to slow down your program so it does not run too fast,
         or if you wish to keep track of how often your
         program runs.

         Here are some functions to help you do this:
         \begin{center}
         \begin{tabular}{|c|p{4in}|}
            \hline
            \multicolumn{2}{|c|}{\bf Date/time functions (\filename{time.h})}\\
            \hline
            \code{time} & Returns a \code{struct} containing current date/time;
               for details on the structure \code{struct},
               please read the section~2 manpage\\
            \code{difftime} & Returns the difference of two times\\
            \hline
            \code{asctime} & Prints the date/time\\
            \hline
         \end{tabular}
         \end{center}

      \subsection{Miscellaneous functions}
         Here are some miscellaneous functions:
         \begin{center}
         \begin{tabular}{|c|p{4in}|}
            \hline
            \multicolumn{2}{|c|}{\bf Miscellaneous functions (\filename{stdlib.h})}\\
            \hline
            \code{system} & Executes an external program\\
            \hline
            \code{qsort} & Built-in sorting function\\
            \code{bsearch} & Built-in search-tree function\\
            \hline
         \end{tabular}
         \end{center}


\appendix
   \section{Using \code{printf}-family functions}

      When you use \code{printf}, \code{fprintf}, and/or
      \code{sprintf}, you can use
      \code{\%i} to print integers,
      \code{\%f} to print floats,
      etc.
      You can also type \code{\n} to print
      the newline character.
      We'll explore what other symbols you can use
      to print other variables and symbols.

      Here are the symbols used to print variables:
      \begin{center}
      \begin{tabular}{|c|p{4in}|}
         \hline
         \multicolumn{2}{|c|}{\bf Symbols to print variables for \code{printf} family functions}\\
         \hline
         \code{\%c} & Character\\
         \code{\%s} & String\\
         \code{\%d} & Integer (more common)\\
         \code{\%i} & Integer (less common)\\
         \code{\%f} & Real\\
         \hline
         \code{\%o} & Octal integer\\
         \code{\%x} & Hexadecimal integer\\
         \hline
      \end{tabular}
      \end{center}
      You can also use the above symbols with \code{scanf}-family
      functions to read values into variables.
      Because \code{scanf} functions need to write variables,
      it needs to know the address of the variables it writes to;
      therefore you must use the address-of operator
      when you use \code{scanf}, like this:
      \begin{sourcecode}
         \begin{alltt}
int i;
scanf("\%d", &i);\end{alltt}
      \end{sourcecode}
      The only exceptions are the pointers and the arrays---they
      are variables that hold addresses to the memory area
      that \code{scanf} writes to, so \code{scanf} does not need
      to know the address of the pointers or arrays.
      That means strings, which are arrays, don't need the ampersand.

      You can add modifiers to the above symbols to control
      how you want the characters to be printed.

      A common one is placing a number between \code{\%}
      and the letter to force the output to a certain width.
      For example:
      \begin{sourcecode}
         \begin{alltt}
printf("4-digit hex number: \%04x\n");\end{alltt}
      \end{sourcecode}
      The `0' in front of `4' uses 0 as the number padding.

      There are numerous other modifiers that cannot be
      listed all here.
      Please refer to \book{The C Programming Language}
      for details.

      There are also various weird characters you can work with.
      They are not for \code{printf} functions but
      for any string in C in general:
      \begin{center}
      \begin{tabular}{|c|p{4in}|}
         \hline
         \multicolumn{2}{|c|}{\bf Printable symbols}\\
         \hline
         \code{\bs{}n} & Newline character (to next line)\\
         \code{\bs{}r} & Carriage return character
            (to beginning of the same line)\\
         \code{\bs{}t} & Tab character\\
         \code{\bs{}b} & Backspace character
            (back one character w/o erasing character)\\
         \code{\bs{}a} & Alarm (print it to get a beep)\\
         \code{\bs\bs} & Backslash character\\
         \hline
         \code{\%\%}   & Percent character
            (works only with \code{printf}-family of functions,
            and it's only necessary with \code{printf}-family of functions)\\
         \hline
      \end{tabular}
      \end{center}

   \section{Representing numbers}

      You can represent different types of numbers in C.
      There are decimal integers, reals (floats),
      octals, and hexadecimals.

      You already know how to read and write
      decimal integers---0, 1, 2, 3,\ldots.
      And you may already know how to read and write
      floating numbers (if you know the e-notation.)

      These two numbers exist in C because those are the
      numbers we use in everyday life.

      But\ldots computers don't use decimal (base~10)
      numbers.  They use binary (base~2) numbers.

      It would be useful to write numbers in binary,
      though, because it helps us \emph{visualize}
      what computer ``sees,''
      the way computer stores the numbers in its memory.

      \emph{But} large binary numbers are
      too long to write.
      So computer scientists created octal
      (base~8) and hexadecimal (base~16)
      numbers,
      that are multiple bases of the binary,
      to make it easier for
      programmers to write numbers
      that represent numbers inside the computer's
      mind (memory.)

      \subsection{Floating numbers}
         In computers, there is something we call the \term{e-notation}.
         This is a technique used to represent
         numbers in the form $a\times{}10^b$.

         Since printing out
         \cout{\imply{a} * 10\char94\imply{b}}
         (\cout{\^} is a common notation used to represent ``power'')
         or \cout{\imply{a} * 10**\imply{b}}
         (\cout{**} is a notation used to represent ``power'' in FORTRAN)
         wastes too much screen space,
         computer scientists made a shorter notation to represent
         $a\times{}10^b$,
         and it looks like this:
         \begin{sourcecode}
            \begin{alltt}
\imply{a}e{b}\end{alltt}
         \end{sourcecode}
         It is very easy to confuse this with $e^b$.
         Don't \Smile

         So to represent $6.02\times10^{23}$ in C,
         type \code{6.02e23}.
         Compact, saves memory, everyone's happy.

      \subsection{Octal numbers}
         Base~8 numbers (called \term{octal} numbers because
         the prefix ``oct'' means ``eight,''
         just like the prefix ``dec'' in ``decimal'' means ``ten.'')
         use only 8 of the 10 numbers in our decimal system.
         These numbers are 0, 1, 2, 3, 4, 5, 6, and 7.

         Octal numbers are not used very often in C,
         but it \emph{is} often used with the UNIX program
         \filename{chmod}.
         So it is good to know octal numbers.
         Please read the \filename{chmod} manual for the details
         on the usage of \filename{chmod}.

         Due to time constrains, we will not go into the details
         of converting between decimal (standard) numbers to
         octal numbers,
         but you can use a scientific calculator to convert
         between decimal and octal numbers.\footnote{
            Note: Not all scientific calculators have
               base conversion keys.
         }
         To convert from a decimal number to a octal number,
         type the number you wish to convert to the octal number,
         then press the \calckey{OCT} button
         (it's \calckey{3rd}-\calckey{)} on my TI-36X calculator).
         To convert from a decimal number to a octal number,
         put the calculator in octal mode by pressing
         the \calckey{OCT} button,
         typing the octal number you wish to convert to decimal,
         then pressing the \calckey{DEC} button
         (it's \calckey{3rd}-\calckey{EE} on my TI-36X.)

         \begin{table}
            \begin{center}
            \begin{tabular}{|c|c|}
               \hline
               \bf Octal & \bf Binary\\
               \hline
               0 & 000\\
               1 & 001\\
               2 & 010\\
               3 & 011\\
               4 & 100\\
               5 & 101\\
               6 & 110\\
               7 & 111\\
               \hline
            \end{tabular}
            \end{center}
            \caption{Octal-to-binary conversion table}
            \label{table:octal}
         \end{table}
         Since we use the octal numbers to make it easier
         to visualize binary numbers,
         it helps to have a octal-to-binary conversion table,
         like table~\ref{table:octal}.

         To represent octal numbers in C,
         you must precede the number by \code{0}.
         So, to write \code{21} in octal (equivalent to 17 in decimal,)
         type \code{021} in C.

      \subsection{Hexadecimal numbers}

         Hexadecimal numbers are base~16 numbers
         that utilizes all 10 numbers in the decimal system,
         plus 6 more from the alphabet to make up the 6 numbers
         (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F---16 ``numbers!'')

         To represent hexadecimal numbers in C,
         you precede the number by \code{0x}.
         Some examples of hexadecimal numbers are
         \code{0x10} (16 in decimal,)
         \code{0x2A} (42 in decimal,)
         \code{0xFACE} (64206 in decimal,)
         and \code{0xDEAD} (57005 in decimal.)

         You can also use your calculator to convert between
         decimal and hexadecimal numbers.
         Your scientific calculator should have a button
         labeled \calckey{HEX} (\calckey{3rd}-\calckey{(}
         on my calculator.)
         To type hexadecimal numbers, you can use the keys
         labeled \calckey{A}-\calckey{F}
         (\calckey{3rd} and one of
         \calckey{1/x}, \calckey{$x^2$}, \calckey{$\sqrt{x}$},
         \calckey{SIN}, \calckey{COS}, \calckey{TAN} keys on my calculator.)

         \begin{table}
            \begin{center}
            \begin{tabular}{|c|c|c|}
               \hline
               \bf Hexadecimal & \bf Binary & \bf Decimal\\
               \hline
               0 & 0000 & 0\\
               1 & 0001 & 1\\
               2 & 0010 & 2\\
               3 & 0011 & 3\\
               4 & 0100 & 4\\
               5 & 0101 & 5\\
               6 & 0110 & 6\\
               7 & 0111 & 7\\
               8 & 1000 & 8\\
               9 & 1001 & 9\\
               A & 1010 & 10\\
               B & 1011 & 11\\
               C & 1100 & 12\\
               D & 1101 & 13\\
               E & 1110 & 14\\
               F & 1111 & 15\\
               \hline
            \end{tabular}
            \end{center}
            \caption{Hexadecimal-to-binary conversion table}
            \label{table:hex}
         \end{table}
         A hexadecimal-to-binary table is given in table~\ref{table:hex}.

\end{document}

