\documentclass[10pt,hyperref={implicit=true}]{beamer} \errorcontextlines=10 \mode { %\usetheme{Warsaw} \usetheme[hideothersubsections]{Goettingen} % or ... \setbeamercovered{transparent} % or whatever (possibly just delete it) \subject{C Programming for Engineers} \setbeamertemplate{footline}% {% \par\vspace*{-\baselineskip}\par% \raisebox{0.5ex}{\usebeamercolor[fg]{structure}% \ slide \insertframenumber/\inserttotalframenumber}% }% } \mode
{ \renewcommand{\floatpagefraction}{0.75} % default is .5, to increase % density. \renewcommand*{\bottomfraction}{0.6} % default is 0.3 \renewcommand*{\topfraction}{0.85} % default is 0.7 \renewcommand*{\textfraction}{0.1} % default is 0.2 \pagestyle{fancy} \fancyhf{} \newlength{\markWidth} \setlength{\markWidth}{0.5\textwidth} \newlength{\topicnumwidth} \settowidth{\topicnumwidth}{1.114.3} \addtolength{\markWidth}{-0.6\topicnumwidth} %\addtolength{\headheight}{1.92ex} \renewcommand{\sectionmark}[1]{\markright{\thesection. #1}} \lhead{\parbox[t]{\markWidth}{\raggedright\nouppercase{\rightmark}}} \rhead{\thepage} \AtBeginDocument{\thispagestyle{empty}} } \usepackage[english]{babel} \usepackage{alltt,booktabs,array,cols,multicol,meta,key,xcolour-names} \usepackage[utf8]{inputenc} % or whatever \usepackage{lgrindsetup} \usepackage{times} \usepackage[T1]{fontenc} % Or whatever. Note that the encoding and the font should match. If T1 % does not look nice, try deleting the line with the fontenc. \usepackage{varioref} \title{C Programming for Engineers} \subtitle{A Review of C. Introducing iostream} \author[Nick Urbanik]{Nick Urbanik \texttt{\footnotesize{}nicku\at{}nicku.org}\\ {\tiny This document Licensed under GPL---see slide~\pageref{sld:license}}% } \date{2006 February} % Copyright (C) 2005 Nick Urbanik % You can redistribute modified or unmodified copies of this document % provided that this copyright notice and this permission notice are % preserved on all copies under the terms of the GNU General Public % License as published by the Free Software Foundation--either version 2 % of the License or (at your option) any later version. \AtBeginSubsection[] { \begin{frame} \tiny \frametitle{Outline} %\scriptsize \begin{multicols}{3} \tableofcontents[currentsection,currentsubsection] \end{multicols} \end{frame} } % If you wish to uncover everything in a step-wise fashion, uncomment % the following command: %\beamerdefaultoverlayspecification{<+->} \newcounter{program} %\newcommand*{\program}[1]{\refstepcounter{program}\label{#1}\arabic{program}} % \newcommand*{\program}[1]{% % \refstepcounter{program}\hypertarget{#1}{Program \texttt{#1}}% % } %\newcommand*{\program}[1]{\refstepcounter{program}\label{#1}\arabic{program}} \newcommand*{\program}[1]{% \hypertarget{#1}{Program \texttt{#1}}% } \newcommand*{\linkto}[1]{\hyperlink{#1}{\texttt{#1}}} \providecommand*{\bs}{\texttt{\char '134}} % Backslash, no break \begin{document} \maketitle \thispagestyle{empty} % \begin{frame} % \titlepage % \end{frame} \begin{frame} \frametitle{Outline} \mode {% \tiny% %\footnotesize \begin{multicols}{2}% \tableofcontents \end{multicols} % You might wish to add the option [pausesections] }% \mode
{% \tableofcontents }% \end{frame} \section{Who am I? Who are You?} \label{sec:who-am-i-who-are-you} \begin{frame}[<+->] \frametitle{Welcome!} \begin{itemize} \item Welcome to our class in Electrical Control, C Programming \item My name is Nick Urbanik \begin{itemize} \item Call me Nick \end{itemize} \item My email address is \texttt{nicku\at{}nicku.org} \mode
{% \item {The notes for this class are always available at \hfill\mbox{}\linebreak\url{http://nicku.org/c-for-engineers/}}} \mode{% \item The notes for this class are always available at \url{http://nicku.org/c-for-engineers/}} \item I taught in Hong Kong for ten years \item I taught in Macau one year before that \item Before that I wrote software in C++ to collect data for medical experiments \end{itemize} \end{frame} % \begin{frame} % \frametitle{Please tell me about yourselves} % \begin{itemize} % \item I am passing a sheet of paper to you all % \item Please write down your: % \begin{itemize} % \item Name % \item email address % \item phone number % \end{itemize} % \item Do you have a current job? % \begin{itemize} % \item If so, is it in a field relating to computing or electrical % engineering? % \end{itemize} % \end{itemize} % \end{frame} % \begin{frame}[<+->] % \frametitle{Can You Write a C Program to\,\ldots} % \begin{itemize} % \item print your name? % \item print the sum of ten numbers? % \item read a number from the keyboard (standard input) and print its % value multiplied by 10? % \item read data from a file? % \item write data to a file? % \item using pointers? % \item using structures? % \item print the contents of an array? % \end{itemize} % \end{frame} \begin{frame} \frametitle{How we will work in these classes} \begin{itemize} \item We will learn by doing \begin{itemize} \item I will explain something for a short time \item you will then try it out for a short time \end{itemize} \item Next week: \begin{itemize} \item I will print the notes out for you, now that I know what you need \item I will give you more information about this course \end{itemize} \item This is always available from \url{http://nicku.org/}; click on the link on the left ``C for Engineers''. \item I will publish all the teaching material also on \url{http://gonzo.org.au/}, and I'll explain to you how to use it \end{itemize} \end{frame} \section{Overview} \subsection{Quick Tour} \label{sec:quick-tour} \begin{frame} \frametitle{C --- Quick tour} \begin{itemize} \item C was originally designed as a low-level systems programming language for an early version of the UNIX operating system. \item Combine: \begin{itemize} \item efficiency and hardware access capability of assembler with \item high level language structures and \item portability \end{itemize} \item Most of the Linux and UNIX operating systems are written in C. \end{itemize} \end{frame} \begin{frame} \frametitle{C is \textbf{portable}} \begin{itemize} \item Although C matches the capabilities of many computers, it is independent of any particular machine architecture. \item it is not difficult to write portable programs that can be run without change on a variety of hardware \item the standard makes portability issues explicit, and prescribes a set of constants that characterize the machine on which the program is run. \begin{itemize} \item See \href{run:gedit /usr/include/limits.h}{\texttt{limits.h}} \end{itemize} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{C --- quick tour (continued)} \begin{itemize} \item The standard library is a suite of ready-written commonly used functions \item header files declare the library functions, and any symbolic constants required. \item The (obsolete) header file for the \texttt{iostream} library is \alert{included} into your program file with: %[ #include %] \item Header files tell the compiler about the library functions and about the type of the parameters and return types \item linker automatically links in the required functions at compile-time. \item C programs make use of functions from the standard library; e.g., all input and output operations are usually performed using standard library functions. \end{itemize} \end{frame} \subsection{Standard Input, Standard Output} \label{sec:standard-input-standard-output} \begin{frame} \frametitle{Standard Input, Output} \begin{itemize} \item If you run a program in Windows or Linux, it usually has three files already open: \par\noindent% %@- \begin{tabular}[t]{@{}lcl@{}} %@+ \toprule% \emph{Name} & \emph{File Descriptor} & \emph{normally connected to}\\ \midrule% Standard Input & 0 & keyboard \\ Standard output & 1 & screen \\ Standard error & 2 & screen \\ \bottomrule \end{tabular} \par\smallskip\par \item These are normally connected to the keyboard and your command prompt window \end{itemize} \includegraphics[width=0.6\linewidth]{cli2} \end{frame} \subsection{Redirecting Output and Input} \label{sec:redirecting-output-and-input} \begin{frame}[fragile] \frametitle{Output Redirection} \begin{itemize} \item We redirect output using '{\verb|>|}' \item For example: \begin{semiverbatim} C:\bs{}STUDENT> \textbf{command > output} \end{semiverbatim} Creates the file \texttt{output} (or overwrites it if it already exists) and places the standard output from \texttt{command} into it \item We can append to a file rather than overwriting it by using \verb|>>| \includegraphics[width=0.6\linewidth]{basic_shell_use_output_redirection} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Input Redirection} \label{sld:input-redirection} \begin{itemize} \item \texttt{<} redirects standard input from a file, e.g., \begin{semiverbatim} C:\bs{}STUDENT> \textbf{analyse < numbers.txt} \end{semiverbatim} \item \texttt{analyse} now take the contents of the file \texttt{numbers.txt} as its input \includegraphics[width=0.6\linewidth]{basic_shell_use_input_redirection} \end{itemize} \end{frame} % \begin{frame} % \frametitle{Don't be worried!} % \begin{itemize} % \item This quick tour of C will just briefly show you what you will % learn during this course. % \item You are not expected to understand everything of every example % during this ``quick tour'' % \item We \alert{will} cover all the details later % \item Just have a quick overview now % \end{itemize} % \end{frame} \section{C++ and \texttt{iostream} library} \label{sec:c++-and-iostream-library} \begin{frame} \frametitle{C++} \begin{itemize} \item C++ is forwards compatible with C \item If a C++ compiler cannot compile a C program, the C program may be poorly written \item We will use some basic C++ features in this course, where they make things easier \item One of these ways is file input and output using the \texttt{iostream} standard library. \item Another is the standard \texttt{string} library, but I don't think that Borland C++ 3.1 supports it. \end{itemize} \end{frame} \subsection{An overview of the \texttt{iostream} library} \label{sec:overview-of-the-iostream-library} \begin{frame}[fragile] \frametitle{Overview of \texttt{iostream} library} \begin{itemize} \item To use \texttt{iostream} library in programs, we must include the header file like this: %[ #include %] \item If you are using a very old C++ compiler, put this instead: \begin{semiverbatim} #include \end{semiverbatim} \item The library defines three standard stream objects: \begin{description} \item[\texttt{\textbf{std::cin}}] pronounced \emph{see-in} \begin{itemize} \item an \texttt{istream} class object representing \emph{standard input} \end{itemize} \item[\texttt{\textbf{std::cout}}] pronounced \emph{see-out} \begin{itemize} \item an \texttt{ostream} class object representing \emph{standard output} \end{itemize} \item[\texttt{\textbf{std::cerr}}] pronounced \emph{see-err} \begin{itemize} \item an \texttt{ostream} class object representing \emph{standard error} \end{itemize} \end{description} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Input and Output operators} \begin{itemize} \item Output is done using the left shift operator @<<@ \item Input is done using the right shift operator @>>@ %[ #include int main( void ) { char name[ 1000 ]; std::cout << "what is your name? "; std::cin >> name; if ( name[ 0 ] == '\0' ) std::cerr << "error: name is empty!\n"; else std::cout << "hello, " << name << "!\n"; } %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{How do I remember?} \begin{itemize} \item A way of remembering which operator is which: \item each operator points in the direction the data moves, e.g., %[ >> x %] puts data \emph{into} @x@, while %[ << x %] gets data \emph{out from} @x@ \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Why is this better than \V{printf}\Of{()} and \V{scanf}\Of{()}?} \begin{itemize} \item @std::cin@, @std::cout@ and @std::cerr@ ``know'' the type of data they are working with, so \item there is no need for you to remember which format string is needed for which data type; \item ``it all just works'' \end{itemize} \end{frame} \section{Continuing our tour} \subsection{hello.cpp} \label{sec:hello.cpp} \begin{frame}[fragile] \frametitle{First example} \begin{itemize} \item \program{hello.cpp}: %[ // A first program in C++ #include int main( void ) { std::cout << "Hello World\n"; } %] \item Output for Program \linkto{hello.cpp}: \begin{verbatim} Hello World \end{verbatim} \end{itemize} \end{frame} % \begin{frame} % \frametitle{Example with function} % \begin{itemize} % \end{itemize} % \end{frame} \begin{frame} \frametitle{Good programming practice} \begin{itemize} \item Indentation can improves clarity and readability. It can be enhanced by placing braces or blank lines. \item Use variable and function names that explain themselves \item Functions should be shorter than one A4 page and should be simple to understand \item Every long or complicated function should be preceded by a comment describing the purpose of the function. \item Aim: make the program as easy for a human to understand as possible \item Saves money: less time to change/update program = less money. \end{itemize} \end{frame} \subsection{Basic Syntax} \label{sec:basic-syntax} \begin{frame}[fragile] \frametitle{Format of @main()@ function without parameters} \begin{semiverbatim} \K{int} \V{main}( \K{void} ) \{ \meta{declarations}; \meta{statements}; \} \end{semiverbatim} \end{frame} \begin{frame} \frametitle{Variable declarations} \begin{itemize} \item Variables are declared and defined with a \alert{data type} and a \alert{name}. \item The name is also called an \alert{identifier}. \item First character of a variable must be letter or underscore (\_). Special characters (e.g., \$ and \#) are illegal. \item Some people (including me!) recommend using lowercase letters and underscores only. \end{itemize} \end{frame} \subsection{Input characters without skipping whitespace} \label{sec:input-chars-without-skipping-whitespace} \begin{frame}[fragile] \frametitle{Input characters without skipping whitespace} \mode {% \renewcommand*{\LGsize}{\scriptsize}% } \begin{itemize} \item We can input and output characters one at a time: \item \program{one-char-io.cpp}: %[ #include int main( void ) { char letter; std::cin >> letter; std::cout << letter; } %] \item Note that by default, @std::cin >> letter;@ will skip over whitespace, such as spaces, tabs and newlines \item You can use the \texttt{iostream} \alert{member function} @std::cin.get()@ to input characters one at a time, including whitespace: %[ #include int main( void ) { char letter; std::cin.get( letter ); std::cout << letter; } %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Data Types} \begin{itemize} \item Three of the most commonly used data types: \par\noindent% \begin{tabular}[t]{>{\ttfamily}ll} int & integer \\ double & floating point number \\ char & character \end{tabular} \par% \item \program{vars.cpp}: %[ #include int main( void ) { int num = 5; float cost = 9.5; std::cout << "Hello: num = " << num << " cost = " << cost << '\n'; } %] \end{itemize} \end{frame} \begin{frame} \frametitle{The @std::endl@ manipulator} \begin{itemize} \item The \texttt{iostream} libraries support \alert{manipulators} \item A manipulator changes the state of a stream \item The @std::endl@ manipulator: \begin{itemize} \item prints a newline @'\n'@, and \item sends any remaining characters stored ready for output, to the output \begin{itemize} \item We say that this ``flushes the buffer'' \end{itemize} \end{itemize} \end{itemize} \end{frame} \subsection{{I/O of other data to standard output and from standard input}} \label{sec:i-o-of-other-data-to-standard-output-and-from-standard-input} \begin{frame}[fragile] \frametitle{Input and output with \texttt{iostream}} \begin{itemize} \item Simple input and output operations using \texttt{iostream} library objects @std::cout@ and @std::cin@ \item \program{celcius.cpp}: %[ #include int main( void ) { double fahr = 212, cel; cel = ( 5.0 / 9.0 ) * ( fahr - 32 ); std::cout << fahr << " deg F => " << cel << " deg C\n"; } %] Output of program \linkto{celcius.cpp}: \begin{verbatim} 212 deg F => 100 deg C \end{verbatim} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Using @std::cin@ for input} \begin{itemize} \item @std::cin@ object performs the opposite operation. \item reads text from \alert{standard input} and assigns to variables \item automatically converts the input text data to appropriate types \item \program{cin-cout-2.cpp}: %[ #include int main( void ) { int num; float cost; std::cout << "Enter number: "; std::cin >> num; std::cout << "Enter cost: "; std::cin >> cost; std::cout << "Num = " << num << ", cost = " << cost << '\n'; } %] \end{itemize} \end{frame} % \begin{frame}[fragile] % \frametitle{How @scanf()@ puts values into variables} % \begin{semiverbatim} % scanf( "%d", &num ); % \end{semiverbatim} % \begin{itemize} % \item If the user enters the number 45 as the value for @num@. % The computer will place 45 into location @num@ % \end{itemize} % \begin{semiverbatim} % scanf( "%f", &cost ); % \end{semiverbatim} % \begin{itemize} % \item If user enters the 17, a floating point value (4 bytes) will be % placed into memory location @cost@. % \end{itemize} % \end{frame} \subsection{Reading into strings} \label{sec:reading-into-strings} \begin{frame}[fragile] \frametitle{Strings --- array of characters} \begin{itemize} \item A \alert{string} is an array of characters, i.e., text. \item The length of the string can be defined with a number enclosed in brackets. e.g., array of 10 characters with name @lname@: %[ char lname[ 10 ]; %] \item \program{cin-cout-3.cpp}: %[ #include int main( void ) { int num; char lname[ 1000 ]; std::cout << "Enter class number: "; std::cin >> num; std::cout << "Enter last name: "; std::cin >> lname; std::cout << "class number is " << num << ", lastname is " << lname << '\n'; } %] \end{itemize} \end{frame} \subsection{Loops} \label{sec:loops} \begin{frame}[fragile] \frametitle{Loops} \begin{itemize} \item A loop will cause statements to be executed repeatedly until a test condition proves false \item \program{while-1.cpp}: %[ #include int main( void ) { int j = 0; while ( j < 5 ) { std::cout << "j has the value " << j << '\n'; j = j + 1; } } %] \end{itemize} \end{frame} \subsection{Reading till the end of file} \label{sec:reading-till-eof} \begin{frame} \frametitle{End of file} \begin{itemize} \item When there is no more input, a program has reached the \emph{end of file} \item When reading standard input: \begin{itemize} \item that is redirected from a file (see %\mode{slide %\ref{sld:input-redirection})}\mode
{section %\vref{sec:redirecting-output-and-input}}% section~\vref{sec:redirecting-output-and-input}), the program has reached end of file when, well, the last line is read. \item from the keyboard, you can type \key{Control-Z} on Windows, or \key{Control-d} on Linux to tell your program that it has reached the end of file \end{itemize} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Reading till the end of file} \begin{itemize} \item If you execute the code @std::cin >> name;@ after reaching end of file, the result is \alert{false}. \item That means you can write code like this: %[ if ( std::cin >> name ) { // do something with @name@ } %] \item You can also write a loop that automatically terminates when there is no more to read: %[ float num; while ( std::cin >> num ) { // Now we know that @num@ is a valid @float@, // so do something with it } %] \begin{itemize} \item After this loop is finished, either we have reached end of file, or the next input is not a valid @float@ \end{itemize} \end{itemize} \end{frame} \subsection{Infinite Loop while reading} \begin{frame}[fragile] \frametitle{Infinite Loop while reading} \begin{itemize} \item If you do something like this: %[ float num = 1.0; std::cout << "enter positive floats: "; while ( num > 0 ) { std::cin >> num; std::cout << "You gave me " << num << '\n'; } %] if you enter something that is not a valid @float@, you get an infinite loop. \item Use the method I described in the last slide. \item See \url{http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.2} for more about this. \end{itemize} \end{frame} \section{Data Types} \label{sec:data-types} \begin{frame} \frametitle{Data Types} \begin{itemize} \item Data is represented in memory by a sequence of bits, arranged into bytes, eight bits to a byte \item These bits could represent \begin{itemize} \item strings or characters \item integers \item floating point values \item memory addresses \item binary values representing music or video \item \ldots \end{itemize} \item Each item of data has a \alert{data type} \item The \alert{data type} determines how the program will interpret the data \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Declaration \& data types} \begin{itemize} \item A variable declaration consists of a data type and an identifier, followed by a semicolon: \begin{semiverbatim} \red{\meta{Data Type}} \green{\meta{Variable Name}} \blue{\meta{semicolon}} \end{semiverbatim} \item Example: \begin{semiverbatim} \red{int} \green{count}\blue{;} \end{semiverbatim} \setlength{\extrarowheight}{0pt}% \par\medskip\par% \noindent% \begin{tabular}[t]{l>{\KWfont}l} \toprule \textbf{Basic data types} & \textnormal{\textbf{Keywords}} \\ \midrule character & @char@ \\ signed character & @signed char@ \\ unsigned character & @unsigned char@ \\ integer & @int@ \\ unsigned integer & @int@ \\ long integer & @long@ \\ unsigned long integer & @unsigned long@ \\ long long integer & @long long@ \\ unsigned long long integer & @unsigned long long@ \\ short integer & @short@ \\ floating point & @float@ \textnormal{or} @double@ \textnormal{or} @long double@ \\ \bottomrule \end{tabular} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Integer and floating point data types} \begin{itemize} \item Types of integer data (each has an \alert{unsigned} counterpart): \begin{itemize} \item character \item integer \item short integer \item long integer \item long long integer \end{itemize} \item Types of floating point values: \begin{itemize} \item single precision (@float@) \item double precision (@double@) \item long double precision (@long double@) \end{itemize} \item The range of values that can be held are \alert{machine dependent}. \item The ranges of integer types are in \texttt{limits.h} \item The ranges of floating types are in \texttt{float.h} \end{itemize} \end{frame} \subsection{Integer Types} \label{sec:integer-types} \begin{frame} \frametitle{Signed integers --- 1} \begin{itemize} \item An unsigned integer has only positive values while a signed integer can have a positive or negative value. \item Signed Integers: \par\smallskip\par\noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule \K{int} & \textbf{use:} standard integer\\ \midrule% size: & system dependent, usually size of a word.\\ range: & \V{INT\_MIN} to \V{INT\_MAX}, defined in \texttt{limits.h}. For 4 byte word, $-2^{31} - 1$ to $2^{31}$, i.e., $-2147483648$ to 2147483647\\ example declaration: & @int num;@\\ example constant: & @1000@\\ \bottomrule \end{tabularx} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Signed integers --- 2} \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule \K{long} & \textbf{use:} large numbers\\ \midrule size: & usually 4 bytes.\\ range: & \V{LONG\_MIN} to \V{LONG\_MAX}. For 4 bytes, $-2^{31}$ to $2^{31} - 1$, i.e., $-2147483648$ to 2147483647\\ example declaration: & \V{long lnum}\Of{;}\\ example constant: & \N{5212000L}\\ \bottomrule \end{tabularx} \par\medskip\par% \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule \K{short} & \textbf{use:} smaller numbers\\ \midrule% size: & 2 bytes or same size as integer\\ range: & \V{SHRT\_MIN} to \V{SHRT\_MAX}. For 2 bytes, $-2^{15}$ to $2^{15} - 1$, i.e., $-32768$ to 32767 \\ declaration: & \V{short snum}\Of{;}\\ constants: & \N{120}\\ \bottomrule \end{tabularx} \end{frame} \begin{frame}[fragile] \frametitle{\K{long long}} \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule \K{long long} & \textbf{use:} very large numbers\\ \midrule size: & usually 8 bytes.\\ range: & for 8 bytes, $-2^{63}$ to $2^{63} - 1$, i.e., $-9$,223,372,036,854,775,808 to 9,223,372,036,854,775,807\\ example declaration: & \K{long long} \V{lnum}\Of{;}\\ example constant: & \N{5212000LL}\\ \bottomrule \end{tabularx} \par\medskip\par% \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule \K{unsigned long long} & \textbf{use:} very large positive numbers\\ \midrule size: & usually 8 bytes.\\ range: & for 8 bytes, 0 to $2^{64} - 1$, i.e., 0 to 18,446,744,073,709,551,615\\ example declaration: & \K{unsigned long long} \V{lnum}\Of{;}\\ example constant: & \N{5212000LL}\\ \bottomrule \end{tabularx} \end{frame} \begin{frame} \frametitle{Unsigned integers --- 1} \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule% \K{unsigned int} & \\ \midrule% size: & system dependent; always same size as \K{int}\\ range: & 0 to \V{UINT\_MAX}. For 4 byte word, 0 to $2^{32} - 1$, i.e., 4294967295\\ declaration: & \K{unsigned int} \V{unum}\Of; or \K{unsigned} \V{unum}\Of;\\ constants: & \N{5530u}\\ \bottomrule \end{tabularx} \end{frame} \begin{frame} \frametitle{Unsigned integers --- 2} \small% \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule% \K{unsigned long} & \\ \midrule% size: & usually 4 bytes; always same size as \K{long}\\ range: & 0 to \V{UINT\_MAX}. For 4 byte, 0 to $2^{32} - 1 = 4294967295$\\ example declaration: & \K{unsigned long} \V{ulnum}\Of;\\ example constant: & \N{76212000uL}\\ \bottomrule \end{tabularx} \par\medskip\par% \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule \K{unsigned short} & \\ \midrule% size: & usually 2 bytes; always same size as \K{short int}\\ range: & 0 to \V{USHRT\_MAX}. For 2 bytes, 0 to 65536 \\ example declaration: & \K{unsigned short} \V{usnum}\Of;\\ example constant: & \N{34000u}\\ \bottomrule \end{tabularx} \end{frame} \subsection{Characters} \label{sec:characters} \begin{frame}[fragile] \frametitle{Characters} \begin{itemize} \item When working with characters, use the type @char@. \item Note that the type @char@ can be signed \alert{or} unsigned, depending on the compiler. \end{itemize} \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule% \K{char} & \\ \midrule% size: & usually 8 bits; \V{CHAR\_BIT} in \texttt{limits.h}\\ range: & \V{CHAR\_MIN} to \V{CHAR\_MAX}. For 1 byte, could be $-2^{7}$ to $2^{7} - 1$, i.e., $-127$ to 128 \alert{or} 0 to 255\\ example declaration: & \K{char} \V{ch}\Of;\\ example constant: & \Sf{'a'}\\ \bottomrule \end{tabularx} \end{frame} \begin{frame} \frametitle{Characters: signed, unsigned} \mode{\small}% \begin{itemize} \item specify the type as signed or unsigned only if you care. \end{itemize} \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule% \K{signed char} & \\ \midrule% size: & usually 8 bits; \V{CHAR\_BIT} in \texttt{limits.h}\\ range: & \V{SCHAR\_MIN} to \V{SCHAR\_MAX}. For 1 byte, $-2^{7}$ to $2^{7} - 1$, i.e., $-127$ to 128\\ example declaration: & \K{signed char} \V{ch}\Of;\\ example constant: & \Sf{'a'}\\ \bottomrule \end{tabularx} \par\medskip\par% \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule \K{unsigned char} & \\ \midrule% size: & usually 8 bits; \V{CHAR\_BIT} in \texttt{limits.h}\\ range: & 0 to \V{UCHAR\_MAX}. For 1 byte, 0 to $2^{8} - 1 = 255$\\ example declaration: & \K{unsigned char} \V{ch}\Of;\\ \bottomrule \end{tabularx} \end{frame} \begin{frame}[fragile] \frametitle{Character types} \begin{itemize} \item Characters are represented in C with integer values. \item The correspondence between a given character and an integer value is determined by an agreed-upon character set, such as the ASCII character set. \item Examples of declarations: %[ char letter; signed char sletter; unsigned char uletter; %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{princhar.cpp}} \mode{\footnotesize}% %[ #include int main( void ) { char letter = 'A'; // 'A' is character constant int num = letter; char ch1 = 'b'; // ASCII code = 98 char ch2 = 'B'; // ASCII code = 66 std::cout << "letter = " << letter << ", num = " << num << '\n'; std::cout << "letter + 1 = " << letter + 1 << ", num = " << num << '\n'; std::cout << ch1 << " - " << ch2 << " = " << ch1 - ch2 << std::endl; } %] Output for Program \linkto{princhar.cpp}: \begin{verbatim} letter = A, num = 65 letter + 1 = 66, num = 65 b - B = 32 \end{verbatim} \end{frame} % \begin{frame}[fragile] % \frametitle{Output for Program \linkto{princhar.cpp}} % \begin{verbatim} % letter = A, num = 65 % letter + 1 = 66, num = 65 % b - B = 32 % \end{verbatim} % \end{frame} \subsection{Octal, Hexadecimal Output with \V{ostream}} \label{sec:octal-hex-output} \begin{frame}[fragile] \frametitle{Integer constants: octal and hexadecimal} \begin{itemize} \item An integer can be represented in an octal or a hexadecimal form. Octal integer constants are represented with a leading zero. Hexadecimal integer constant is represented with the leading characters @0x@, or @0X@. \par\medskip\par% \noindent% \begin{tabular}{lll} \toprule \textbf{Integer} & \textbf{Octal} & \textbf{Hexadecimal} \\ \midrule 4 & 04 & 0x4 \\ 12 & 014 & 0xc \\ 123 & 0173 & 0x7b \\ \bottomrule \end{tabular} \par\medskip\par% \item The long integer qualifier @L@ can also used with the octal and hexadecimal \item Example of octal constant: \ @0553000L@ \item Example of hexadecimal constant: \ @0x2f6c7a333L@ \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{printvar.cpp}} %\hypertarget{printvar.cpp}{}% \mode{% \renewcommand*{\LGsize}{\scriptsize}% }% %[ #include #include int main( void ) { int num = 77; short int small = 0173; short little = 0x7b; long int big = 88000; long large = -43000L; unsigned int unum = 45000; unsigned long ubig = 330000000UL; std::cout << std::showbase; std::cout << "num (dec) = " << num << ", (oct) = " << std::oct << num << ", (hex) = " << std::hex << num << '\n'; std::cout << "small (oct) = " << std::oct << small << ", little (hex) = " << std::hex << little << '\n'; std::cout << "big (dec) = " << std::dec << big << ", large (dec) = " << large << '\n'; std::cout << "unum = " << unum << ", ubig = " << ubig << '\n'; std::cout << "small (dec) = " << small << ", little (dec) = " << little << std::endl; } %] \end{frame} \begin{frame}[fragile] \frametitle{Output for Program \linkto{printvar.cpp}} \begin{verbatim} num (dec) = 77, (oct) = 0115, (hex) = 0x4d small (oct) = 0173, little (hex) = 0x7b big (dec) = 88000, large (dec) = -43000 unum = 45000, ubig = 330000000 small (dec) = 123, little (dec) = 123 \end{verbatim} \begin{itemize} \item We need to include \texttt{iomanip} here for the \emph{manipulators}: \begin{description} \item[\texttt{\textbf{std::oct}}] Changes the \alert{state} of the \texttt{ostream} to displaying all integer type numbers in \emph{octal}. \alert{All} numbers printed while in this state are in octal. \item[\texttt{\textbf{std::hex}}] Changes the \alert{state} of the \texttt{ostream} to displaying all integer type numbers in \emph{hexadecimal} \item[\texttt{\textbf{std::dec}}] Changes the \alert{state} of the \texttt{ostream} to displaying all integer type numbers in \emph{decimal} \item[\texttt{\textbf{std::showbase}}] a state that displays \emph{octal} with leading ``@0@'', \emph{hexadecimal} with leading ``@0x@'' \end{description} \end{itemize} \end{frame} \subsection{Floating Point Types} \label{sec:floating-point-types} \begin{frame} \frametitle{Floating point data types --- 1} \begin{itemize} \item The floating point data type is used to represent real numbers. Real numbers include the fractional number between integers. two components: an exponent and a fraction \par\noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule \textbf{@float@} & \\ \midrule size: & system dependent, usually four bytes.\\ range: & @FLT_MIN@ to @FLT_MAX@ defined in \texttt{float.h} \\ example declaration: & @float fnum;@ \\ example constant: & @3.456f@ \\ \bottomrule \end{tabularx} \end{itemize} \end{frame} \begin{frame} \frametitle{Floating point data types --- @float@} \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule% \textbf{@double@}\\ \midrule% size: & twice the size of float, usually eight bytes\\ range: & @DBL_MIN@ to @DBL_MAX@ defined in \texttt{float.h}\\ example declaration: & @double dnum;@\\ example constants: & floating point notation: @3.4567@ exponential notation: @4.788e+5@, @3e1@\\ \bottomrule \end{tabularx} \end{frame} \begin{frame} \frametitle{Floating point data types --- \K{long double}} \noindent% \begin{tabularx}{\linewidth}[t]{lY} \toprule% \K{long double} & \\ \midrule% size: & bigger than the size of double.\\ range: & @LDBL_MIN@ to @LDBL_MAX@ defined in \texttt{float.h}\\ example declaration: & \K{long double} \V{ldnum}\Of;\\ example constants: & \N{3.4567L} exponential notation: @4.788e+5L@\\ \bottomrule \end{tabularx} \end{frame} \begin{frame}[fragile] \frametitle{\program{float-io.cpp}} \mode{% \footnotesize% \renewcommand*{\LGsize}{\footnotesize}% } %[ #include int main( void ) { float cost = 15.92; float total = 3.6e5; float value = 357e-1; // value is 35.7 double debt = 1.2e15; long double decrease = 5e-6; std::cout << "cost = " << cost << ", total = " << total << '\n'; std::cout << "value = " << value << '\n'; std::cout << "debt = " << debt << '\n' << "decrease = " << decrease << '\n'; } %] Output for Program \linkto{float-io.cpp} \begin{verbatim} cost = 15.92, total = 360000 value = 35.7 debt = 1.2e+15 decrease = 5e-06 \end{verbatim} \end{frame} \begin{frame}[fragile] \frametitle{\program{float.cpp} showing limits of floating values} \mode{% \footnotesize% \renewcommand*{\LGsize}{\footnotesize}% } %[ #include #include int main() { std::cout << "float min: " << FLT_MIN << '\n'; std::cout << "float max: " << FLT_MAX << '\n'; std::cout << "double min: " << DBL_MIN << '\n'; std::cout << "double max: " << DBL_MAX << '\n'; std::cout << "long double min: " << LDBL_MIN << '\n'; std::cout << "long double max: " << LDBL_MAX << '\n'; std::cout << "float epsilon: " << FLT_EPSILON << '\n'; std::cout << "double epsilon: " << DBL_EPSILON << '\n'; std::cout << "long double epsilon: " << LDBL_EPSILON << '\n'; std::cout << "A long double constant: " << 4.788e+5L << '\n'; return 0; } %] \end{frame} \begin{frame}[fragile] \frametitle{Output for Program \linkto{float.cpp}} \begin{verbatim} float min: 1.17549e-38 float max: 3.40282e+38 double min: 2.22507e-308 double max: 1.79769e+308 long double min: 3.3621e-4932 long double max: 1.18973e+4932 float epsilon: 1.19209e-07 double epsilon: 2.22045e-16 long double epsilon: 1.0842e-19 A long double constant: 478800 \end{verbatim} \end{frame} % \begin{frame}[fragile] % \frametitle{Output for Program \linkto{float-io.cpp}} % \begin{verbatim} % cost = 15.92, total = 360000 % value = 35.7 % debt = 1.2e+15 % decrease = 5e-06 % \end{verbatim} % \end{frame} \subsection{Named Constants} \label{sec:named-constants} \begin{frame}[fragile] \frametitle{Symbolic constants: \Of\#\K{define}, \K{const}, and \K{enum}} \begin{itemize} \item \textbf{@#define@} can be thought of as a global substitution command. \item The @#define@ directive consists of the @#define@ keyword, a define symbol, and a replacement text. \item \program{define.cpp}: \end{itemize} %[ #include #define RATE 1.5 // Note: terminated by comment or newline int main( void ) { float cost = RATE * 8.0; std::cout << "Cost = " << cost << ", rate = " << RATE << '\n'; } %] \end{frame} \subsection{Enumerated Types: \K{enum}} \label{sec:enum} \begin{frame}[fragile] \frametitle{K{const} and \K{enum}} \mode{\small}% \begin{itemize} \item Using @const@ is better than @#define@. \program{const.cpp}: \end{itemize} {\mode{\renewcommand*{\LGsize}{\scriptsize}}% %[ #include int main( void ) { const float rate = 1.5; // with ";" float cost = rate * 8; std::cout << "cost = " << cost << ", rate = " << rate << '\n'; } %] } \begin{itemize} \item \program{enum-2.cpp}: \end{itemize} {\mode{\renewcommand*{\LGsize}{\scriptsize}}% %[ #include enum weather { clouds, rain, sunny, storm }; int main( void ) { weather today = sunny; std::cout << clouds << ' ' << rain << ' ' << sunny << ' ' << storm << '\n'; std::cout << "today: " << today << '\n'; } %] } \end{frame} \begin{frame}[fragile] \frametitle{Enumerated types --- 2} \begin{itemize} \item \program{enum-3.cpp}: \end{itemize} %[ #include enum weather { clouds = 30, rain = 5, sunny = 255, storm = 1 }; enum boolean { TRUE = 1, FALSE = 0 }; int main( void ) { weather today = rain; std::cout << clouds << ' ' << rain << ' ' << sunny << ' ' << storm << '\n'; std::cout << "today: " << today << '\n'; } %] \begin{itemize} \item Output of program \linkto{enum-3.cpp}: \begin{verbatim} 30 5 255 1 \end{verbatim} \end{itemize} \end{frame} \section{Expressions} \label{sec:expressions} \begin{frame} \frametitle{Expressions} \begin{itemize} \item Expressions define the tasks to be performed in a program do calculations perform function calls and assignment operations \item Arithmetic expressions perform the standard arithmetic operations. \begin{itemize} \item Arithmetic operator --- is a symbol or a binary operator, i.e. acts upon 1 or more operands or values. \item Operand ---- may be constant, variable, or function. \end{itemize} \bigskip \includegraphics[width=0.4\textwidth]{operator-operands} \end{itemize} \end{frame} \subsection{Arithmetic Expressions} \label{sec:arithmetic-expressions} \begin{frame}[fragile] \frametitle{Arithmetic operators --- unary} \begin{itemize} %\item divided into three main categories: \item Unary arithmetic operators: \begin{description} \item[@+@] plus, or positive \item[@-@] negative \end{description} \par\medskip\par% \noindent% \begin{tabular}[t]{ll} @-6@ & negative 6\\ @-( -6 )@ & positive 6\\ @-( 3 - 7 )@ & positive 4\\ @-y@ & change the sign of operand @y@ \end{tabular} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Arithmetic operators --- binary} \begin{itemize} \item Additive operators: \begin{description} \item[@+@] addition \item[@-@] subtraction \end{description} %[ total = 8 + 5 - 2; sum = num - 3; %] \item Multiplicative operators: \begin{description} \item[@*@] multiplication \item[@/@] division \item[@%@] modulo or remainder \end{description} %[ int total; total = 8 * 5; total = 23 / 4; // now @total@ has the value 5 total = 23 % 4; // now @total@ has the value 3 %] \end{itemize} \end{frame} \subsection{Arithmetic Operators and Precedence} \label{sec:arithmetic-operators-and-precedence} \begin{frame}[fragile] \frametitle{Arithmetic precedence and associativity} \begin{itemize} \item One operator may take precedence over another. \item When an expression is evaluated, it is broken down into a series of subexpressions, one for each operator. \item The order in which these subexpressions are evaluated is determined by either parentheses or precedence. \item Example: %[ ( 2 + 4 ) * ( 5 - 3 ) %] evaluates to the same as %[ 6 * 2 %] \item If there are no parentheses, precedence determines the order of evaluation \item All operators are ranked according to their precedence. \item Operators with greater precedence are evaluated first. \item Example: %[ 2 + 4 * 5 - 3 %] evaluates to the same as: %[ 2 + 20 - 3 %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Arithmetic Precedence and Associativity (cont')} \begin{itemize} \item If the operators share the same operand, the priority of one operator over the other will be determined by its associativity. Associativity describes how an operator associates its operands. \item Arithmetic operators associate left to right, whereas assignment operators associate right to left. \item Example: %[ 2 + 10 - 5 %] evaluates the same as %[ 12 - 5 %] \item The following table lists the precedence and assciativity of operators. \end{itemize} \end{frame} \subsection{All Operators and their Precedence} \label{sec:all-operators-and-their-precedence} \begin{frame}[allowframebreaks,fragile] \frametitle{All Operators and their Precedence} \setlength{\extrarowheight}{0pt}% \newcommand*{\cm}{,\,\,}% \newcommand*{\opSep}{0.5ex}% \mode {% \small% }% \mode
{% See table~\ref{tab:operators-and-precedence} for a list of all C operators and their precedence and associativity. \par% Associativity tells you whether, if the precedence is equal, whether the operators be applied from left to right (left associative), or from right to left (right associative). \begin{table}[tbh] \centering% } %@- \begin{tabular}{@{}lcl@{}} %@+ \toprule %@- \multicolumn{1}{@{}c}{\em Level} & \multicolumn{1}{c}{\em Operator} & \multicolumn{1}{c@{}}{\em Function} \\ %@+ \midrule 15L & @->@\cm@.@ & structure member selectors \\ & @[]@ & array index \\ & @()@ & function call \\ [\opSep] 14R & @sizeof@ & size in bytes \\ & @++@\cm@--@ & increment, decrement \\ & $\sim$ & bitwise NOT \\ & @!@ & logical NOT \\ & @+@\cm@-@ & unary plus, minus \\ & @*@\cm@&@ & dereference, address-of \\ & @()@ & type conversion (cast) \\ [\opSep] 13L & @*@\cm\texttt{/}\cm\textsf{\%} & multiply, divide, modulus \\ [\opSep] 12L & @+@\cm@-@ & arithmetic operators \mode
{% \\ [\opSep] }% \mode {% \\ \bottomrule \end{tabular} \par % \end{frame} % \begin{frame}[fragile] % \frametitle{Arithmetic precedence (cont')} % \setlength{\extrarowheight}{0pt}% % \newcommand*{\cm}{,\,\,}% % \newcommand*{\opSep}{0.5ex}% %@- \begin{tabular}{@{}lcl@{}} %@+ \toprule %@- \multicolumn{1}{@{}c}{\em Level} & \multicolumn{1}{c}{\em Operator} & \multicolumn{1}{c@{}}{\em Function} \\ %@+ \midrule }% end of mode presentation 11L & @<<@\cm@>>@ & bitwise shift \\ [\opSep] 10L & @<@\cm@<=@\cm@>@\cm@>=@ & relational operators \\ [\opSep] 9L & @==@\cm@!=@ & equality, inequality \\ [\opSep] 8L & @&@ & bitwise AND \\ [\opSep] 7L & @^@ & bitwise XOR \\ [\opSep] 6L & @|@ & bitwise OR \\ [\opSep] 5L & @&&@ & logical AND \\ [\opSep] 4L & @||@ & logical OR \\ [\opSep] 3L & @?:@ & arithmetic if \\ [\opSep] 2R & @=@ & assignment operator \\ & @*=@\cm@/=@\cm\textsf{\%=} & compound assignment operators \\ & \textsf{+=}\cm\textsf{$-$=}\cm@<<=@ & \\ & @>>=@\cm@&=@\cm@|=@\cm@^=@ & \\ [\opSep] 1L & @,@ & comma operator \\ \bottomrule \end{tabular} \mode
{% \caption{Table of C operators and their precedence} \label{tab:operators-and-precedence} \end{table} } \end{frame} \subsection{Relational Expressions} \label{sec:relational-expressions} \begin{frame}[fragile] \frametitle{Comparison Expressions} \begin{itemize} \item Relational, equality, and logical expressions compare their operands. the result of the comparison is the integer value of either one or zero. \item If an operation compares successfully, the result of the expression is an integer value of 1. If an operation compares fails, the result of the expression is an integer value of 0. \item A relational operator compares two operands and determines whether one is greater or less than the other. \par\noindent% \begin{tabular}[t]{ll} @<@ & less than \\ @>@ & greater than \\ @<=@ & less than or equal \\ @>=@ & greater than or equal \end{tabular} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Relational expressions --- 1} \begin{itemize} \item Relational expressions can be combined with other expressions. \item Example: %[ num = 3; abc = ( num < 5 ); %] As $3 < 5$, the resulting value of @abc@ is 1. \item Example: %[ num = 8; abc = 5 + ( num < 5 ); %] As $8 > 5$, the value of @abc@ is $5 + 0 = 5$. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Relational expressions --- 2} \begin{itemize} \item The equality operators test a relationship between two operands \item result is 1 or 0. \begin{description} \item[@==@] equal, \item[@!=@] not equal \end{description} \item equality operator is a double equal sign @==@ \item assignment operation is a single equals sign @=@ e.g \mode{\small} \begin{semiverbatim} \K{while} ( test \alert{==} 1 ) // \textnormal{\footnotesize{}comparison operation for equality} test \alert{=} 1; // \textnormal{\footnotesize{}assignment operation} \end{semiverbatim} \end{itemize} \end{frame} \subsection{Logical Expressions} \label{sec:logical-expressions} \begin{frame} \frametitle{Logical expressions --- 1} \begin{itemize} \item The logical operators compare the truth or false of their operands. determined by whether or not it has a zero value \begin{itemize} \item If an expression evaluates to zero, the expression is false \item If an expression evaluates to a non-zero, it is true. \end{itemize} \item The operands of a logical operation are often relational expressions. \par\noindent% \begin{tabular}[t]{ll} @&&@ & logical AND\\ @||@ & logical OR\\ @!@ & logical NOT\\ \end{tabular} \end{itemize} \end{frame} \begin{frame} \frametitle{Logical expressions --- 2} \mode {% \scriptsize% }% \begin{itemize} \item Here is the truth table for the logical AND operation: \par\smallskip\par \noindent% \begin{tabular}[t]{ll|ll|ll} \multicolumn{2}{c|}{\V{expr1}} & \multicolumn{2}{c|}{\V{expr2}} & \multicolumn{2}{c}{\Of(\V{expr1}\Of{) \&\& (}\V{expr2}\Of)} \\ \hline% T & non-zero & T & non-zero & T & 1\\ T & non-zero & F & 0 & F & 0\\ F & 0 & T & non-zero & F & 0\\ F & 0 & F & 0-zero & F & 0\\ \end{tabular} \par\smallskip\par% \item Truth table for the logical OR operation: \par\smallskip\par% \noindent% \begin{tabular}[t]{ll|ll|ll} \multicolumn{2}{c|}{\V{expr1}} & \multicolumn{2}{c|}{\V{expr2}} & \multicolumn{2}{c}{\Of(\V{expr1}\Of{) || (}\V{expr2}\Of)} \\ \hline% T & non-zero & T & non-zero & T & 1\\ T & non-zero & F & 0 & T & 1\\ F & 0 & T & non-zero & T & 1\\ F & 0 & F & 0-zero & F & 0\\ \end{tabular} \par\smallskip\par% \item Truth table for the logical NOT operation: \par\smallskip\par% \noindent% \begin{tabular}[t]{ll|ll} \multicolumn{2}{c|}{\V{expr}} & \multicolumn{2}{c}{\Of{!(}\V{expr}\Of)} \\ \hline% T & non-zero & F & 0\\ F & 0 & T & 1\\ \end{tabular} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{countdig.cpp}} %[ /* Counts only the numeric characters '0' - '9' read from standard input */ #include int main( void ) { int n = 0; char c; while ( std::cin >> c ) { if ( c >= '0' && c <= '9' ) n = n + 1; } std::cout << "Count of digits = " << n << '\n'; } %] \end{frame} \subsection{Assignment Expressions} \label{sec:assignment-expressions} \begin{frame}[fragile] \frametitle{Assignment expressions} \begin{itemize} \item assignment operation is an expression. \item resulting value of the assignment expression is the value assigned to the variable in the assignment operation. \item assignment operation can be combined with other operators to form a complex expression: %[ total = ( num = ( 4 + 2 ) ); %] \item Parentheses can be left out since assignment evaluate from right to left. %[ total = num = 4 + 2; %] which is identical to %[ total = 4 + 2; num = 4 + 2; %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Arithmetic assignment operators} \begin{itemize} \item provide a shorthand applying an arithmetic operation to a variable \begin{itemize} \item @j += 3;@ is equivalent to @j = j + 3;@ \item @j *= 3;@ is equivalent to @j = j * 3;@ \end{itemize} \item List of arithmetic assignment operators: \par\noindent% \begin{tabular}[t]{>{\ttfamily}ll} @+=@ & add and then assign\\ @-=@ & subtract and then assign \\ @*=@ & multiply and then assign\\ @/=@ & divide and then assign\\ @%=@ & modulo; assign remainder \end{tabular} \end{itemize} \end{frame} \subsection{Increment, Decrement Operators} \label{sec:increment-decrement-operators} \begin{frame}[fragile] \frametitle{Increment and decrement assignment operators} \begin{itemize} \item an assignment operation in which 1 is added/subtracted to a variable and the result assigned to that variable. \item The increment or decrement operator can operate in two ways: Prefix places the increment or decrement operator before its operand. Postfix places the increment or decrement operator after its operand. \item Example: %[ x = 32; y = ++x; %] imply $x = 32 + 1 = 33$ and $y = x = 33$ \item But %[ x = 32; y = x++; %] imply $y = x = 32$ and $x = 32 + 1 = 33$ \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{plusequl.cpp}} %[ #include int main( void ) { int n, j, k; k = j = n = 4; std::cout << "n = " << n << ", j = " << j << ", k = " << k << '\n'; n += j = 3; std::cout << "n = " << n << ", j = " << j << '\n'; } %] \alert{Output for Program \linkto{plusequl.cpp}:} \begin{verbatim} n = 4, j = 4, k = 4 n = 7, j = 3 \end{verbatim} \end{frame} \subsection{Comma Operator} \label{sec:comma-operator} \begin{frame}[fragile] \frametitle{Comma operator expressions} \begin{itemize} \item The comma operator expression is an expression that consists of a list of other expressions. \item The comma does not perform any operation on these expressions. \begin{itemize} \item they are simply evaluated sequentially as if they were a series of statements. \end{itemize} \item Example: %[ r = ( 3 * 5, 8.00 + 2.5, num = 5 ); %] \item The result is the value of the last expression in its list i.e., %[ r = num = 5 %] \item The main use of comma is in the headers of @for@ loops: %[ for ( i = 0, j = n; i < n; ++i, --j ) %] \end{itemize} \end{frame} \subsection{Arithmetic if Expressions\label{sec:arithmetic-if-expressions}} \begin{frame}[fragile] \frametitle{Arithmetic if Expressions} \begin{itemize} \item A conditional expression implements an if-else decision format. \item The conditional expression consists of three subexpressions: test expression and two alternative result expressions \par% {\color{red}\meta{expression1} \Of{?} \meta{expression2} \Of{:} \meta{expression3}} \par% \item If the test is true, the result will be the value of the second expression. \item If the test is false, the result will be the value of the third expression. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Arithmetic if expressions --- 2} \begin{itemize} \item When used in an assignment operation, the arithmetic if expression works like an if-else statement. %[ max = ( a > b ) ? a : b; %] \item equivalent to %[ if ( a > b ) max = a; else max = b; %] \end{itemize} \end{frame} \subsection{Bitwise Operators} \label{sec:bitwise-operators} \begin{frame} \frametitle{Bitwise operators --- 1} \begin{itemize} \item The bitwise operations allow the programmer to manipulate specific bits. \item The bitwise operations can be combined with \alert{masks} to turn specific bits on and off. \item The bitwise \alert{AND} operation, @&@, is used to \alert{clear} specific bits in an integer operand, leaving the other bits unchanged. \item The bitwise \alert{OR} operation, @|@, is used to \alert{set} specific bits in an integer operand, leaving the other bits unchanged \end{itemize} \end{frame} \begin{frame} \frametitle{Bitwise operators --- 2} \begin{itemize} \item Here is the truth table for the bitwise AND operation: \par\smallskip\par% \noindent% \begin{tabular}[t]{ll|ll|ll} \multicolumn{2}{c|}{\texttt{bit n}} & \multicolumn{2}{c|}{\texttt{bit m}} & \multicolumn{2}{c}{\texttt{m \& n}} \\ \hline% T & 1 & T & 1 & T & 1\\ T & 1 & F & 0 & F & 0\\ F & 0 & T & 1 & F & 0\\ F & 0 & F & 0 & F & 0\\ \end{tabular} \par\smallskip\par% \item Truth table for the bitwise OR operation: \par\smallskip\par% \noindent% \begin{tabular}[t]{ll|ll|ll} \multicolumn{2}{c|}{\texttt{bit n}} & \multicolumn{2}{c|}{\texttt{bit m}} & \multicolumn{2}{c}{\texttt{m | n}} \\ \hline% T & 1 & T & 1 & T & 1\\ T & 1 & F & 0 & T & 1\\ F & 0 & T & 1 & T & 1\\ F & 0 & F & 0 & F & 0\\ \end{tabular} \end{itemize} \end{frame} \begin{frame} \frametitle{Bitwise operators --- 3} \mode{\footnotesize}% \begin{itemize} \item The one's complement operator, $\sim$, is a unary operator. \item The resulting value is set to the opposite of that of the operand's bit. \par\smallskip\par% \noindent% \begin{tabular}[t]{ll} \toprule% bit \texttt{m} & $\sim$\texttt{m}\\ \midrule% 0 & 1 \\ 1 & 0 \\ \bottomrule \end{tabular} \par\medskip\par% \item The bitwise exclusive OR operator, \textasciicircum, results in 1 if the corresponding two bits are different: \par\smallskip\par% \noindent% \begin{tabular}[t]{ccc} \toprule% bit \texttt{m} & bit \texttt{m} & \texttt{m \textasciicircum{} n}\\ \midrule% 0 & 0 & 0 \\ 0 & 1 & 1 \\ 1 & 0 & 1 \\ 1 & 1 & 0 \\ \bottomrule \end{tabular} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Shift Operators} \begin{itemize} \item There are two shift operators: \begin{description} \item[@<<@] left shift operator \item[@>>@] right shift operator \end{description} \item useful for accessing individual parts of a bit pattern \item shift the bits of the left operand some number of positions to the left or right. \end{itemize} %[ unsigned char bits = 1; // 0000 0001 bits = bits << 1; // 0000 0010 bits = bits << 2; // 0000 1000 bits = bits >> 3; // 0000 0001 %] \end{frame} \begin{frame}[fragile] \frametitle{Right Shift Operator} \mode {% \renewcommand*{\LGsize}{\scriptsize}% }% \begin{itemize} \item the right shift operator will fill negative signed numbers with `1's from the left, but will shift 0 into the MSb (most significant bit) of unsigned numbers. \item \program{shiftright-demo.cpp} \end{itemize} %[ #include #include int main( void ) { int test_numbers[] = { -16, 16, -1, 1 }; const int len = sizeof( test_numbers ) / sizeof( test_numbers[ 0 ] ); for ( int i = 0; i < len; ++i ) { int n = test_numbers[ i ]; unsigned u = n; std::cout << showbase; std::cout << "dec n: " << dec << n << "; n >> 2: " << ( n >> 2 ) << "\thex n: " << hex << n << "; n >> 2: " << ( n >> 2 ) << '\n'; std::cout << "dec u: " << dec << u << "; u >> 2: " << ( u >> 2 ) << "\thex u: " << hex << u << "; u >> 2: " << ( u >> 2 ) << '\n'; } } %] \end{frame} \begin{frame}[fragile] \frametitle{Right Shift Operator: example output} \begin{itemize} \item output of program \linkto{shiftright-demo.cpp} (folded to fit): \end{itemize} {% \mode {% \footnotesize% }% \begin{verbatim} dec n: -16; n >> 2: -4 hex n: 0xfffffff0; n >> 2: 0xfffffffc dec u: 4294967280; u >> 2: 1073741820 hex u: 0xfffffff0; u >> 2: 0x3ffffffc dec n: 16; n >> 2: 4 hex n: 0x10; n >> 2: 0x4 dec u: 16; u >> 2: 4 hex u: 0x10; u >> 2: 0x4 dec n: -1; n >> 2: -1 hex n: 0xffffffff; n >> 2: 0xffffffff dec u: 4294967295; u >> 2: 1073741823 hex u: 0xffffffff; u >> 2: 0x3fffffff dec n: 1; n >> 2: 0 hex n: 0x1; n >> 2: 0 dec u: 1; u >> 2: 0 hex u: 0x1; u >> 2: 0 \end{verbatim} } \begin{itemize} \item Notice that when shifted right: \begin{itemize} \item unsigned values have the upper two bits zero \begin{itemize} \item so the \alert{unsigned} value 0xfffffff0 shifted right by two is 0x3ffffffc \end{itemize} \item signed values have the upper two bits the same as the previous value of the MSb (most significant bit) \begin{itemize} \item so the \alert{signed} value 0xfffffff0 ($-16$) shifted right two places is 0xfffffffc \end{itemize} \end{itemize} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Use of bitwise operators} \begin{itemize} \item Use the AND operator `@&@' to \alert{clear} individual bits, leaving the others unchanged \begin{itemize} \item For example, %[ x = x & 0xf; %] will clear all but the least significant four bits of @x@ \end{itemize} \item Use the OR operator `@|@' to \alert{set} individual bits, leaving the others unchanged \begin{itemize} \item For example, %[ y = y | ~0xf; %] will set all bits except for the least significant four bits of @y@ \end{itemize} \item Use the Exlusive OR operator `@^@' to \alert{toggle} (flip) individual bits, leaving the others unchanged \begin{itemize} \item For example, %[ z = z ^ 0xf; %] will toggle the least significant four bits of @z@, i.e., make 1s~$\leftrightarrow$~0s \end{itemize} \end{itemize} \end{frame} \subsection{Casts} \label{sec:casts} \begin{frame}[fragile] \frametitle{Cast expressions} \mode {% \footnotesize% }% \begin{itemize} \item The cast operation returns the value of an expression, converting it to the type in the brackets %takes the value of its operand converts it % to the type designated within the parentheses of the cast. \item Example: %[ ( float ) 7 %] \vspace*{-3ex} \begin{itemize} \item This converts the integer 7 to a floating point value, 7.00. \end{itemize} \item The operand may be any expression \begin{itemize} \item Examples: %[ ( int ) ( 5.8 * 2.7 ) ( double ) ( k = 10 ) ( float ) num %] \end{itemize} \item If a floating point value is cast to an integer, the floating point fraction is lost. \begin{itemize} \item Example: \vspace*{-1ex} %[ ( int ) 3.75 %] \vspace*{-3ex} \item resulting value is 3 \end{itemize} \item Casts overide the compiler's concept of correctness --- \alert{use rarely} \end{itemize} \end{frame} \begin{frame} \frametitle{Conversions} \begin{itemize} \item Expressions can include operands of different number types \item Example: An integer can be multiplied by a float. \item C handled operands of different types by converting one of them into the same type as that of the other operand. \item Conversion determines which operand to convert by a process of \alert{promotion} and \alert{demotion}. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Conversions: promotion} \begin{itemize} \item In expressions with two different types of operands, the operand with the smaller type is always \alert{promoted} to that of the largest type. \item Example: %[ int num = 6; float cost; cost = num * 5; %] \item The expression @num * 5@ results in the integer @30@ and will be promoted to a @float@, @30.0@ before assigned into the @cost@ variable. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Conversions: demotion} \begin{itemize} \item \alert{Demotion} from a floating point type to an integer type results in the loss of the floating point's fraction. \item Example: %[ int num; float cost = 62.65; num = cost; %] \item The fraction will be cut off, leaving just the integer, 62. The value 62 is then assigned to the variable @num@. \end{itemize} \end{frame} \section{Statements} \label{sec:statements} \begin{frame} \frametitle{Statements: an introduction} \begin{itemize} \item A C program is a sequence of \alert{declarations} and \alert{statements}. \item We have seen: \begin{itemize} \item how to declare variables, and \item how to create expressions using operators \item examples of putting this all together. \end{itemize} \item Now let's look at \textbf{\alert{statements.}} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Statements: intro --- 2} \begin{itemize} \item We can turn an expression such as @x = 0@ or @std::cout << "a"@ into a statement simply by putting a semicolon at the end: %[ x = 0; std::cout << "a"; %] \item We can join these into a \alert{compound statement} by putting braces \textbf{\texttt{\{ \}}} around them. \item There are some which are used to create \alert{loops} and make \alert{\textsf{decisions}}. These are sometimes called \alert{\textsf{control-flow statements}}. \end{itemize} \end{frame} \subsection{Simple Statements} \label{sec:simple-statements} \begin{frame}[fragile] \frametitle{Expression statements} \begin{itemize} \item An \alert{expression statement} consists of any valid expression, followed by a semicolon. \item Often the expression is an assignment operation or a function call. \item Example: %[ count = 8; num = 3 + 4; calc(); %] \item However, the expression could just as easily be an arithmetic expression or relational expression. \item Example: %[ 4 + 5; // nothing done with the result, 9. ( n < 3 ); %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Null statement (empty statement)} \begin{itemize} \item If there is no expression in the expression statement, nothing happens. This is called as the \alert{null statement}. \renewcommand*\LGsize{\large} \item Example: %[ ; // just a semicolon %] \end{itemize} \end{frame} \subsection{Compound Statements} \label{sec:compound-statements} \begin{frame}[fragile] \frametitle{Compound Statements} \begin{itemize} \item A compound statement is a statement composed of one or more statements. \item A compound statement consists of opening and closing braces within which statements are placed. \item Example: %[ { num = 6; fact = ( 5 - 3 ); std::cout << fact << ", " << num << '\n'; } %] \end{itemize} \end{frame} \begin{frame} \frametitle{Blocks --- 1} \begin{itemize} \item Variables can be declared at the beginning of compound statement. A compound statement with variable declarations is referred to as a \alert{block}. \item The body of a function is a compound statement itself, and is often referred to as the \alert{function block}. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{blocks.cpp}} %[ #include int main( void ) { int num = 10; float cost = 100.0; { float cost = 50.0; num = 5; std::cout << "Inside: " << cost << ", " << num << '\n'; } std::cout << "Outside: " << cost << ", " << num << '\n'; } %] \begin{itemize} \item Output of program \linkto{blocks.cpp}: \end{itemize} \begin{verbatim} Inside: 50, 5 Outside: 100, 5 \end{verbatim} \end{frame} \subsection{Scope} \label{sec:scope} \begin{frame}[fragile] \frametitle{Scope} \begin{itemize} \item A new \alert{scope} is created in each block \item the compiler searches for an identifier defined in the innermost scope first \item then searches the scopes that the enclose current scope\ldots \item \ldots\,until it reaches global scope \begin{itemize} \item global scope is outside of any block \end{itemize} \item identifiers defined in an inner scope ``hide'' identifiers defined in an outer scope \item For example, in program~\linkto{blocks.cpp}, there are two variables called @cost@ in different nested scopes \begin{itemize} \item The inner output statement prints the value of the @cost@ variable defined in the inner scope \item The outer output statement prints the @cost@ defined in the outer scope. \end{itemize} \end{itemize} \end{frame} \subsection{Looping Statements} \label{sec:looping-statements} \begin{frame} \frametitle{Iteration statements} \begin{itemize} \item Loops are implemented with three \alert{iteration statements}: \begin{itemize} \item @while@ \item @do@ \item @for@ \end{itemize} \item Each statement repeats a statement called the \alert{body of the loop} \item The body of the loop can be any statement, including: \begin{itemize} \item \alert{compound} statement, or \item another loop, or \item a null statement. \end{itemize} \end{itemize} \end{frame} \subsection{\K{while} Statement} \label{sec:while-statement} \begin{frame}[fragile] \frametitle{\K{while} statement} \begin{itemize} \item \textbf{@while@} loop consists of the keyword \textbf{@while@}, a test expression in parentheses, and a statement. \item statement is repeated for as long as the test expression evaluates to a non-zero value. \begin{semiverbatim} \K{while} ( \alert{\meta{test expression}} ) \alert{\meta{statement}}; \end{semiverbatim} \item Example: %[ i = 0; // initialize the loop counter while ( i < 5 ) { std::cout << "ABC "; ++i; // update the loop counter // very important } // the loop becomes infinite // without this statement that // changes the loop counter %] \end{itemize} \end{frame} \subsection{\K{do} statement} \label{sec:do-statement} \begin{frame}[fragile] \frametitle{Iteration Statements --- @do@ loop} \begin{itemize} \item The @do@ statement is a variation on the while statement. \item Instead of the test occurring at the beginning of the loop, it occurs at the end, \item Example: %[ i = 0; do { std::cout << "abc\n"; ++i; // loop counter } while ( i < 4 ); %] \end{itemize} \end{frame} % \begin{frame}[fragile] % \frametitle{\program{while-3.cpp}} % %[ % #include % const int max = 3; % int main( void ) % { % int num; % num = 1; % while ( num < max ) { % std::cout << "The " % << num % << " iteration\n"; % num = num + 1; % } % } % %] % \end{frame} \begin{frame}[fragile] \frametitle{\program{square-1.cpp}} %[ #include int main( void ) { int num; std::cout << "Enter a number: "; std::cin >> num; while ( num != 0 ) { int square = num * num; std::cout << "Square of " << num << " = " << square << '\n'; std::cout << "Enter a number (0 to quit): "; std::cin >> num; } } %] \mode {% \small% }% \begin{itemize} \item This program has a major problem. \item What happens if we input a character that is not part of an integer? \end{itemize} \end{frame} \subsection{Avoid Confusing == with =} \label{sec:avoid-confusing-==-with-=} \begin{frame} \frametitle{Test Expression} \begin{itemize} \item The test expression for the @while@, @for@, and @if@ statements can be any valid expression, \item Example: \begin{itemize} \item assignment operation \item simple primary expression consisting of a variable or a constant \end{itemize} \item A zero result evaluated is considered to be false while any non-zero result is true. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Traps with = and ==} \begin{itemize} \item Don't confuse comparison with assignment in a test expression. \begin{semiverbatim} \K{while} ( \V{i} \alert{=} \V{k} ) \{ ... \} \end{semiverbatim} \item If \alert{\V{k}} equals 0, the test will always be false \item If \alert{\V{k}} is not equal to zero, the test will always be true. \item Examples of \alert{incorrect} test expressions: {\mode{\footnotesize}% \begin{semiverbatim} \K{while} ( \V{n} \alert{=} 0 ) \{ {\scriptsize/* always false */} ... \} \K{while} ( \V{n} \alert{=} 3 ) \{ {\scriptsize/* always true, an infinite loop */} ... \} \end{semiverbatim} } \item The correct way to write these test expressions is: \begin{semiverbatim} \K{while} ( \V{n} \alert{==} 0 ) \{ ... \} \K{while} ( \V{n} \alert{==} 3 ) \{ ... \} \end{semiverbatim} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{quit-1.cpp}} %[ #include /* This program shows problems that come from confusing assignment with comparison */ int main( void ) { int quit = 0, num = 1, square; while ( quit = 0 ) // Oh dear; always false { // the loop body will never be executed square = num * num; std::cout << "Square of " << num << " = " << square << '\n'; if ( num = 10 ) // Oh dear; always true quit = 1; num++; } } %] \end{frame} % \begin{frame}[fragile] % \frametitle{Assignment from a function call expression} % \begin{itemize} % \item Assignment expressions can be combined with function calls to % form a very powerful test expression. it can call functions and % assign values. % \item The following example is a loop which reads in and prints out % characters until the user enters a carriage return. % %[ % ch = getchar(); % while ( ch != '\n' ) { % putchar( ch ); % ch = getchar(); % } % %] % \item The combination of an assignment operation and function call % perform the same operation: % %[ % while ( ( ch = getchar() ) != '\n' ) % putchar(ch); % %] % \end{itemize} % \end{frame} \subsection{Using a constant or single variable as a test condition} \label{sec:using-a-constant-or-single-variable-as-a-test-condition} \begin{frame}[fragile] \frametitle{Using a constant or single variable as a test condition} \begin{itemize} \item Constants are often used to write infinite loops. \item Variables are used as a shorthand for comparing the value of the variable to zero. \item Example: %[ while ( 1 ) // infinite loop while ( 0 ) // never execute loop while ( i ) // is equivalent to // @while ( i != 0 )@ %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{square-2.cpp}} %[ #include int main( void ) { int num; while ( 1 ) { // or for (;;) std::cout << "Please enter a number: "; if ( ! ( std::cin >> num ) ) break; int square = num * num; std::cout << "Square of " << num << " = " << square << '\n'; char ch; std::cout << "Another square? (y/n) "; if ( std::cin >> ch && ch != 'y' ) break; } } %] \end{frame} \subsection{\K{while} and the null statement} \label{sec:while-and-for-loops} \begin{frame}[fragile] \frametitle{\K{while} test and null statement} \begin{itemize} \item A @while@ statement can be written in which the test expression does all the work. The statement following the test expression is simply a null statement. \item Example: %[ while ( std::cin.get( ch ) && ch != '\n' ) ; // do nothing %] \item Three actions take place in the above example: \begin{itemize} \item function call to the \texttt{istream} member function @get()@ \item @std::cin.get( ch )@ will return false if reach end of input file; \item inequality operation in which character value obtained by @std::cin.get()@ is tested against a newline constant. \end{itemize} \item End result is that we wait till we get a newline character, or end of file \end{itemize} \end{frame} \subsection{\K{for} Statement} \label{sec:for-statement} \begin{frame}[fragile] \frametitle{The \K{for} Statement} \begin{itemize} \item The for statement consists of three expressions followed by a statement. \begin{semiverbatim} \alert{\K{for}} ( \meta{expression 1}; \meta{expression 2}; \meta{expression 3} ) \meta{statement}; \end{semiverbatim} \item \meta{expression 1} is executed once, before loop begins. It is often used to \alert{initialize} variables used in the test expression. \item \meta{expression 2} is the \alert{test} expression for the loop. When it evaluates as false, the loop stops. \item \meta{expression 3} \alert{update} expression. It is executed within the loop and is usually used to update variables used in the test expression. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Example of \K{for} loop} \mode {% \renewcommand*{\LGsize}{\Large}% }% %[ for ( int i = 1; i < 3; ++i ) { std::cout << "OK\n"; } %] \end{frame} \subsection{Comparing \K{while} and \K{for}} \label{sec:comparing-while-and-for} \begin{frame}[fragile] \frametitle{\K{for} and \K{while}: a comparison} \mode{\scriptsize\renewcommand{\LGsize}{\scriptsize}}% \noindent% \begin{minipage}[t]{0.5\linewidth} %\begin{columns}[t] %\column{.5\textwidth}% \noindent% \K{for} loop: \vspace{\baselineskip} \begin{semiverbatim} \K{for} ( \meta{init}; \meta{test}; \meta{update} ) \{ \meta{body of loop} \} \end{semiverbatim} \vspace{3\baselineskip} example: %[ for ( int i = 0; i < 3; ++i ) std::cout << "loop " << i << '\n'; %] \end{minipage}% \hspace{1em}% \begin{minipage}[t]{0.45\linewidth} %\column{.5\textwidth}% \K{while} loop: \vspace{\baselineskip} \begin{semiverbatim} \meta{init}; \K{while} ( \meta{test} ) \{ \meta{body of loop} \meta{update}; \} \end{semiverbatim} \vspace{\baselineskip} example: %[ int i = 0; while ( i < 3 ) { std::cout << "loop " << i << '\n'; ++i; } %] \end{minipage} %\end{columns} \end{frame} \begin{frame}[fragile] \frametitle{Nested loops --- loop within a loop} \begin{itemize} \item The inner loop executes fully within each iteration of the outer loop \item Example: %[ for ( int k = 0, i = 0; i < 3; ++i ) { for ( int j = 0; j < 3; ++j ) { ++k; std::cout << k << ' '; } std::cout << '\n'; } %] \item See example program \texttt{nested-for.cpp} \item Output: \begin{verbatim} 1 2 3 4 5 6 7 8 9 \end{verbatim} \end{itemize} \end{frame} \subsection{\K{if} and \K{switch} Statements} \label{sec:if-and-switch-statements} \begin{frame}[fragile] \frametitle{Conditions: \K{if} statement} \begin{itemize} \item The \red{@if@} and \red{@switch@} statements are decision making structures that determine which statements are to be executed and which are not. \item @if@ is a condition placed on a statement's execution. \begin{itemize} \item if the condition is true, the statement is executed \item if the condition is false, the statement is not executed \end{itemize} \begin{semiverbatim} \K{if} ( \meta{test expression} ) \meta{statement}; \end{semiverbatim} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\K{if} and \K{else}} \begin{itemize} \item The @if@ statement can choose between several choices using @else@: \begin{semiverbatim} \K{if} ( \meta{condition} ) \{ doThis(); \} \K{else if} ( \meta{condition 2} ) \{ doThat(); \} \K{else} \{ doTheOther(); \} \end{semiverbatim} \item Only \alert{one} action is performed \item the first that matches is done. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{The \K{switch} statement --- 1} \begin{itemize} \item The @switch@ statement provides a convenient way to choose among several alternatives. \item It is a conditional statement (selection) \begin{semiverbatim} \K{switch} ( \meta{integer expression} ) \{ \K{case} \meta{integer}: \meta{statements}; \K{break}; \K{case} \meta{integer}: \meta{statements}; \K{break}; \K{default}: \meta{statements}; \K{break}; \} \end{semiverbatim} \end{itemize} \end{frame} \begin{frame} \frametitle{The \texttt{switch} statement --- 2} \begin{itemize} \item The @switch@ compares an \alert{integer value} against a set of integer constants. \item The execution will continue unless a @break@ is encountered. \end{itemize} \end{frame} \subsection{\K{break}, \K{continue}, \K{goto}} \label{sec:break-continue-goto} \begin{frame} \frametitle{The jump Statements} \begin{itemize} \item The jump statements are non-structured control statements that allow the program to jump across statements. \item Strickly speaking, these are not allowed in structured programming. \item However, @break@ and @continue@ are especially useful. \item @break@ and @continue@ statements are used with @while@, \K{for}, and \K{switch} statements. \item @break@ provides an exit condition other than that of the statement's test expression. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Example of use of \K{continue}} \begin{itemize} \item Kernighan and Ritchie provide this example of using @continue@: %[ for ( i = 0; i < n; ++n ) { if ( a[ i ] < 0 ) // skip negative elements continue; // do positive elements } %] \item See also my example program \texttt{cat.cpp} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\K{goto}: use it seldom} \begin{itemize} \item @goto@ and \alert{label} statements allow the program to jump to any statement. \item Using @goto@ can cause the program to become very hard to understand \item Use it only when you really have to \begin{itemize} \item An example is to break out of a nested loop from the inner loop \end{itemize} %[ for ( i = small; i < big; ++i ) for ( j = small2; j < bigger; ++j ) if ( i == j ) goto equal; equal: %] \item \V{equal} here is a label \end{itemize} \end{frame} \mode
\subsection{Exercises} \label{sec:exercises-with-if-else-and-while-for} \begin{enumerate} \item Write a program using the following code fragment as a guide: %[ int i = 10; if ( i > 0 ) std::cout << "i > 0\n"; if ( i > 1 ) std::cout << "i > 1\n"; if ( i > 2 ) std::cout << "i > 2\n"; // ... if ( i > 10 ) std::cout << "i > 10\n"; else std::cout << "something else\n"; %] \item Save your source to a different file name, but replace all the @if@s (except the first) to @else if@s. \item Run your two programs and compare the output. \item Write a program contianing a @while@ loop and a @for@ loop that both output data and do the same thing. \end{enumerate} \mode \section{Functions} \label{sec:functions} \begin{frame} \frametitle{Functions --- 1} \begin{itemize} \item A big program may be too complex to hold in your head. \item I need a way to break a big problem into many small, easy-to-understand problems. \item One way to break a problem into small problems is to divide a problem into small parts that can be written as \alert{functions}. \item A \alert{function} is a number of statements that: \begin{itemize} \item Perform one easily-understood job \item are given a single name. \end{itemize} \item A function is a little bit like a simple IC, with input pins and output pins. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Functions --- 2} \begin{itemize} \item A function may have inputs and outputs: \medskip% \begin{center} \includegraphics[width=0.5\linewidth]{function-box} \end{center} \medskip% \item The function call: %[ y = sin( x ); %] can be represented by the block diagram above. \item The inputs go in the parentheses: @()@ \item The output of the function can be assigned, as above. \end{itemize} \end{frame} \begin{frame} \frametitle{Functions --- 3} \begin{itemize} \item To write and use functions in your program, there are two things to consider: \item When you \alert{define} the function, you write the statements that the function will perform when it is \alert{called}. \item When you want to \alert{use} the function, we say we \alert{call} the function. \end{itemize} \end{frame} \subsection{Defining Functions} \label{sec:defining-functions} \begin{frame}[fragile] \frametitle{Function definition} \begin{itemize} \item A function definition consists of a \alert{header} and a \alert{body}. \item \alert{header} contains the function name, its return type, and parameter types. \item The \alert{body} of a function is a block, which usually contains variable declarations and statements. \begin{semiverbatim} \meta{return type} \meta{function_name}( \meta{parameter list} ) \{ \meta{variable definitions}; \(\vdots\) \meta{statements}; \} \end{semiverbatim} \item Example: %[ void calc( void ) { int num; num = 5; } %] \end{itemize} \end{frame} \subsection{Calling Functions} \label{sec:calling-functions} \begin{frame}[fragile] \frametitle{Function definition and call} \framesubtitle{\program{nowincal.cpp}} %[ // Program to call a function #include // function definition: void calc( void ) { std::cout << "Now in Calc\n"; } int main( void ) { std::cout << "Hello World\n"; calc(); std::cout << "Now in Main\n"; } %] \end{frame} \subsection{Using \K{return} Value from Functions} \label{sec:using-return-value} \begin{frame}[fragile] \frametitle{Functions as expressions} \begin{itemize} \item A function call is an expression whose value is the function's return value. \item \program{calc-2.cpp} \end{itemize} %[ #include float calc( void ) { return 8.0 * 5.35; } int main( void ) { float res1 = calc(); float res2 = 7 + 5 * calc(); if ( calc() > 5 ) std::cout << "Larger\n"; std::cout << "res1 = " << res1 << ", res2 = " << res2 << '\n'; } %] \end{frame} \begin{frame} \frametitle{\K{return} statement and function return value} \begin{itemize} \item The @return@ statement consists of the keyword @return@, an expression, and a semicolon. \item Syntax: @return@ \alert{\meta{expression}}\texttt{;} \item The \alert{\meta{expression}} is called the \alert{return} expression. \item @return@ statement will: \begin{itemize} \item end the processing of a function \item make execution continue from where the function was called, and \item specify the function's return value. \end{itemize} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Function return value: example} \framesubtitle{\program{calc-3.cpp}} %[ #include // Example of a function that takes // parameters float calc( int num, float calc_rate ) { return calc_rate * num; } int main( void ) { float rate = 2.0; float res = calc( 5, rate ); std::cout << "res = " << res << '\n'; } %] \end{frame} \begin{frame} \frametitle{Return inconsistencies} \begin{itemize} \item Return value inconsistencies: occur when the \alert{return expression} has a type different from the function's \alert{return type}. \item The \alert{return expression} is what comes between the keyword @return@ and the semicolon. \item The \alert{return type} is what is written before the name of the function in a function definition. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{retbad-1.cpp}} %[ #include short getnum( void ) { long num = 2147483647L; std::cout << "Number is " << num << '\n'; return num; } int main( void ) { long res = getnum(); // return value inconsistency std::cout << "result is " << res << '\n'; } %] \begin{itemize} \item Output for program \linkto{retbad-1.cpp}: \end{itemize} \begin{verbatim} Number is 2147483647 result is -1 \end{verbatim} \end{frame} \begin{frame}[fragile] \frametitle{\program{retbad-2.c}} %[ #include calc( void ) /* return type missing */ { /* gives return type inconsistency */ /* legal in C */ /* Illegal in C++, won't compile */ float cost = 8.0 * 5.35; return cost; } int main( void ) { float res1; res1 = calc(); printf( "%f\n", res1 ); } %] \begin{itemize} \item Output from program \linkto{retbad-2.c}: \end{itemize} \begin{verbatim} 42.000000 \end{verbatim} \end{frame} \subsection{Function Parameters} \label{sec:function-parameters} \begin{frame} \frametitle{Function parameters} \begin{itemize} \item Functions may have zero or more \alert{parameters}. \item Parameters are usually the \textbf{inputs} to the function. \item Parameters appear in the parentheses after the name of the function, both in the function definition and in the function call. \item The \alert{type} and \alert{\textsf{number}} of parameters must match in: \begin{itemize} \item function definition, and \item function call. \end{itemize} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Function parameters --- 2} \begin{itemize} \item In this example the parameters match \item \program{funcmult.cpp} %[ #include float mult( int a, float b ) { return a * b; } int main( void ) { int x = 3; float y = mult( x, 4.5 ); // function call std::cout << "y = " << y << '\n'; } %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Function parameters --- 3} \begin{itemize} \item In the function definition of @mult()@: \vspace*{-2ex} %[ float mult( int a, float b ) { return a * b; } %] \vspace*{-2ex} \begin{itemize} \item the first parameter is called @a@. \item the second parameter is called @b@. \end{itemize} \item In the function call, \vspace*{-2ex} %[ float y = mult( x, 4.5 ); // function call %] \vspace*{-2ex} \begin{itemize} \item the value of @x@ is copied to @a@, the value 4.5 is copied into @b@. \item The \alert{type} of the parameter in the function call matches the type of the parameter \alert{in the same position} in the function definition. \item This is like pins on an IC plugging into the holes in the IC socket. \end{itemize} \end{itemize} \end{frame} % \subsection{Macros} % \label{sec:macros} % \begin{frame}[fragile] % \frametitle{Macros --- 1} % \begin{itemize} % \item A \texttt{\#define} symbol can be used not only to represent % constants, but expressions and even whole statements. % \item The \texttt{\#define} does not recognize statements or % expressions. It only performs a substitution on text. % \item \program{macros-1.cpp}: % %[ % #include % #define VAL 1.2 % #define GREETING ( std::cout << "Hi\n" ) % #define MULT ( 4 * 5 ) % int main( void ) % { % int result = MULT; % GREETING; % std::cout << "VAL is " << VAL % << ", result equals " << result << '\n'; % } % %] % \end{itemize} % \end{frame} % \begin{frame}[fragile] % \frametitle{Macros --- 2} % \begin{itemize} % \item The define symbol with arguments can be described as macro and % is often written in lower case. % \item \program{macro-no-parens.cpp} % {\footnotesize % %[ % #include % // Bad, no don't write macros like this: % #define add( x, y ) x + y % // Yes, Write them with parentheses: % #define add2( x, y ) ( ( x ) + ( y ) ) % int main( void ) % { % int num = 2 * add( 4, 6 ); // num = 2 * 4 + 6 % std::cout << "'2 * add( 4, 6 )' = " << num << '\n'; % int num2 = 2 * add2( 4, 6 ); // num2 = 2 * ( 4 + 6 ) % std::cout << "'2 * add2( 4, 6 )' = " << num2 << '\n'; % } % %] % } % \item Note that when a macro is combined with other expressions, % precedence and associativity rules can cause unintended results, \item Example: % %[ % 100 / mult (2, 5) % %] % \item which is equal to \texttt{100 / 2 * 5} or \texttt{(100 / 2) * % 5}. % \item Better: \texttt{\#define add( x, y ) ( ( x ) + ( y ) )} % \end{itemize} % \end{frame} % \begin{frame}[fragile] % \frametitle{Macros --- use parentheses} % \begin{itemize} % \item A define macro should always have a set of parentheses placed % at the beginning and end of its replacement text. % \item Example: % %[ % #define mult( x, y ) ( x * y ) % j = 100 / mult( 2, 5 ); % %] % \item which is equal to \texttt{j = 100 / ( 2 * 5 )} % \item Functions that can be written as single expressions could be % replaced by a macro that will expand to a expression. % \item Example: % %[ % #define max( x, y ) ( ( x > y ) ? x : y ) % %] % \item Danger! % \begin{itemize} % \item It won't work properly with a call like this: % %[ % j = max( ++i, ++j ); % %] % \item Why not? % \end{itemize} % \end{itemize} % \end{frame} \section{Arrays} \label{sec:arrays} \begin{frame} \frametitle{Arrays} \begin{itemize} \item An array is a collection of objects, all of the same data type. \item Any one data type can be used in an array. \begin{itemize} \item an array of integers \item an arrary of characters \item an array of structures \item an array of pointers \end{itemize} \item The declaration of an array reserves memory, which is then managed by pointers (to be discussed in next section). \item Array objects themselves are actually referenced through pointer indirection. \end{itemize} \end{frame} \subsection{Defining Arrays} \label{sec:defining-arrays} \begin{frame} \frametitle{Array declaration} \begin{itemize} \item An array declaration consists of 4 parts \begin{itemize} \item the data type \item array name, \item square brackets around the\ldots \item \ldots\,number of objects in the array \end{itemize} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Arrays --- 2} \begin{itemize} \item The declaration below declares an array of 5 integers. The array name is @mynums@ %[ int mynums[ 5 ]; %] \item Many different kinds of arrays may be declared, each having its own data type and number objects. \par\noindent% \begin{tabularx}{\linewidth}[t]{>{\ttfamily}lY} \K{int} total[10]; & an array of ten integers (i.e. \texttt{total[0]}, \texttt{total[1]},\,\ldots\, \texttt{total[9]})\\ \K{ char} name[40]; & an array of forty characters (i.e. \texttt{name[0]}, \texttt{name[1]},\,\ldots\,\texttt{name[39]}) \end{tabularx} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Array initialisation} \begin{itemize} \item When a variable is defined it can be \alert{initialised} with a value. In the declaration: %[ char mychar = 'E'; %] \item the variable @mychar@ is \alert{initialised} with the character @'E'@. \item The elements of an array can also be initialised in an array declaration. The initalisation values are listed within curly braces and separated by commas: %[ int mynums[ 5 ] = { 3, 4, 5, 6, 7, }; %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Array Length} \begin{itemize} \item When using standard C, the initialization part of the array declaration can be used be left out of the array declarations. The number is, instead, determined by the number of values in the initialisation block. \item \program{array-1.cpp} %[ #include int main( void ) { char letters[] = { 'A', 'B', 'C', }; int totals[] = { 23, 8, 11, 31, }; std::cout << letters[ 1 ] << ' '; std::cout << totals[ 3 ] << '\n'; } %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Array references and array notation} \begin{itemize} \item Once an array has been declared, its objects can be referenced and used in expressions. \item The array name, together with the position of an object in the array is used to reference an object. \item The objects in an array are arranged in sequence, starting from zero. The number of an object's place in that sequence is referred to as either the object's index or subscript. \item In the example above, we can see %[ mynums[ 0 ] = 3; // first object mynums[ 1 ] = 4; // second object mynums[ 2 ] = 5; // third object mynums[ 3 ] = 6; // fourth object mynums[ 4 ] = 7; // fifth object %] \end{itemize} \end{frame} \subsection{Arrays and Loops} \label{sec:arrays-and-loops} \begin{frame}[fragile] \frametitle{Array management and loops} \begin{itemize} \item Operations cannot be performed on an array as a whole. \item To assign a set of values to an array, you need to assign a value to each element individually. \item An array is only a collection of objects. It is not an object itself. We use loops to process all these objects. \item \program{arrayprt.cpp} %[ #include int main( void ) { int nums[] = { 23, 8, 11, 31 }; for ( int i = 0; i < 4; ++i ) { std::cout << nums[ i ] << ' '; } std::cout << '\n'; } %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Array Management and Loops --- 2} \begin{itemize} \item A common rule of thumb is that the test for the end of an array is the less than operator, @<@, tested against the number of objects declared in the array. \item Example: this @for@ loop prints each number in the array: %[ int nums[ 4 ] = { 42, 1000, 7, 103 }; for ( int i = 0; i < 4; ++i ) std::cout << "this num is " << nums[ i ] << '\n'; %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Using constants for array size} \begin{itemize} \item In the listing below, the same symbolic constant, \textbf{\texttt{max}}, is used in both the array declaration and the test for the last array object in the \textbf{\texttt{for}} statement. %[ #include const int max = 4; int main( void ) { int mynums[ max ] = { 23, 8, 11, 31 }; for ( int i = 0; i < max; ++i ) std::cout << mynums[ i ] << ' '; std::cout << '\n'; } %] \end{itemize} \end{frame} \mode
\subsection{Exercise} \label{sec:exercise-array} Write a program that: \begin{enumerate} \item Reads up to 20 numbers into an array; \item After reading those numbers, the program calculates and prints the sum of the numbers in the array. \item Note that your program should stop attempting to read numbers when there are no more numbers to read, i.e., because you have reached end of file, or a character is in the input that cannot be part of a number. \end{enumerate} \mode \subsection{Strings} \label{sec:strings} \begin{frame}[fragile] \frametitle{Arrays of characters: strings} \begin{itemize} \item A \alert{string} is an array of characters. \item Here are examples of definitions of strings: %[ char name[ 20 ]; char string[] = "This is a string"; char str[ 10 ] = "string"; char letters[ 10 ] = { 's', 't', 'r', 'i', 'n', 'g', '\0' }; %] \item Note that the string definitions @str@ and @letters@ are equivalent. \item Note that a string is automatically ended with a special character called the \alert{null} character, @'\0'@ \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Arrays of characters: strings --- 2} \begin{itemize} \item Because the string has the extra @'\0'@ character at the end, the array of characters must be long enough to hold it. \item Example: %[ char string2[] = "string"; %] \item \ldots\ has seven characters, so this would be wrong: %[ char string3[ 6 ] = "string"; // too short! %] \item but these are okay: %[ char string4[ 7 ] = "string"; char string5[ 100 ] = "string"; %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Careful: strings cf. characters} \begin{itemize} \item A common mistake is to confuse a string with a character. \item Example: %[ char c; // Wrong! A character has single quotes: @'A'@ c = "A"; %] \item The string @"A"@ is actually \alert{\textsf{two}} characters: @'A'@ then @'\0'@. \item One final note: do not assign strings! %[ char str[ 100 ]; str = "this is a string"; /* Oh no, a mistake! Use @strcpy()@ library function instead. */ strcpy( str, "this is a string" ); // OK %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Working with strings} \begin{itemize} \item The standard C++ \texttt{strings} library is the best choice for simplicity, but the Borland 3.1 compiler does not seem to support it \item The standard library that comes with (nearly) every C compiler provides lots of functions for working with strings. \item To use them, put: %[ #include %] \item at the top of your program. \item Here are some: \item @strlen()@ --- give the length of a string \item @strcpy()@ --- copy one string to another string \item @strcmp()@ --- compare two strings \item @strcat()@ --- join one string onto the end of another \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Working with strings 2} \begin{itemize} \item Example using @strlen()@: %[ int len; len = strlen( "a string" ); // @len@ = 8 %] \item Example using @strcpy()@: %[ char str1[ 100 ], str2[] = "a string"; strcpy( str1, str2 ); %] \end{itemize} \end{frame} \section{Pointers} \label{sec:pointers} \begin{frame} \frametitle{Pointers} \begin{itemize} \item Any object defined in a program can be referenced through its address. A pointer is a variable that has as its value the address of an object. \item A pointer is used as a referencing mechanism. \item A pointer provides a way to reference an object using that object’s address. \item There are 3 elements involved in this referencing process: \begin{itemize} \item a pointer variable \item an address \item and another variable \end{itemize} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Pointer holds address} \begin{itemize} \item A pointer variable holds the \alert{address} of another variable of a \alert{particular type} \item \program{pointer-1.cpp} \mode{\small}% %[ #include int main( void ) { int num = 12; int *nptr; nptr = # std::cout << "num holds " << num << " and nptr points to " << *nptr << '\n'; std::cout << "The address held in nptr is " << nptr << '\n'; } %] \item Output of program \linkto{pointer-1.cpp}: \begin{verbatim} num holds 12 and nptr points to 12 The address held in nptr is 0xbfafade8 \end{verbatim} \end{itemize} \end{frame} \subsection{Pointers as Function Parameters} \begin{frame}[fragile] \frametitle{Pointers as Function Parameters} \begin{itemize} \item If you try to write a function to swap its parameters like this: %[ void swap( int x, int y ) { int temp = x; x = y; y = temp; } %] and call it like this: @swap( a, b );@, the values of @a@ and @b@ are copied by value, so the final values are not changed. \item The right way is to pass the \alert{address} of @a@ and @b@ like this: @swap( &a, &b );@ and define the function like this: %[ void swap( int *x, int *y ) { int temp = *x; *x = *y; *y = temp; } %] \item This is how to change the value of a parameter. \end{itemize} \end{frame} \section{Arrays and Pointers} \subsection{Strong relationship between arrays and pointers} \begin{frame}[fragile] \frametitle{C Arrays are very low level} \mode{% \renewcommand{\LGsize}{\footnotesize}% \small }% \begin{itemize} \item Pointers and arrays have a strong relationship \item Any operation using array subscripting can be done using pointers \item If we define an array of integers and a pointer to an integer like this: \par\vspace*{-3.5ex}\par %[ int a[ 10 ]; int *pa; %] \par\vspace*{-1ex}\par% and if we make @pa@ point to the start of the array @a[]@ like this:% \par\vspace*{-4ex}\par% %[ pa = &a[ 0 ]; %] \par\vspace*{-1ex}\par% then the value of @*pa@ is the same as is stored in @a[ 0 ]@. \item \sloppypar{}The pointer @pa + 1@ points to the value of % @a[ 1 ]@, so this statement is true: \allowbreak% @*( pa + 1 ) == a[ 1 ]@ \item If we add `@1@' to a pointer, we point to the address just after the value stored at that pointer. \begin{itemize} \mode{% \footnotesize }% \item If @sizeof( int )@ is 4, and if addresses each hold one character, then the address @pa + 1@ is 4 address locations higher than the address @pa@. \item The \alert{type} of the pointer determines what address you get when you increment a pointer. \end{itemize} \item similarly @*( pa + i ) == a[ i ]@ is true. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{C Arrays and pointers} \begin{itemize} \item The name of an array is the same as the location of the first element, so these two statements are equivalent: \par\vspace*{-4ex}\par %[ pa = &a[ 0 ]; pa = a; %] \par\vspace*{-1ex}\par \item These statements are also true: \par\vspace*{-4ex}\par %[ a[ i ] == *( a + i ); &a[ i ] == a + i; %] \par\vspace*{-1ex}\par \item An expression made of an array and index has an equivalent expression made with a pointer and offset. \item \alert{Important:} we can do \par\vspace*{-4ex}\par %[ ++pa; // okay; now @pa@ points to @a[ 1 ]@ %] \par\vspace*{-1ex}\par \item \ldots\,but not: \par\vspace*{-4ex}\par %[ ++a; // compiler error %] \par\vspace*{-1ex}\par \item \ldots\,because an \alert{array name is a constant}, but an ordinary pointer is not. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Passing arrays to functions} %\mode{% % \renewcommand{\LGsize}{\scriptsize}% % \small %}% \begin{itemize} \item If a parameter is an array name, inside the function it is a pointer to the first element of the array \item If you find the size of an array with @sizeof@, you are given the number of elements $\times$ the size of one element \item Inside a function, the size of an array parameter is the size of a pointer. \item See program \linkto{array-parameter.cpp}. \item Note that the @sizeof@ operator gives the number of characters in either a type or an expression: \item @sizeof( T )@ gives the number of characters in the type @T@ \item @sizeof expression@ gives the number of characters in the expression @expression@. % \par\vspace*{-4ex}\par % %[ % #include % #include % int ar[ 10 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; % void check_array_parameter( int a[] ) % { % std::cout << "sizeof( a ) = " << sizeof( a ) << '\n'; % std::cout << "sizeof( ar ) = " << sizeof( ar ) << '\n'; % } % int main( void ) % { % check_array_parameter( ar ); % int nelements = sizeof( ar ) / sizeof ar[ 0 ]; % std::cout << "sizeof( ar ) = " << sizeof( ar ) << '\n' % << "number of elements in ar[] is " << nelements % << '\n'; % } % %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{array-parameter.cpp}} \mode{% \renewcommand{\LGsize}{\footnotesize}% \small }% \par\vspace*{-3ex}\par %[ #include int ar[ 10 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; void check_array_parameter( int a[] ) { std::cout << "sizeof( a ) = " << sizeof( a ) << '\n'; std::cout << "sizeof( ar ) = " << sizeof( ar ) << '\n'; } int main( void ) { check_array_parameter( ar ); int nelements = sizeof( ar ) / sizeof ar[ 0 ]; std::cout << "sizeof( ar ) = " << sizeof( ar ) << '\n' << "number of elements in ar[] is " << nelements << '\n'; } %] \par\vspace*{-1ex}\par \begin{itemize} \item Output of \linkto{array-parameter.cpp} \end{itemize} \begin{verbatim} sizeof( a ) = 4 sizeof( ar ) = 40 sizeof( ar ) = 40 number of elements in ar[] is 10 \end{verbatim} \end{frame} \begin{frame}[fragile] \frametitle{Passing arrays to functions --- 3} \begin{itemize} \item To work properly, you need to \alert{pass the length of an array} as a \alert{separate parameter} together with the array. \item Example: \par\vspace*{-3ex}\par %[ double mean( int nums[], int len ) { int sum = 0; for ( int i = 0; i < len; ++i ) { sum += nums[ i ]; } if ( len == 0 ) return 0; return ( double ) sum / len; } %] \item Note that it makes no difference to write the parameter as @int nums[ 100 ]@, since that length information will not be passed to the function as part of the @int nums[ 100 ]@ parameter \item If the length of the array passed to @mean()@ is 100, then that number must be passed as a \alert{separate parameter}. \end{itemize} \end{frame} \section{Multidimensional Arrays and arrays of pointers} \subsection{Arrays of pointers} \label{sec:arrays-of-pointers} \begin{frame}[fragile] \frametitle{Arrays of pointers} \begin{itemize} \item Arrays of pointers are very commonly used in C, because this gives much greater flexibility than alternatives (see slide \S\pageref{sec:multidimensional-arrays}) \item Can easily sort an array of pointers; copy only the address, not the data \item Can define an array of pointers to lines like this: %[ const int maxlines 10000; char *line[ maxlines ]; %] \item We must make sure that we allocate memory using the @new@ operator for this as we read lines. \end{itemize} \end{frame} \subsection{Memory Allocation} \label{sec:memory-allocation} \begin{frame}[fragile] \frametitle{Allocating memory with \K{new}} \begin{itemize} \item If we don't know how much data we will read, we need to \alert{allocate} memory as we need it \begin{itemize} \item The @new@ operator allocates memory as it is needed \item deallocate (free) memory with the @delete@ operator \end{itemize} \item If allocating a scalar value, use syntax like this: \begin{semiverbatim} \meta{pointer} = \K{new} \meta{type}; \end{semiverbatim} and free the memory like this: \begin{semiverbatim} \K{delete} \meta{pointer}; \end{semiverbatim} \item if allocating an \alert{array} or \alert{string}, use syntax like this: \begin{semiverbatim} \meta{pointer} = \K{new} \meta{type}[ \meta{length} ]; \end{semiverbatim} and free the memory like this: \begin{semiverbatim} \K{delete} [] \meta{pointer}; \end{semiverbatim} \item the result from @new@ is a null pointer if the memory cannot be allocated. \begin{itemize} \item \alert{Always} check the return value of @new@ \end{itemize} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Example use of \K{new}: \program{new-1.cpp}} \mode {% \renewcommand*{\LGsize}{\footnotesize}% } \begin{itemize} \item Program \linkto{new-1.cpp} does the following: \begin{itemize} \item dynamically allocate an array of ten integers \item terminate if allocation doesn't succeed \item put a value into each element of the array \item print each value \item free up the memory \end{itemize} \end{itemize} %[ #include #include int main( void ) { const int maxn = 10; int *a = new int[ maxn ]; if ( a == NULL ) { std::cerr << "Out of memory!\n"; exit( 1 ); } for ( int i = 0; i < maxn; ++i ) a[ i ] = i + 1; for ( int i = 0; i < maxn; ++i ) std::cout << "a[ " << i << " ] = " << a[ i ] << '\n'; delete [] a; } %] \end{frame} \begin{frame}[fragile] \frametitle{\program{new.cpp} --- 1} \mode{\renewcommand*{\LGsize}{\scriptsize}}% %[ #include #include // Read all of input into memory. Normally we would process one line // at a time, as we read it. // Read each line into a string // allocate memory for the string and copy the string into that memory // add the newly allocated string to an array of pointers int read_lines( char *lines[], int maxnlines ) { const int maxlinelen = 8000; char line[ maxlinelen ]; int nlines = 0; while ( std::cin.getline( line, maxlinelen ) ) { int len = std::cin.gcount(); // includes space for '\0' char *p; if ( nlines >= maxnlines || ( p = new char[ len ] ) == NULL ) { return -1; } else { strcpy( p, line ); lines[ nlines++ ] = p; } } return nlines; } %] \end{frame} \begin{frame}[fragile] \frametitle{Program \texttt{new.cpp} --- 2} \mode{\renewcommand*{\LGsize}{\scriptsize}}% %[ void write_lines( char *lines[], int nlines ) { while ( nlines-- > 0 ) std::cout << *lines++ << '\n'; } void free_lines( char *lines[], int nlines ) { while ( nlines-- > 0 ) delete [] *lines++; } int main( void ) { const int maxlines = 10000; char *line[ maxlines ]; int nlines = read_lines( line, maxlines ); if ( nlines >= 0 ) { write_lines( line, nlines ); free_lines( line, nlines ); } else { std::cerr << "Input is too big to read\n"; } } %] \end{frame} \subsection{Multidimensional Arrays} \label{sec:multidimensional-arrays} \begin{frame}[fragile] \frametitle{Multidimensional Arrays} \begin{itemize} \item Not used as much as arrays of pointers \item Usually we allocate memory with new for each string %[ int matrix[ 2 ][ 4 ] = { { 1, 2, 3, 4 }, { 10, 20, 30, 40 } }; %] defines a rectangular matrix. \item We can access the entry with the value 30 with %[ int entry = matrix[ 1 ][ 2 ]; %] \item Note that this is \alert{wrong}, and just uses the comma operator: %[ int entry = matrix[ 1, 2 ]; // WRONG!!! % %] \end{itemize} \end{frame} \subsection{Command Line Arguments: \V{argc}, \V{argv}} \label{sec:argc-argv} \begin{frame}[fragile] \frametitle{\V{argc} and \V{argv}} \begin{itemize} \item The @main()@ function takes two optional parameters that are always called @argc@ and @argv@: %[ int main( int argc, char *argv[] ) %] \item parameter @argc@ is the number of arguments on the command line \alert{including the program name} \item parameter @argv@ is a pointer to an array of command line arguments \item if the program \texttt{echo} is called like this: \begin{verbatim} echo this is a test \end{verbatim} \item then @argc@ is 5, @argv[ 0 ]@ is @"echo"@, @argv[ 1 ]@ is @"this"@, @argv[ 2 ]@ is @"is"@, @argv[ 3 ]@ is @"a"@, @argv[ 4 ]@ is @"test"@ and finally @argv[ 5 ]@ is the null pointer. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{echo.cpp}} \begin{itemize} \item The program \linkto{echo.cpp}: %[ #include int main( int argc, char *argv[] ) { for ( int i = 1; i < argc; ++i ) std::cout << argv[ i ] << ' '; std::cout << '\n'; } %] \item prints its parameters, like the echo command in the Windows \texttt{CMD.EXE} shell, or like the echo command built into the \texttt{bash} shell that is popular with Linux. \end{itemize} \end{frame} \section{Structures} \label{sec:structures} \begin{frame}[fragile] \frametitle{Structures --- 1} \label{sld:employee} \begin{itemize} \item A structure consists of a set of data objects that can be referenced as one object. \begin{semiverbatim} \K{struct} \alert{\meta{tag name}} \{ \alert{\meta{list of declarations}} \}; \end{semiverbatim} \item A tag can be used to label a structure type declaration. In the structure type declaration, the keyword struct may be followed with a tag placed before the opening brace of the declaration list, \item Example: %[ struct employee { int id; float salary; }; %] \end{itemize} \end{frame} % \begin{frame}[fragile] % \frametitle{Structure variables} % \begin{itemize} % \item define a structure variable \texttt{user}. % (\texttt{employee} was declared on slide~\pageref{sld:employee}) % \begin{itemize} % \item In C, we must always use the keyword @struct@: % %[ % struct employee user; % %] % \item In C++ we do not need to: % %[ % employee user; % %] % \end{itemize} % % \item or, without giving the type a name: % % %[ % % struct { % % int id; % % float salary; % % } user; % %] % \end{itemize} % \end{frame} \begin{frame}[fragile] \frametitle{Defining \K{struct} variables} \begin{itemize} \item We can define a variable @person@ of the type % @struct employee@ like this: %[ struct employee { int id; float salary; }; // somewhere else: struct employee person; %] \item We can now refer to the two values in the variable @person@ as @person.id@ and @person.salary@ \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Initialising \K{struct} variables} \begin{itemize} \item We can initialise a structure when it is defined by putting a list of values in braces, as we do for arrays \item The first item in that list initialises the first element of the structure, \item the second item initialises the second element of the structure, \item \ldots \item We could initialise our @struct employee@ like this: %[ struct employee person = { 8, 80000 }; %] \item After this, @person@ will contain the same values as in the next slide. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Structures: \program{struct.cpp}} %[ #include int main( void ) { struct employee { int id; float salary; }; struct employee person; person.id = 8; person.salary = 80000; std::cout << "ID = " << person.id << '\n'; std::cout << "Salary = $" << person.salary << '\n'; } %] %$ \end{frame} \subsection{Passing Structures to Functions} \label{sec:passing-structures} \begin{frame}[fragile] \frametitle{Accessing a structure through a pointer} \begin{itemize} \item Given a pointer to a struct declared as: %[ struct employee { int id; float salary; }; struct employee person; struct employee *p = &person; %] \item we could access the members with the \alert{arrow operator} `@->@' like this: %[ p->id = 8; p->salary = 80000; std::cout << "ID = " << p->id << '\n'; std::cout << "Salary = $" << p->salary << '\n'; %] %$ \item There is nothing magic about the ``@->@'' operator; it is just a shorthand used, because we often access members of structures through pointers \item Note that ``@p->id@'' is equivalent to ``@(*p).id@'', and ``@p->salary@'' is equivalent to ``@(*p).salary@''. \end{itemize} \end{frame} \begin{frame} \frametitle{Passing Structures to Functions} \begin{itemize} \item Unlike arrays, structures are passed to functions \alert{by value} \item That means that your function only gets a copy of the structure. \item If you want to modify the original structure, you need to either: \begin{itemize} \item return the modified structure, or \item pass a pointer to the structure. \end{itemize} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Passing Structures: example}% Here we use the @struct employee@ defined previously. Passing structure by value %[ struct employee raise_salary( struct employee p, float raise ) { p.salary += raise; return p; } // in another function: struct employee manager = { 50, 100000 }; manager = raise_salary( manager, 20000 ); %] Passing a pointer to structure: %[ void raise_salary( struct employee *p, float raise ) { p->salary += raise; } // in another function: struct employee manager = { 50, 100000 }; raise_salary( &manager, 20000 ); %] \end{frame} \begin{frame}[fragile] \frametitle{Structures: \program{complex.cpp}} \mode{% \renewcommand*{\LGsize}{\scriptsize}% }% %[ #include struct complex { int re; int im; }; complex cadd( complex z1, complex z2 ) { complex zt; zt.re = z1.re + z2.re; zt.im = z1.im + z2.im; return zt; } int main( void ) { complex za; za.re = 1; za.im = 2; complex zb = za; complex zc = cadd( za, zb ); std::cout << "zc.re = " << zc.re << ", zc.im = " << zc.im << '\n'; } %] Output of program \linkto{complex.cpp}: \begin{verbatim} zc.re = 2, zc.im = 4 \end{verbatim} \end{frame} \subsection{\K{typedef}} \label{sec:typedef} \begin{frame}[fragile] \frametitle{\K{typedef}} \begin{itemize} \item A @typedef@ is used to allow the programmer to give another name to a type. %\item @typedef@ is less useful in C++ than in C. \item \begin{semiverbatim} \K{typedef} \alert{\meta{type} \meta{NAME}}; \end{semiverbatim} defines \meta{NAME} as a new name for the existing type \meta{type} \item Example: %[ typedef float FF; // @FF@ is now a type FF abc; // equivalent to @float abc;@ %] \item Often @typedef@ is used with @struct@ variables to avoid needing to type the word ``@struct@'' \begin{itemize} \item I do not encourage you to do this. \item See \url{http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_paper/codingstyle.ps}, and search for ``\texttt{typedef} is evil'' at section 3.5. \end{itemize} \end{itemize} \end{frame} \section{Reading and Writing Files} \label{sec:file-io} % \begin{frame} % \frametitle{Text Files --- 1} % \begin{itemize} % \item Each C compiler has a set of low level system call functions % that connect to and access files through the operating system % \item These system I/O functions all take a set of standard % arguments and perform very simple read and write operations on a % file. % \item There is another set of C file functions stream I/O file % functions, that impose an abstract logical organization on files, % regardless of their physical structure % \item These file functions establish a file interface that allows % them to treat each file as a byte stream file. A file is a % continuous stream of bytes. It can be read, written, and % referenced, one byte at a time. % \end{itemize} % \end{frame} \subsection{\texttt{fstream}: file input and output} \label{sec:fstream-file-input-and-output} \begin{frame} \frametitle{Text Files --- \texttt{ifstream} and \texttt{ofstream}} \begin{itemize} \item We work with text files much the same way as with standard input and standard output \item Open a file for input --- \textbf{\texttt{ifstream}} \item Open a file for output --- \textbf{\texttt{ofstream}} \item when the \texttt{fstream} object goes out of scope, the file is \alert{automatically closed} \end{itemize} \end{frame} % \begin{frame}[fragile] % \frametitle{Text files --- 4} % %[ % FILE *fptr; % fptr = fopen( "data.txt", "r" ); % if ( fptr == NULL ) % exit( 1 ); % fclose( fptr ); % %] % \begin{itemize} % \item There are 3 basic modes for opening a file: % \end{itemize} % \begin{description} % \item["r"] Allows only reading from a file. The file must already % exist. If the file does not exist, fopen operation will fail. % The file can only be read, but not written. % \item["w"] Allows only writing to a file. The file will be % created. If the file already exists, it will be destroyed. % \item["a"] Allows only writing at the end of a file. Same as "w" % mode, a file will be created if it does not existed. If a file % already exists, it will simply be opened, not destroyed. % \end{description} % \end{frame} % \begin{frame} % \frametitle{Text files --- 5} % \begin{itemize} % \item Updating a file requires both reading and writing to the % file. read/write specifiers are added to basic mode: % \end{itemize} % \begin{description} % \item["r+"] As with the \texttt{"r"} mode, a file will be opened. % The file can be both read from and written to. If the file does % not exist, the open operation will fail. % \item["w+"] As with the \texttt{"w"} mode, a file will be created. % The file can be both read from and written to. If the file already % exists, it will be destroyed. % \item["a+"] As with the \texttt{"a"} mode, a file will be created % if it does not exist. If a file does exist, it will simply be % opened, not destroyed. The file can be both written to and read % from. However, the file can only be written to at the end of the % file. Data in the file that already exists cannot be overwritten % or updated. % \end{description} % \end{frame} \subsection{Error Handling} \label{sec:error-handling} \begin{frame}[fragile] \frametitle{If cannot open a file, what next?} \begin{itemize} \item If you fail to create an \texttt{ifstream} object (perhaps the file does not exist), the object evaluates as \alert{false} \item It is \alert{always essential} to test the result of things that can go wrong, and provide an error message or return an error code \item If things have gone wrong, it may be better to stop the program using the @exit()@ command. \item Note: @#include @ when you use @exit()@. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Text Files --- 7} %[ #include #include // ... std::ifstream fin( "data.in" ); if ( ! fin ) { std::cerr << "error: unable to open file " << "'data.in' for reading\n"; exit( 1 ); } std::ofstream fout( "data.out" ); if ( ! fout ) { std::cerr << "error: unable to open file " << "'data.out' for writing\n"; exit( 1 ); } %] % \begin{itemize} % \item In some systems, such as MSDOS or Windows, files require a % binary specification (not required in Unix), \item Example: % %[ % fopen( "abc.bin", "rb" ); % %] % \item add this to support portable programs. % \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Appending to files} \begin{itemize} \item To append to a file, use the extra parameter @std::ios::app@ when defining the \texttt{ofstream} object: %[ #include #include // ... std::ofstream fout( "data.out", std::ios::app ); if ( ! fout ) { std::cerr << "error: unable to open file " << "'data.out' for appending\n"; exit( 1 ); } %] \item There are a number of other parameters available. \item OR them together with the bitwise OR operator ``\verb!|!'' \end{itemize} \end{frame} \subsection{Binary files} \label{sec:binary-files} \begin{frame}[fragile] \frametitle{Binary files --- 1} \begin{itemize} \item To open a file for binary input or output, use the extra parameter @std::ios::binary@ when defining the \texttt{ofstream} or \texttt{ifstream} object: \mode{% \renewcommand*{\LGsize}{\scriptsize}% }% %[ #include #include // ... std::ofstream fout( "data.out", std::ios::app | std::ios::binary ); if ( ! fout ) { std::cerr << "error: unable to open binary file " << "'data.out' for appending\n"; exit( 1 ); } %] \item Here we open a binary file for input: %[ #include #include // ... std::ifstream fin( "data.in", std::ios::in | std::ios::binary ); if ( ! fin ) { std::cerr << "error: unable to open binary file " << "'data.in' for reading\n"; exit( 1 ); } %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Binary files --- 2} \begin{itemize} \item Here we open a binary file for output: \mode{% \renewcommand*{\LGsize}{\small}% }% %[ #include #include // ... std::ofstream fout( "data.out", std::ios::out | std::ios::binary ); if ( ! fout ) { std::cerr << "error: unable to open binary file " << "'data.out' for writing\n"; exit( 1 ); } %] \end{itemize} \end{frame} % \begin{frame} % \frametitle{} % \begin{itemize} % \item % \end{itemize} % \end{frame} \subsection{Character I/O} \label{sec:character-i/o} \begin{frame}[fragile] \frametitle{Character Input and Output} \begin{itemize} \item We can treat a file as a stream of characters. The \texttt{istream} member function @get()@ and the \texttt{ostream} member function @put()@ read and write one character at a time. \item \program{copy-file-to-output.cpp}: \mode{% \renewcommand*{\LGsize}{\scriptsize}% }% %[ #include #include #include int main( void ) { char ch; std::ifstream fin( "abc.txt" ); if ( ! fin ) { std::cerr << "Cannot open file abc.txt\n"; exit( 1 ); } // skips whitespace. // while ( fin >> ch ) // std::cout << ch; while ( fin.get( ch ) ) std::cout.put( ch ); } %] \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Character I/O with Text Files --- 2} \begin{itemize} \item \program{copyfile.cpp} %[ #include #include #include int main( void ) { char ch; std::ifstream fin( "abc.txt" ); std::ofstream fout( "mmm.txt" ); if ( ! fin || ! fout ) { std::cerr << "Problem opening files\n"; exit( 1 ); } // The following skips white space: // while ( fin >> ch ) // fout << ch; while ( fin.get( ch ) ) fout.put( ch ); } %] \end{itemize} \end{frame} \subsection{Reading a Line at a time: \texttt{getline()}} \label{sec:reading-a-line-at-a-time-getline()} \begin{frame}[fragile] \frametitle{Working with Lines in Text Files} \begin{itemize} \item We often want to work with one line of a text file at a time \item the \texttt{istream} member function @getline()@ reads from a file and places it in a string or character array, without the ending newline. %\item @fgets()@ takes two parameters: the address of a % character array and the maximum number of characters to be % read: {\mode{\small}% \begin{semiverbatim}\small \V{std::cin.getline}( \meta{string or character array}, \meta{maximum length} ); \end{semiverbatim} } \item @getline()@ returns false if there is any error. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{\program{copy-lines-from-file.cpp}:} %[ #include #include #include int main( void ) { const int maxline = 100; char line[ maxline ]; std::ifstream fin( "abc.txt" ); if ( ! fin ) { std::cerr << "Cannot open file abc.txt\n"; exit( 1 ); } while ( fin.getline( line, maxline ) ) std::cout << line << '\n'; } %] \end{frame} \subsection{I/O of other data to/from Text Files} \label{sec:io-of-other-data-to-from-text-files} \begin{frame}[fragile] \frametitle{Reading other data from Text Files --- 1} \begin{itemize} \item We can write formatted text to text files just as we can to standard output with @std::cout@ \item \program{fileout.cpp} %[ #include #include int main( void ) { int num = 127; std::ofstream fout( "abc.txt" ); fout << num; std::cout << "Wrote '" << num << "' to abc.txt\n"; } %] \end{itemize} \end{frame} % \begin{frame}[fragile] % \frametitle{\program{fileout.cpp}} % %[ % #include % int main( void ) % { % int num; % FILE *fptr1; % fptr1 = fopen( "abc.txt", "w" ); % num = 127; % fprintf( fptr1, "\%d", num ); % fclose( fptr1 ); % } % %] % \end{frame} \begin{frame}[fragile] \frametitle{Reading other data from Text Files --- 2} \begin{itemize} \item We can read formatted text from text files just as we can from standard input with @std::cin@ \item \program{filein.cpp}: %[ #include #include #include int main( void ) { int num; std::ifstream fin( "abc.txt" ); if ( ! fin ) { std::cerr << "Cannot open abc.txt\n"; exit( 1 ); } fin >> num; std::cout << "we got '" << num << "' from abc.txt\n"; } %] \end{itemize} \end{frame} \section{Guidelines} \label{sec:guidelines} \subsection{Style Guidelines} \label{sec:style-guidelines} \begin{frame}[fragile] \frametitle{Program layout: rules of thumb} \begin{itemize} \item Use spaces after commas, around operators, \item Example: %[ printf( "%d", i ); %] not %[ printf("%d",i); %] and %[ x = x + 3; %] not %[ x=x+3; %] \item I suggest you put your @main()@ function last. \begin{itemize} \item avoids the need to put ``function prototypes'' that need unnecessary extra maintainance \end{itemize} \item Use modern books about C, not very old ones. \item Indent your program to make it easy to follow. \item Indent the body of loops and @if@ statements. \end{itemize} \end{frame} \subsection{Program Design} \label{sec:program-design} \begin{frame} \frametitle{Program design} \begin{itemize} \item ``Real'' programs need to be designed; they may be too complicated to hold in your head all at one time. \item Sitting at the keyboard and typing a program as you think it up may work for small programs, but bigger programs written this way will become very messy and expensive to maintain. \begin{itemize} \item The result is rather like a rough sketch to try out ideas. \item You may want to start again after the experience you get from this ``sketch'' \end{itemize} \item The greatest cost for a program is usually in maintaining it. \item Flowcharts: \begin{itemize} \item are okay for simple programs \item are good for representing complicated, unstructured looping and branching \item \textbf{But:} a flowchart can easily become more complicated than the program itself! \end{itemize} \end{itemize} \end{frame} \begin{frame} \frametitle{Pseudocode: a basic design tool} \begin{itemize} \item \alert{Pseudocode} is a more practical way to show how your program will work. \item Pseudocode is a mixture of: English and structured C programming statements, such as @if@, @while@, @do@. \item Pseudocode should be simpler and easier to understand than the final program source code \item Pseudocode should be written \alert{before} you type in your new program! \end{itemize} \end{frame} \begin{frame} \frametitle{Program design: top-down} \begin{itemize} \item Top-down design looks at the big picture first, forgetting the details. \item Write pseudocode including only these important, big steps, leaving out small steps at first. This is like your @main()@ function. \item Write more pseudocode for each of these big steps, giving more detail, but not the smallest details. These are written rather like function definitions. \item For each step, write out more pseudocode like more function definitions, until you have enough detail to begin writing your source code. \item Check your design carefully before you move on. \end{itemize} \end{frame} \subsection{Modules} \label{sec:modules} \begin{frame} \frametitle{Making an application from many modules} \begin{itemize} \item Most useful C or C++ programs are written in separate \alert{modules} \item Each module corresponds to: \begin{itemize} \item one \texttt{.c}, \texttt{.C}, \texttt{.cc}, \texttt{.cpp}, or \texttt{.cxx} file (lets call this the \alert{source file}), and \item one \texttt{.h}, \texttt{.H}, \texttt{.hh}, or \texttt{.hpp} file (we call this the \alert{header file}). \end{itemize} \item Each header file lists the publicly exported names: type definitions, global variables, and function prototypes \begin{itemize} \item Avoid defining variables or functions in header files \end{itemize} \item It makes this set of names as small as possible to \alert{reduce the interaction between modules} \item All non-public functions defined in the source files are defined with the keyword @static@ so that they cannot be linked to from other modules. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Modules --- silly example} \begin{block}{main.cpp:} \vspace*{-3ex}\par% %[ #include #include "calc.h" #include "main.h" int glob; int main( void ) { glob = 10; int sum = calc( 15 ); std::cout << "sum = " << sum << '\n'; } %] \end{block} \par\vspace*{-2ex}\par% \begin{block}{main.h:} \vspace*{-3ex}\par% %[ #ifndef MAIN_H #define MAIN_H extern int glob; #endif %] \end{block} \end{frame} \begin{frame}[fragile] \frametitle{Modules --- silly example (continued)} \begin{block}{calc.cpp:} %[ #include "main.h" #include "calc.h" int calc( int n ) { return glob + n; } %] \end{block} \begin{block}{calc.h:} %[ #ifndef CALC_H #define CALC_H extern int calc( int n ); #endif %] \end{block} \end{frame} \begin{frame}[fragile] \frametitle{\K{static} variables} \mode{% \renewcommand{\LGsize}{\scriptsize}% \small }% \begin{itemize} \item A variable defined with the keyword @static@ is visible only within its file, and does not conflict with a variable with the same name defined in another file \item the @static@ keyword can (and should) be used with functions that are to be used only within one file \item The @static@ keyword can be used inside functions and blocks \begin{itemize} \item It is initialised once, and its value remains even between function calls. See \program{static.cpp}: \end{itemize} \par\mode{\vspace*{-3ex}}\par% %[ #include void show_times_called( void ) { static int called = 0; std::cout << "called " << ++called << " times\n"; } int main( void ) { for ( int i = 0; i < 5; ++i ) show_times_called(); } %] \par\vspace*{-1ex}\par \item output of \linkto{static.cpp}: \mode{% \scriptsize }% \begin{verbatim} called 1 times called 2 times called 3 times called 4 times called 5 times \end{verbatim} \end{itemize} \end{frame} \section{Some Things to Read} \label{sec:things-to-read} \begin{frame}[allowframebreaks] \mode{\frametitle{Resources}}% \begin{thebibliography}{5} % None of these affects how cite appears, only how the bibitem appears. % \beamertemplatebookbibitems makes little pictures of books in bib. \beamertemplatebookbibitems % \beamertemplatearticlebibitems makes little pictures of text in bib. % \beamertemplatearticlebibitems % \beamertemplatetextbibitems uses [1], [2] or [optional] in bib. % \beamertemplatetextbibitems % \beamertemplatearrowbibitems make little arrows (like ordinary items) % \beamertemplatearrowbibitems \bibitem[K\&R]{K&R} Brian W. Kernighan and Dennis M. Ritchie. \newblock% \emph{The C Programming Language}. \newblock% Prentice Hall 1988. \bibitem{Lip1998} Stanley B. Lippman and Jos\'{e}e Lajoie and Barbara E. Moo. \newblock% \emph{C++ Primer, Fourth Edition}. \newblock% Addison-Wesley 2005. \bibitem{Str2004} Bjarne Stroustrup.% \newblock% \emph{The C++ Programming Language (Special 3rd Edition)}. \newblock% Addison-Wesley, 2004, ISBN 0201889544. \bibitem{AAM1998} Tom Adamson and James L. Antonakos and Kenneth C. Mansfield Jr. \newblock% \emph{Structured C for Engineering and Technology, Third Edition}. \newblock% Prentice Hall, 1998. \bibitem{Oua1993} Steve Oualline.% \newblock% \emph{Practical C Programming}.% \newblock% O'Reilly 1993. \bibitem{Dav1995} Paul Davies.% \newblock% \emph{The Indispensable Guide to C With Engineering Applications}. \newblock% Addison-Wesley 1995. \bibitem{Dei1994} H. M. Deitel and P. J. Deitel.% \newblock% \emph{C How to Program, Second Edition}.% \newblock% Prentice Hall 1994. \bibitem{Kas1989} Vincent Kassab.% \newblock% \emph{Technical C Programming}.% \newblock% Prentice Hall 1989. \beamertemplatearticlebibitems% \bibitem{Cli2006} Marshall Cline. \newblock% \emph{C++ FAQ LITE}. \newblock% \url{http://www.parashift.com/c++-faq-lite/} % \bibitem{GPL2} % GNU General Public License. % \newblock% % \url{http://www.gnu.org/copyleft/gpl.html} \bibitem{} Bjarne Stroustrup.% \newblock% \emph{A Tour of the Standard Library}. \newblock% Chapter 3 of \emph{The C++ Programming Language}. \newblock% \url{http://public.research.att.com/~bs/3rd_tour2.pdf} \end{thebibliography} \end{frame} \begin{frame} \frametitle{License covering this document} \label{sld:license} Copyright \copyright{} 2006 Nick Urbanik You can redistribute modified or unmodified copies of this document provided that this copyright notice and this permission notice are preserved on all copies under the terms of the GNU General Public License as published by the Free Software Foundation --- either version 2 of the License or (at your option) any later version. \end{frame} \end{document} \begin{frame} \frametitle{} \begin{itemize} \item \end{itemize} \end{frame}