% Generated by Sphinx.
\def\sphinxdocclass{report}
\documentclass[letterpaper,10pt,english]{sphinxmanual}
\usepackage[utf8]{inputenc}
\DeclareUnicodeCharacter{00A0}{\nobreakspace}
\usepackage{cmap}
\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage{times}
\usepackage[Bjarne]{fncychap}
\usepackage{longtable}
\usepackage{sphinx}
\usepackage{multirow}



\title{Introduction to Computer Science in C\#}
\date{27-January-2015 10:43:45}
\release{1.0}
\author{COMP 170 Contributors}
\newcommand{\sphinxlogo}{}
\renewcommand{\releasename}{Release}
\makeindex

\makeatletter
\def\PYG@reset{\let\PYG@it=\relax \let\PYG@bf=\relax%
    \let\PYG@ul=\relax \let\PYG@tc=\relax%
    \let\PYG@bc=\relax \let\PYG@ff=\relax}
\def\PYG@tok#1{\csname PYG@tok@#1\endcsname}
\def\PYG@toks#1+{\ifx\relax#1\empty\else%
    \PYG@tok{#1}\expandafter\PYG@toks\fi}
\def\PYG@do#1{\PYG@bc{\PYG@tc{\PYG@ul{%
    \PYG@it{\PYG@bf{\PYG@ff{#1}}}}}}}
\def\PYG#1#2{\PYG@reset\PYG@toks#1+\relax+\PYG@do{#2}}

\expandafter\def\csname PYG@tok@gd\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.63,0.00,0.00}{##1}}}
\expandafter\def\csname PYG@tok@gu\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.50,0.00,0.50}{##1}}}
\expandafter\def\csname PYG@tok@gt\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.27,0.87}{##1}}}
\expandafter\def\csname PYG@tok@gs\endcsname{\let\PYG@bf=\textbf}
\expandafter\def\csname PYG@tok@gr\endcsname{\def\PYG@tc##1{\textcolor[rgb]{1.00,0.00,0.00}{##1}}}
\expandafter\def\csname PYG@tok@cm\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
\expandafter\def\csname PYG@tok@vg\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@m\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@mh\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@cs\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}\def\PYG@bc##1{\setlength{\fboxsep}{0pt}\colorbox[rgb]{1.00,0.94,0.94}{\strut ##1}}}
\expandafter\def\csname PYG@tok@ge\endcsname{\let\PYG@it=\textit}
\expandafter\def\csname PYG@tok@vc\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@il\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@go\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.20,0.20,0.20}{##1}}}
\expandafter\def\csname PYG@tok@cp\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@gi\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.63,0.00}{##1}}}
\expandafter\def\csname PYG@tok@gh\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}}
\expandafter\def\csname PYG@tok@ni\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.84,0.33,0.22}{##1}}}
\expandafter\def\csname PYG@tok@nl\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.13,0.44}{##1}}}
\expandafter\def\csname PYG@tok@nn\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.05,0.52,0.71}{##1}}}
\expandafter\def\csname PYG@tok@no\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.38,0.68,0.84}{##1}}}
\expandafter\def\csname PYG@tok@na\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@nb\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@nc\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.05,0.52,0.71}{##1}}}
\expandafter\def\csname PYG@tok@nd\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.33,0.33,0.33}{##1}}}
\expandafter\def\csname PYG@tok@ne\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@nf\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.02,0.16,0.49}{##1}}}
\expandafter\def\csname PYG@tok@si\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.44,0.63,0.82}{##1}}}
\expandafter\def\csname PYG@tok@s2\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@vi\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@nt\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.02,0.16,0.45}{##1}}}
\expandafter\def\csname PYG@tok@nv\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@s1\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@gp\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.78,0.36,0.04}{##1}}}
\expandafter\def\csname PYG@tok@sh\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@ow\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@sx\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.78,0.36,0.04}{##1}}}
\expandafter\def\csname PYG@tok@bp\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@c1\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
\expandafter\def\csname PYG@tok@kc\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@c\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
\expandafter\def\csname PYG@tok@mf\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@err\endcsname{\def\PYG@bc##1{\setlength{\fboxsep}{0pt}\fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}}
\expandafter\def\csname PYG@tok@mb\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@ss\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.32,0.47,0.09}{##1}}}
\expandafter\def\csname PYG@tok@sr\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.14,0.33,0.53}{##1}}}
\expandafter\def\csname PYG@tok@mo\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@kd\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@mi\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@kn\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@o\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\expandafter\def\csname PYG@tok@kr\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@s\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@kp\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@w\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.73,0.73}{##1}}}
\expandafter\def\csname PYG@tok@kt\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.56,0.13,0.00}{##1}}}
\expandafter\def\csname PYG@tok@sc\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@sb\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@k\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@se\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@sd\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}

\def\PYGZbs{\char`\\}
\def\PYGZus{\char`\_}
\def\PYGZob{\char`\{}
\def\PYGZcb{\char`\}}
\def\PYGZca{\char`\^}
\def\PYGZam{\char`\&}
\def\PYGZlt{\char`\<}
\def\PYGZgt{\char`\>}
\def\PYGZsh{\char`\#}
\def\PYGZpc{\char`\%}
\def\PYGZdl{\char`\$}
\def\PYGZhy{\char`\-}
\def\PYGZsq{\char`\'}
\def\PYGZdq{\char`\"}
\def\PYGZti{\char`\~}
% for compatibility with earlier versions
\def\PYGZat{@}
\def\PYGZlb{[}
\def\PYGZrb{]}
\makeatother

\renewcommand\PYGZsq{\textquotesingle}

\begin{document}

\maketitle
\tableofcontents
\phantomsection\label{index::doc}



\chapter{Context}
\label{context:introduction-to-computer-science-in-c}\label{context::doc}\label{context:context}

\section{Motivation for This Book}
\label{context_motivation:motivation-for-this-book}\label{context_motivation::doc}
This is really a preface, but the otherwise very capable Sphinx publishing environment
that we use is not set up for a separate preface.


\subsection{Pedagogy}
\label{context_motivation:pedagogy}
Our first aim is to provide a good introduction and
conceptual framework for more computer science, not an encyclopedic coverage of C\#.
C\# will not be most students' only language, or necessarily the most used.
Designing and creating algorithms in a particular language is an important skill,
requiring ongoing effort, so most of the text is still centered on C\#.

C\# is an object-oriented language.  There is the ongoing argument about when to introduce
details of object-oriented programming.  We last taught Java, objects first.  Students
dutifully followed our lead.  Later, we saw quick programs that students wanted
to write for themselves,
that were layered with totally unnecessary and distracting instances of objects.

We have seen less problem with the opposite order, which we use:
start off with more procedural programming, then introduce the use of
instances of existing classes of objects, and then move to designing
classes with instance variables, constructors, and instance methods,
and see where they are truly useful.  If you prefer,
after the chapter on functions you can read the first couple
of sections in {\hyperref[classes:classes]{\emph{Classes and Object-Oriented Programming}}}, that
cover defining your own simple objects.

We tend to introduce examples first, and then the general syntax,
and then more examples and exercises. Later examples
on a subject are sometimes essentially
links to documented code that is both directly visible on the web and
in the separate download of all of the example source code.

There are review questions at the end of most chapters.
The review questions may seem to be in a strange order: Often we invite students
to consider a general overarching theme in an early question.  In case that
was too much to bite off, later questions often explicitly address a specific
point that would have been an implicit part of an earlier general question.
Sometimes a later more pointed question even gives an answer to part of
an earlier question.

Labs are intended as early practice on a subject, with generally small
bits requested at a time.  They are usually included in the main body
of the book soon after the needed
background is introduced.
There are also larger assignments as some of the appendix sections.


\subsection{C\# and Mono}
\label{context_motivation:c-and-mono}
We have taught introductory programming for many years,
through a progression of programming languages.  Our last language was Java,
still the language of the AP test, which drives so many introductory texts.

We had C\# in mind:  It is a more modern language.  Its designers got to reflect
on the glitches with Java, and address them effectively.

The key problem with C\# used to be that it was totally a Microsoft language for Windows.
Many of our students have their own machines: many are OS-X machines from Apple;
some are Linux.
We did not want to cut those students off.
Nor did we want to limit students to thinking of
a computer as a Windows machine.  Meanwhile the open source implementation
of C\#, Mono, has been maturing, along with its tool chains.

While many open-source tools have hackers jumping in to eliminate bugs, and maybe
providing enough documentation for a professional, documentation for a
beginner is often lacking.  This book contributes there, partly in the
documentation for Mono's lovely interactive environment csharp, and also
for the integrated development environment, Xamarin Studio.
We show beginners how to start using the Xamarin Studio environment,
with its large array of features (not all needed by the
beginner), and introduce more features as needed.

We aim to end up with a book that provides a solid conceptual framework
for beginning computer scientists in the context of
the clean, well-established modern language,  C\#,
using multi-platform free and open-source
tools, with clear documentation.

We hope that you find this to be a winning combination.


\section{Resources Online}
\label{context_intro:resources-online}\label{context_intro::doc}
This book is designed for Comp 170 at Loyola University, Chicago.
The materials are available to all on the web.
Here are some important web links:

\index{book examples download}\index{examples download}\index{source download}\begin{itemize}
\item {} 
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/archive/master.zip}{The course example file,}
is the \emph{essential resource} to download and unzip onto your machine.
The zip file and the folder it unzips to have a long name,
introcs-csharp-master-examples.
We suggest you \emph{rename the unzipped folder}
\code{examples} to match later references.

Computer programs are designed to run on a computer and solve problems.
Though the initial problems will be tiny and often silly,
they will serve as learning tools to prepare for substantive problems.

\item {} 
\href{http://introcs.cs.luc.edu}{http://introcs.cs.luc.edu} is an online text version for your web browser.
See also {\hyperref[context_download:alt-formats]{\emph{Downloading Text, Source Code, and Videos}}} for pdf and epub versions.
Except on very geometrically oriented topics,
\emph{text-oriented learners may be happiest just reading the book}
in one of these formats.

\item {} 
\href{https://luc.box.com/CSharpVideos}{https://luc.box.com/CSharpVideos} is a box.com
folder containing all the videos.
The numbers
at the beginning of the titles are chapter and section numbers from the text.
These make it easy to sequence the videos, even though there is not an
automatic \emph{playlist}.
The listing in box.com takes up several pages.
These box.com videos may be
\begin{itemize}
\item {} 
streamed, including at full size (though generally after an initial delay),

\item {} 
downloaded individually or

\item {} 
the whole gigabyte folder can be downloaded at once to play later on your machine.
(This is a choice on the menu under the page's Folder Options.)

\end{itemize}

There is a mixture of new high-def videos and older
lower resolution
800x600 pixel videos.   In that folder see 00README.html,
\href{https://luc.box.com/s/2lqak4pbsdcyw08ds3ia}{https://luc.box.com/s/2lqak4pbsdcyw08ds3ia},
for a description of the differences
between the old videos and the latest update of the online book.

For those who learn best with
spoken words combined with written words, the videos should be a good
start.  Even if you use a video for a section, you are encouraged to
\emph{review the written text afterward}.
Then be aware of the written version for quick reference.
The written text may include extra details and exercises, and it
will have the latest revisions.

\end{itemize}

In various formats, be aware of these helpful features:
\begin{itemize}
\item {} 
We have picked out particularly important words, phrases, and symbols,
and put them in our
index, which is accessible from the banner
of each web page.  The banner stays visible if the window is big enough,
and if the window is smaller, the baner only appears at the beginning
of the page with a dropdown menu for most of the options.

\item {} 
In a web version on our website, you can use the
Search option to
look for words, in general.  The search link is also accessible from
the web page banner.  This does \emph{not} work on a downloaded
local html copy.

\item {} 
The web version and pdf versions display mathematical formulas
prettily.  If you use the local html version when not connected to the
internet, you see only the LaTex encoded source for formulas.
While offline reading sections
with math formulas, we suggest using the pdf version.

\item {} 
We start with a brief table of contents for the whole book.
\emph{In the web versions}
you can get the most detailed table of contents for a single chapter by
clicking on a chapter title in the main table of contents or a
chapter title in the Site drop-down menu in the banner.

\item {} 
The web version shifts the behavior of the top banner depending  on
screen resolution, so it adapts for anything from large monitors
to small mobile devices. With a wide screen the banner stays at the
top of your screen, and shows all the standard internal links and
drop-down menus.  On a narrower screen the banner is only at the top
of each webpage, and scrolls off the screen; the only direct
link is to the main table of contents, while the rest of the links
of the wide version can be accessed via the icon at the right side of
the banner.

\end{itemize}

Here are further links that may be useful in our repository:
\begin{itemize}
\item {} 
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp/}{https://github.com/LoyolaChicagoBooks/introcs-csharp/}
is the home page for the repository of all the sources for the book.
To read this book, you do \emph{not} need to go to that URL, but if you do, the home page
gives you an idea of what \emph{updates have been made recently} to the book or
accompanying examples. Since improvements are made on an ongoing basis,
the notes about recent changes may be useful to you.

The multiple production versions are generated largely by
\href{http://sphinx.pocoo.org/}{Sphinx} software from the common
set of sources in the repository.  The sources are
largely plain text files.

\item {} 
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/}{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/}
is another repository containing the \emph{latest versions}
of the source code files.
You can quickly browse and view individual files under the Source tab.
Example file links throughout this text refer to these repository files.

\end{itemize}

\index{book alternate formats}

\section{Downloading Text, Source Code, and Videos}
\label{context_download:alt-formats}\label{context_download:downloading-text-source-code-and-videos}\label{context_download:index-0}\label{context_download::doc}
Here are tables that summarize the links already described more fully in the
last section, plus several further versions.  The book has a primary site and a mirror,
in case the first is down.
The examples and videos are not mirrored.


\subsection{Example Source Code and Videos}
\label{context_download:example-source-code-and-videos}

\begin{threeparttable}
\capstart\caption{Source Code and Videos}

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Format
} & \textsf{\relax 
URL
}\\
\hline
C\# Examples (as pages)
 & 
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples}{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples}
\\
\hline
C\# Examples (as ZIP)
 & 
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/archive/master.zip}{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/archive/master.zip}
\\
\hline
Videos
 & 
\href{https://luc.box.com/CSharpVideos}{https://luc.box.com/CSharpVideos}
\\
\hline\end{tabulary}

\end{threeparttable}



\subsection{Primary Book Site (cs.luc.edu)}
\label{context_download:primary-book-site-cs-luc-edu}

\begin{threeparttable}
\capstart\caption{Available Book Formats (Primary Site)}

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Format
} & \textsf{\relax 
URL
}\\
\hline
Web Pages
 & 
\href{http://introcs.cs.luc.edu/html/}{http://introcs.cs.luc.edu/html/}
\\
\hline
Web Pages (offline ZIP)
 & 
\href{http://introcs.cs.luc.edu/dist/html.zip}{http://introcs.cs.luc.edu/dist/html.zip}
\\
\hline
PDF
 & 
\href{http://introcs.cs.luc.edu/latex/comp170.pdf}{http://introcs.cs.luc.edu/latex/comp170.pdf}
\\
\hline
ePub (Experimental)
 & 
\href{http://introcs.cs.luc.edu/epub/comp170.epub}{http://introcs.cs.luc.edu/epub/comp170.epub}
\\
\hline\end{tabulary}

\end{threeparttable}



\subsection{Mirror Book Site (courseclouds.com)}
\label{context_download:mirror-book-site-courseclouds-com}

\begin{threeparttable}
\capstart\caption{Available Book Formats (Mirror Site)}

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Format
} & \textsf{\relax 
URL
}\\
\hline
Web Pages
 & 
\href{http://introcs.cs.courseclouds.com/html/}{http://introcs.cs.courseclouds.com/html/}
\\
\hline
Web Pages (offline ZIP)
 & 
\href{http://introcs.cs.courseclouds.com/dist/html.zip}{http://introcs.cs.courseclouds.com/dist/html.zip}
\\
\hline
PDF
 & 
\href{http://introcs.cs.courseclouds.com/latex/comp170.pdf}{http://introcs.cs.courseclouds.com/latex/comp170.pdf}
\\
\hline
ePub (Experimental)
 & 
\href{http://introcs.cs.courseclouds.com/epub/comp170.epub}{http://introcs.cs.courseclouds.com/epub/comp170.epub}
\\
\hline\end{tabulary}

\end{threeparttable}


\index{computer science}

\section{Computer Science, Broadly}
\label{context_computerscience:computer-science-broadly}\label{context_computerscience:index-0}\label{context_computerscience:computer-science}\label{context_computerscience::doc}
We intend this book as an introduction to computer science, with a focus on
creating problem solutions in the C\# programming language.
We should not jump in too quickly.  You can get lost in our details and
miss an idea of the much larger breadth of computer science.

\index{information processing}

\subsection{Information Processing}
\label{context_computerscience:information-processing}\label{context_computerscience:index-1}
Computer Science is the study and practice of information processing.
This can take many forms.  Many forms appear in electronic computers,
but information processing takes place in many other contexts, too:

In the early days of electronic computers,
the information was largely numerical, calculating mathematical functions.

Later analyzing textual information
has become much more important, for instance:
What can you tell about the severity of the current flu outbreak by
analyzing the phrasing in Google searches?

Images are analyzed:  What can a satellite image tell you about the
distribution of drought?

Sounds:  how do you convert verbal speech accurately
into written sentences?

DNA holds information that our bodies process into proteins.

Our brain chemicals and
electronic signals process information.  There is  rich interplay
between cognitive scientists and computer scientists modeling
problem solving in the brain with \emph{neural nets} on a computer,
sometimes to better understand brains and
sometimes to
better solve problems on an electronic computer.

Economic systems are becoming better understood in terms of the
flow of information.

The \emph{computer} doing computations and processing can be a familiar \emph{electronic}
computer, but it can be genes or brain chemicals,
or a whole society as its economy adapts.

\index{algorithms}

\subsection{Algorithms}
\label{context_computerscience:algorithms}\label{context_computerscience:index-2}
Algorithms are at the heart of traditional problem solving .  An \emph{algorithm}
is a clearly expressed sequence of steps leading to a result in a
finite amount of time.

A recipe for baking a pound cake is an algorithm.

Such an algorithm has useful concepts that we use later in computer
programming:
\begin{itemize}
\item {} 
A named sub-problem: your recipe may include the instruction
``Beat 4 eggs.''  The recipe probably says no more about it, but this is
\emph{shorthand}, a name for a simpler sequence of steps, an
algorithm like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Beating Any Number of Eggs
\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}
1. Get a bowl large enough for the eggs.
2. For each egg:
   a. Crack its shell on the edge of the bowl.
   b. Add the contents of the shell to the bowl.
3. Mix the eggs with a whisk.
4. Continue with step 3 until you cannot
   distinguish the white and yolks.
\end{Verbatim}

\item {} 
Parameters: The egg beating instructions work, in general, for any number
of eggs.  To use these instructions for a \emph{particular} pound cake,
you must supply a specific value to use to make the general instructions
become clear.  The pound cake recipe that uses
the egg beating instructions, uses the number \textbf{4} as the actual data.

\item {} 
Repetition: The instructions for cracking an egg are not \emph{written} repeatedly,
for every egg.  The instruction is stated once, and we are told how
long to go on: for each egg in step 2.  Step 4 says
when to stop repeating step 3.

\end{itemize}

\index{data representation}\index{Jaquard loom}\index{Pascaline}

\subsection{Data Representation}
\label{context_computerscience:id1}\label{context_computerscience:data-representation}\label{context_computerscience:index-3}
A recipe represents data by words that get processed by a human reader.
Machines have used different representations.  One of the earliest
adding machines, the Pascaline,
\href{http://en.wikipedia.org/wiki/Pascal's\_calculator}{http://en.wikipedia.org/wiki/Pascal's\_calculator},
represented numbers by the angle of
rotation of interlocked gears.
An abacus uses the positions of groups of sliding beads to represent digits.
The Jacquard loom,
\href{http://en.wikipedia.org/wiki/Jacquard\_weaving}{http://en.wikipedia.org/wiki/Jacquard\_weaving},
used cards with each row of holes punched in them
indicating which warp threads are raised and which lowered when a cross
thread is woven in.

\index{bit}\index{byte}\index{binary number system}\index{base 2}
In modern electronic computers the most basic bit of data
(actually called a \emph{bit}) is held by two-state switches, often
in the form of a higher voltage vs. a grounded state.  The symbolic representation
is often 0 vs. 1.  This symbolism comes from the representation of integers
in \emph{binary notation}, also called \emph{base 2}:
It is a place value system, but where each place
in a numeral is a 0 or a 1 and represents a power of two, so 1101 in binary
can be viewed in our decimal system as
\((1)2^3+(1)2^2+(0)2^1+(1)2^0=8+4+0+1=13\).

Computer hardware can only handle a limited number of bits at a time,
and memory space is limited, so usually integers are stored in a limited
space, like 8, 16, 32 or 64 bits.
We illustrate with the smallest, 8 bits, called a \emph{byte}.  Since
each bit has two possible states, 8 bits have \(2^8=256\) possible states.
Directly considered as binary numerals, they represent 0 through
\(2^8-1=255\).

We also want to represent negative numbers, and have about half of the available
codes for them.  An 8-bit signed integer in \emph{twos complement} notation
represents 0 through \(2^7-1\)
just as the unsigned numbers do.  These are all the 8-bit codes with a leading 0.
A negative number \(n\) in the range \(-2^7=-128\) through -1,
is represented by what would be
the unsigned notation for \(n+2^8\).  These will be all the
8-bit codes with a leading 1.
For example -3 is represented like unsigned 256 - 3 = 253: 11111101 in binary.

\index{mantissa and exponent}
Limited precision approximation of real numbers are stored in something like
scientific notation, except in binary,  roughly \(\pm(m)2^e\),
with a sign, mantissa m and exponent e. Both e and m have
fixed numbers of bits, so the limited options for the
mantissa restricts the \emph{precision} of the numbers, and the limited options
for the exponent restricts the \emph{range}. Data on these limits for
different sized numeric codes is in {\hyperref[data_types-and-conversions:value-types]{\emph{Value Types and Conversions}}}.

Once you have numbers, all sorts of other kinds of data can be encoded:
Characters
like on your keyboard each have a numerical code associated with each one.  For
example the unicode for the letter A is 65.  Images are often
represented as a sequence of colored pixels.  Since the human eye is only
sensitive to three specific colors, red, green, and blue,
a pixel is represented by a numerical intensity
for each of the three colors.

\index{instruction representation}\index{machine language}\index{assembler}\index{interpreter}\index{architecture}

\subsection{Instruction Representation}
\label{context_computerscience:index-6}\label{context_computerscience:instruction-representation}
Besides the data, instructions need a representation too, and an agent to
interpret them.  In the earliest electronic computers the two-state switches
were relays or later vacuum tubes, and the machine was \emph{manually rewired} when a
new set of instructions/program was needed.  It was a great advance in the 1940's
when the instructions also became symbolic,
represented by binary codes that the computer
could recognize and act on,
\href{http://en.wikipedia.org/wiki/Von\_Neumann\_architecture}{http://en.wikipedia.org/wiki/Von\_Neumann\_architecture}.
This code is called \emph{machine language}.
With machine language the instructions became a form of data that could be stored
in computer memory.  We distinguish the \emph{hardware} on which programs are run
from the stored programs, the \emph{software}.  The \emph{architecture} of the
hardware determines the form and capacities of the machine language, so
machines with a different hardware architecture are likely to have distinct
machine languages.

Biologists have a fair idea of how protein sequence data is encoded in DNA,
but they are still working on how the DNA instructions are encoded
controlling which proteins should be made when.

In this book we will not be writing instructions shown as
sequences of 0's and 1's!
Some of the earliest programs were to help programmers
work with more human-friendly tools, and an early one
was an \emph{assembler}, a program that took easier to understand instructions
and automatically translated them into machine language.  An example
assembler instruction would be like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
MOV 13, X
\end{Verbatim}

to move the value 13 to a storage location identified by the name X.

Machine instructions are very elementary, so programming
was still tedious, and code could not be reused on a
machine with a different architecture.

The next big step past assembler was the advent of
\emph{high level} languages, with instructions more like normal mathematical or
English expressions.  Examples are Fortran (1954) and Cobol (1959).
A Fortran statement for calculating a slope like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
S=(Y\PYGZhy{}V)/(X\PYGZhy{}U)
\end{Verbatim}

might require seven or or more machine code instructions.

To use a Fortran program required three steps: write it (onto punch cards
originally), compile it to machine code, and execute the machine code.
The compiler would still be architecture specific, but the compiler for
an architecture would only need to be written once, and then any number of
programs could be compiled and run.

A later variant for executing a high-level language is
an \emph{interpreter}.  An interpreter translates the high-level language
into machine code, and immediately executes it, not storing the
machine code for later
use, so every time a statement in the code is executed again,
the translation needs to be redone.  Interpreters are also
machine-specific.

Some later languages like Java and C\# use a hybrid approach: A compiler,
that can run on any machine, does most of the work by
translating the high-level language program
into a low-level \emph{virtual machine}
language called a \emph{bytecode}.  This is not the machine language for any real machine,
but the bytecode is simple
enough that writing an interpreter for it is very easy.
Again the interpreter for the bytecode must be machine-specific.
In this approach:

Program source =\textgreater{} COMPILER =\textgreater{} bytecode =\textgreater{} INTERPRETER =\textgreater{} execution

\index{program development cycle}

\subsection{Program Development Cycle}
\label{context_computerscience:index-7}\label{context_computerscience:program-development-cycle}
The easiest way to check your understanding of small new pieces of C\# is to write
a highly specified small program that will be sure to test the new ideas.
That is totally unlike the real world of programming.  Here is a more realistic
sequence:
\begin{enumerate}
\item {} 
Clients have a problem that they want solved.

\item {} 
They connect with software developers.

\item {} 
The clients discuss the needs of their users.

\item {} 
The software developers work with them to make sure they
understand the desired deliverables, and work through the
design decisions and their tradeoffs.

\item {} 
Software developers start building and testing and showing off the
core pieces of the software, and build on out.

\item {} 
The clients may not have a full idea of what they want and the
software developers may not have a full idea of what is feasible, and
seeing the latest version leads both sides to have a clearer vision.
Then the previous process steps are repeated, iteratively refining
the product.

\item {} 
After a production version is out, there may be later versions and error
fixes, again cycling back to the earlier steps.

\end{enumerate}

Note that very important parts of this process are not centered on coding,
but on communicating clearly with a possibly non-technical client.
Communication skills are critical.

\index{computer science!key concepts}

\subsection{Key Computer Science Areas}
\label{context_computerscience:key-computer-science-areas}\label{context_computerscience:index-8}
Most of the introduction so far has been about key concepts that underlie
basic programming. Most of the parts so far about electronic computers
could have been written decades ago.  Much has emerged since then,
\begin{itemize}
\item {} 
the Internet

\item {} 
the development of economical multi-processor machines
distributing computation into many parallel parts

\item {} 
the massive explosion of the amount of information to be stored
from diverse parts of life

\item {} 
the coming \emph{Internet of things}, where sensors are coming to all
sorts of previously ``dumb'' parts of the world, that now can be tracked
by GPS and reacted to in real time.

\item {} 
Computers are now embedded in all sorts of devices:  toasters, thermostats,....
Automobiles of today have more computing power embedded in various devices
than early mainframe computers.

\end{itemize}

We conclude with a brief discussion of some of the other organizing
principles of
computer science.
\begin{description}
\item[{Communication}] \leavevmode
As the world is criss-crossed with media transmitting gigabytes of
data per second, how do we keep the communication reliable and secure?

\item[{Coordination}] \leavevmode
With multiple networked entities, how do we
enhance cooperation, so more work is done in parallel?

\item[{Recollection}] \leavevmode
As the amount of data stored skyrockets, how do we effectively store
and efficiently retrieve information?

\item[{Evaluation}] \leavevmode
How do we predict the performance and plan the necessary capacity
for computer systems?  The most spectacular recent public failure
in this area was the rollout of the federal Affordable Care
website.

\item[{Design}] \leavevmode
How do we design better/faster/cheaper/reliable hardware and software systems?
What new programming languages will be more expressive, lead to fewer
time-consuming errors, or be useful in proving that a major program never
makes a mistake?  Errors in programs controlling machines delivering
radiation for cancer treatment have had errors and led to patient death.

Hardware changes can be evolutionary or revolutionary:
Instead of electric circuits can we use light, quantum particles, DNA...?

\item[{Computation and Automation}] \leavevmode
What can we compute and automate?  Some useful
sounding problems have been proven to be unsolvable.  What are the limits?

\end{description}

\index{Denning - Peter}\index{Miles - Rob}\index{C\# Yellow Book}
A detailed discussion of these principles and the breadth of
importance of computer science can be found at
\href{http://denninginstitute.com/pjd/GP/GP-site/welcome.html}{http://denninginstitute.com/pjd/GP/GP-site/welcome.html}.

For an alternate general introduction to programming and the context of C\# in particular,
there is another free online source,
Rob Miles'
C\# Yellow Book, available at
\href{http://www.csharpcourse.com}{http://www.csharpcourse.com}.
Note that it is written specifically for Microsoft Windows use, using
Visual Studio software development environment, which works only on Windows machines,
and costs a lot if you are not a student.

The {\hyperref[data_lab-edit-compile-run:lab-edit-compile-run]{\emph{Lab: Editing, Compiling, and Running with Xamarin Studio}}} will introduce an alternative to the
Microsoft environment: Xamarin Studio and Mono, which are free,
open-source software projects that make C\# available for multiple platforms:
Windows, Mac, or Linux machines.  With a substantial fraction of students having their own
machine that does  \emph{not} run Windows, this flexibility is important.


\section{Chapter Review Questions}
\label{context_reviewcontext:chapter-review-questions}\label{context_reviewcontext::doc}\begin{enumerate}
\item {} 
What is an algorithm?

\item {} 
Are computers the only things that can perform the operations
in an algorithm?

\item {} 
What are important types of information?

\item {} 
What are very distinct important ways that information is stored?

\item {} 
What is a \emph{bit}?

\item {} 
Look at our brief mention of a Jaquard loom.
In a Jacquard loom, how is a single bit of information stored?
What two choices does it represent?

\item {} 
Does a computer generally execute a C\# program directly?
Briefly, what transformation happens first?

\item {} 
Is coding the only thing important in developing a real-world
application?  What are other important parts of the process?

\item {} 
Is computer science all about writing computer programs?  What are
some important large areas of concern in computer science?

\end{enumerate}


\chapter{C\# Data and Operations}
\label{data::doc}\label{data:c-data-and-operations}
\index{introduction}

\section{A Sample Scala Program}
\label{data_sampleprogram:a-sample-scala-program}\label{data_sampleprogram:index-0}\label{data_sampleprogram::doc}\label{data_sampleprogram:sample-program}
As a start let us consider a ridiculously simple problem and a program to solve
it. Suppose you paint the walls of rooms in one color and the ceiling in
another, and you want to calculate the size of the areas to cover with paint.
For simplicity ignore doors. What data do you need to start with? Clearly the
dimensions of the room. Suppose we consider modern houses where the height of
the room is predictably 8 feet, so the new starting data is just the length and
width of the room.

You need to:
\begin{enumerate}
\item {} 
Obtain the length and width from the user.

\item {} 
Calculate the wall area and ceiling area.

\item {} 
Let the user know the results.

\end{enumerate}

This is a very simple programming pattern: data in, calculate results, output
results. In this case the calculations in the middle are very easy.

In the examples that you should have downloaded is a first simple program,
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/painting/painting.scala}{painting/painting.scala}.

Here is what it looks like when it runs, with the user typing the 20.5 and the
10:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Calculation of Room Paint Requirements
Enter room length: 20.5
Enter room width: 10
The wall area is 488.0 square feet.
The ceiling area is 205.0 square feet.
\end{Verbatim}

This is not very exciting, but it is a simple place to start seeing basic
program features. We will refer back to this sample run while discussing the
program. Here is the text of the program:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{c+c1}{// This version is one where every Scala variable (val) }
\PYG{c+c1}{// is declared with an explicit data type.}

\PYG{k+kt}{object} \PYG{n}{Painting} \PYG{p}{\PYGZob{}}
  \PYG{n}{def} \PYG{n+nf}{main}\PYG{p}{(}\PYG{n}{args}\PYG{p}{:} \PYG{n}{Array}\PYG{p}{[}\PYG{n}{String}\PYG{p}{]}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{println}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Hello, world!\PYGZdq{}}\PYG{p}{)}
    \PYG{n}{val} \PYG{n}{HEIGHT} \PYG{p}{:} \PYG{n}{Double} \PYG{p}{=} \PYG{l+m}{8.0}

    \PYG{n}{println}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Calculation of Room Paint Requirements\PYGZdq{}}\PYG{p}{)}
    \PYG{n}{println}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter room length: \PYGZdq{}}\PYG{p}{)}
    \PYG{n}{val} \PYG{n}{lengthString} \PYG{p}{:} \PYG{n}{String} \PYG{p}{=} \PYG{n}{readLine}\PYG{p}{(}\PYG{p}{)}
    \PYG{n}{val} \PYG{n}{length} \PYG{p}{:} \PYG{n}{Double} \PYG{p}{=} \PYG{n}{lengthString}\PYG{p}{.}\PYG{n}{toDouble}
    \PYG{n}{println}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter room width: \PYGZdq{}}\PYG{p}{)}
    \PYG{n}{val} \PYG{n}{widthString} \PYG{p}{:} \PYG{n}{String} \PYG{p}{=} \PYG{n}{readLine}\PYG{p}{(}\PYG{p}{)}
    \PYG{n}{val} \PYG{n}{width} \PYG{p}{:} \PYG{n}{Double} \PYG{p}{=} \PYG{n}{widthString}\PYG{p}{.}\PYG{n}{toDouble}

    \PYG{c+c1}{// ignore doors}
    \PYG{n}{val} \PYG{n}{wallArea} \PYG{p}{:} \PYG{n}{Double} \PYG{p}{=} \PYG{l+m}{2} \PYG{p}{*} \PYG{p}{(}\PYG{n}{length} \PYG{p}{+} \PYG{n}{width}\PYG{p}{)} \PYG{p}{*} \PYG{n}{HEIGHT}

    \PYG{n}{val} \PYG{n}{ceilingArea} \PYG{p}{:} \PYG{n}{Double} \PYG{p}{=} \PYG{n}{length} \PYG{p}{*} \PYG{n}{width}

    \PYG{n}{println}\PYG{p}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}The wall area is \PYGZdl{}wallArea square feet.\PYGZdq{}}\PYG{p}{)}
    \PYG{n}{println}\PYG{p}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}The ceiling area is \PYGZdl{}ceilingArea square feet.\PYGZdq{}}\PYG{p}{)}
  \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This section gives an overview of a working program, even if all the
explanations do not make total sense yet.  This is a first introduction of
concepts and syntax that gets fully explained in further sections.

Do not worry if you not totally understand the explanations! Try to get the
gist now and the details later.

The different colors are used in modern program editors to emphasize the
different uses of the parts of the program.

We give a line by line explanation:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// This version is one where every Scala variable (val) }
\end{Verbatim}

A basic unit in Scala is an \emph{object}. Our code sits inside an object. Each
class has a \emph{heading} with \code{object} followed by a name. This class is
\code{Painting}. After the heading comes a \emph{body} delimited by braces. The opening
brace \code{\{} in the first line, is matched by the closing brace \code{\}} on the
last line of the program.

Lines 3, 9, and 12 are blank. This is merely for the human reader to separate
sections visually. The computer ignores them.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// is declared with an explicit data type.}
\end{Verbatim}

A class is broken up with chunks called \emph{functions} or \emph{methods}. Functions are
a discrete set of instructions that can be repeated throughout the program.
Each has a \emph{heading} started with \code{def} and is followed by the name of the
function, its \emph{arguments} surrounded by parentheses, and its \emph{return type}
preceeded by a colon. Arguments are passed into the function to change its
behavior, in this example there is only one argument named \code{args}. The return
type of the method \code{main} is a \code{Unit}, which will be described later in the
book.

Every program must start running somewhere. In Scala that is at a function with
name \code{main}, so our program starts running here. This syntax for this
function needs to start just like here, with \code{main(args: Array{[}String{]})}.

After the function heading comes a \emph{body}. Like with a class, a function body
is delimited by braces. The opening brace here is matched by the closing
brace on the second to last line of the program.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\end{Verbatim}

To refer to data in a program we use names called \emph{variables}, and they can be
defined by using the keywords \code{val} or \code{var}. Variables defined by \code{val}
can not be changed later in the program, where as \code{var} allows changes to be
made to the variable. This line says that the variable \code{height} contains the
value \code{8}.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{object} \PYG{n}{Painting} \PYG{p}{\PYGZob{}}
  \PYG{n}{def} \PYG{n+nf}{main}\PYG{p}{(}\PYG{n}{args}\PYG{p}{:} \PYG{n}{Array}\PYG{p}{[}\PYG{n}{String}\PYG{p}{]}\PYG{p}{)} \PYG{p}{\PYGZob{}}
\end{Verbatim}

Another example of a function is \code{println}, which has been defined for us
already. \code{println} accepts a \emph{string} argument and displays it in the
terminal. While you are used to a parameter for a function in math being a
number, functions in Scala are much more general. A function can be defined
with any type of parameters. Here the parameter is a string, \code{"Calculation of
Room Paint Requirements"}, delimited by the quotes at either end. \code{println}
has as sister method called \code{print}, which behaves exactly the same except it
will not start printing to the next line. This allows user input to be on the
same line as printed output.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
    \PYG{n}{val} \PYG{n}{HEIGHT} \PYG{p}{:} \PYG{n}{Double} \PYG{p}{=} \PYG{l+m}{8.0}
\end{Verbatim}

Here is where the program takes in the information requested from the user.
Its action is actually right to left: \code{readDouble} is another function
available in Scala that reads a line typed in by the user on the keyboard. It
returns a \code{Double}, which is a variable datatype that holds a real number (an
integer with a decimal value). In the sample run, on the same line as the
prompt string (because of the previous \code{print}, not \code{println}), the user
types \code{20.5} and the Enter or Return key.

In the sample run, the value produced by the \code{readDouble} function is these
four characters \code{20.5}. The returned value is then assigned to the variable
\code{length}. The \code{=} indicates an \emph{assignment statement}. It is an
\emph{assignment} of the value on the right of the equal sign to be the current
value of the variable on the left of the equal sign.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
    \PYG{n}{println}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Calculation of Room Paint Requirements\PYGZdq{}}\PYG{p}{)}
\end{Verbatim}

These lines are analogous to the previous three lines: give a prompt for the
user, get the user response, and assign to a variable (\code{width} in this case).
In the sample run the variable \code{width} is assigned the value 10.

\index{comment}\index{// comment}
At this point we have all the data we need from the user.  The next part is
the brief calculations of results:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
    \PYG{n}{val} \PYG{n}{lengthString} \PYG{p}{:} \PYG{n}{String} \PYG{p}{=} \PYG{n}{readLine}\PYG{p}{(}\PYG{p}{)}
    \PYG{n}{val} \PYG{n}{length} \PYG{p}{:} \PYG{n}{Double} \PYG{p}{=} \PYG{n}{lengthString}\PYG{p}{.}\PYG{n}{toDouble}
\end{Verbatim}

At the end of the first line is a \emph{comment}. It starts with \code{//} and ends at
the end of the same line. It is ignored by the compiler. It is there for
humans, hopefully to add something that helps understanding of the program.

We have two assignment statements. The values to assign are given by arithmetic
expressions on the right side of the equal signs. It looks pretty much like
regular math, except in math class you may be used to only having one letter names
for variables, unlike \code{length}, \code{width}, and \code{height}.

The tradeoff for allowing multiple character names is that multiplication must
have an explicit operation symbol. The symbol used for multiplication in Scala
is \code{*} an asterisk. The \code{+} and parentheses serve their normal mathematical
purpose. In the sample run, the value of \code{2 * (length + width) * height} is

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
2 * (20.5 + 10) * 8
\end{Verbatim}

which simplifies to 488.0. The decimal value is added because \code{wallArea}
contains a Double.

With the sample run, \code{ceilingArea} would get the value 20.5 * 10, or 205.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
    \PYG{n}{val} \PYG{n}{widthString} \PYG{p}{:} \PYG{n}{String} \PYG{p}{=} \PYG{n}{readLine}\PYG{p}{(}\PYG{p}{)}
\end{Verbatim}

Again \code{println} will print something to the computer console. This time the
string printed is more complicated: The string is preceded by the letter \code{s},
which tells the compiler to substitute things into the string. It is proceeded
by the literal string \code{"The wall area is "}, but then we want to print out
the calculated result. The \code{\$wallArea} allows that by inserting the value of
\code{wallArea} (488 in the sample run) into the string. The rest of the string
immediately follows it.

In the sample output you see what is printed:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
The wall area is 488.0 square feet.
\end{Verbatim}

inserting the value taken from the variable \code{wallArea} inside the string,
given in quotes.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(} \PYG{l+s}{\PYGZdq{}Enter room width: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

This statement behave like the previous one, except with different
quoted strings and the value of a different variable. See the sample output.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
    \PYG{c+c1}{// ignore doors}
\end{Verbatim}

Finally we have the matching closing braces marking the end of the body of the
\code{main} function and the end of the body of the \code{Painting} object.

Of course the display would look different if the user entered different data.
Here is what is displayed when the user enters length 15 and width 6.5:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Calculation of Room Paint Requirements
Enter room length: 15
Enter room width: 6.5
The wall area is 344.0 square feet.
The ceiling area is 97.5 square feet.
\end{Verbatim}

\index{whitespace}
The blank space in the program was there to aid human understanding. In a Scala
program \emph{whitespace} is any consecutive combination of spaces, newlines, and
tabs. Scala treats any amount of whitespace just the same as a single space,
except inside quoted strings, where every character is important.

Also the compiler does not require whitespace around special symbols like
\code{\{\};().=*+,}. Hence  the \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/painting/painting.scala}{painting/painting.scala} program above
would be just as well translated by the compiler if it were written as:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
object Painting\PYGZob{}def main(args:Array[String]):Unit=\PYGZob{}val height=8;
println(\PYGZdq{}Calculation of Room Paint Requirements\PYGZdq{});
print(\PYGZdq{}Enter room length: \PYGZdq{});val length=readDouble();
print(\PYGZdq{}Enter room width: \PYGZdq{});val width=readDouble();
val wallArea=2*(length+width)*height;//ignoredoors
val ceilingArea=length*width;println(s\PYGZdq{}The wall area is \PYGZdl{}wallArea square feet.\PYGZdq{});
println(s\PYGZdq{}The ceiling area is \PYGZdl{}ceilingArea square feet.\PYGZdq{});\PYGZcb{}\PYGZcb{}
\end{Verbatim}

Since human understanding is very important, we will emphasize good whitespace
conventions, and expect you to use them.

Next we give you an even simpler program to run in the lab. After that we
return to how you can get the painting program to run on your computer.

\index{Xamarin Studio}\index{labs!Xamarin Studio}

\section{Lab: Editing, Compiling, and Running with Xamarin Studio}
\label{data_lab-edit-compile-run:index-0}\label{data_lab-edit-compile-run:lab-editing-compiling-and-running-with-xamarin-studio}\label{data_lab-edit-compile-run::doc}\label{data_lab-edit-compile-run:lab-edit-compile-run}
This first lab is aimed at taking you through the end-to-end process of
writing and running a basic computer program with the Xamarin Studio
environment. As with all things in
life, we will learn in this lab that becoming a programmer requires you
to learn a number of other things along the way.

In software development/engineering parlance, we typically describe a
scenario as a \emph{workflow}, which can be thought of as a series of steps
that are possibly repeated. The workflow of programming can loosely be
defined as follows:
\begin{enumerate}
\item {} 
Use a text editor to write your source code (human readable).

\item {} 
Compile your code using the Software Development Kit (SDK) into
object code.

\item {} 
Link your object code to create an executable. (There are other
kinds of results to produce, but we will start with the idea of an
executable program to keep things simple.)  The default is to have
an executable program created with compilation, automatically.

\item {} 
Run your program. Even for the most seasoned developers, your
program may not work entirely right the first time, so you may end
up repeating these steps (debugging).

\end{enumerate}

These steps can all be done with different tools.  Many find it simpler to have
an integrated tool, like Xamarin Studio, that does them all in the same place,
and automates the steps that do not need human interaction!

If you are doing this on your own
machine, make sure you have Mono and Xamarin Studio installed as in
{\hyperref[monotools:development-tools]{\emph{Development Tools}}}.

Other tools are available, like
the development environment
Visual Studio (from Microsoft, only for Windows).

Understanding the lower level tools that accomplish each step is important,
but we defer
a discussion to get you going with Xamarin Studio.


\subsection{Goals}
\label{data_lab-edit-compile-run:goals}
Our primary goal to create and understand an Xamarin Studio setup
that you can use to do all of
the remaining homework assignments and labs for this course.


\subsection{Steps}
\label{data_lab-edit-compile-run:steps}\label{data_lab-edit-compile-run:id1}
Xamarin Studio files and interactions
are organized hierarchically.  At a low level are
individual C\# source code files.  One, or possibly more, are used for a
particular \emph{project}.  Multiple projects are gathered together under a single
\emph{solution}.  Xamarin Studio deals with one solution at a time, though you can
separately create multiple solutions.  The simplest thing is to create
a \emph{single solution for this course},
and put each of the projects that you create in that one solution.
You can keep adding onto previous efforts without having to start over
with a new solution each time.

We start by creating a \emph{solution} with a \emph{project} in it.  The images are from
a Mac.  Windows versions should be similar.
\begin{enumerate}
\item {} 
Open Xamarin Studio, in the appropriate way for an application in your
operating system.  It should be in the Start menu for Windows.
Using Spotlight is quick on a Mac.

\item {} 
You get a Welcome screen.  Toward the upper left corner is a link for
New Solution.  Click on it.  Alternately you can follow the path through the menus:
File -\textgreater{} New -\textgreater{} Solution.

{\hfill\includegraphics[width=227.25pt]{newSolution.png}\hfill}

\item {} 
You get a dialog window to fill out.  Follow the order below.
Later parts may not be visible until you do the previous parts:
\begin{itemize}
\item {} 
Select C\# in left hand side panel

\item {} 
Select Console Project in the middle panel

\item {} 
In the bottom field, ``Solution name'' (\emph{not} the top Name field),
enter any name you like:  We recommend \textbf{work}, which will make
sense for all your work for the course.

\item {} 
Leave the Location field above it as is or change it if you like.

\item {} 
Above that, Enter \textbf{hello} in the Name field, for the name of the project.

\item {} 
Make sure \emph{Create directory for solution} is checked in the bottom right.

\item {} 
Press the OK button.

\end{itemize}

{\hfill\includegraphics[width=489.3pt]{consoleProjectDialog.png}\hfill}

You now have created a solution in Xamarin Studio, with one project
inside it. Later we can add further \emph{projects} to \emph{this solution}.

\item {} 
Look at the Xamarin Studio window that appears.  It should have two main sub-windows or
``Pads'' as Xamarin Studio calls them.  A narrow one on the left is the Solution Pad,
containing a hierarchical view of the solution.  You should see your solution name
at the top and the hello project under that.
Folders have a little triangle shown to their
left.  You can click on the triangle.  A triangle pointing down
means the inside of the folder is displayed.  A triangle pointing to the right
means the contents are not being displayed. Listed under hello are References and
Properties, that we will ignore for now.  Below them is the line for the automatically
generated sample code file Program.cs.
The file should also appear in the Edit Pad to the right.

{\hfill\includegraphics[width=485.25pt]{Program.png}\hfill}

\item {} 
Program.cs should be selected in the Solution Pad, as shown above.
Change the selection by clicking on hello.
At the right end of the
highlighted hello entry you should see an icon with a small gear and a triangle.
Click on it to get the context sensitive popup window.
When selected, most entries in the Solution Pad should show this icon,
allowing you to open its context sensitive menu.

\item {} 
Bring up the context menu on the hello project in the Solution Pad.
Select Run Item.

{\hfill\includegraphics[width=389.25pt]{runMainMenu.png}\hfill}

\item {} 
Here Xamarin Studio combines several steps: saving the file,
compiling it into an executable program,
and starting running it if compilation succeeded.
With the canned file it should succeed!  You see a Console window
something like

{\hfill\includegraphics[width=283.5pt]{pressKey.png}\hfill}

You have a chance to see the output of this simple program.
Follow the instructions and press the space or Enter key.

\item {} 
On Windows, that kills the window.  \textbf{On a Mac, only, there is one more step:}

{\hfill\includegraphics[width=198.75pt]{processComplete.png}\hfill}

You have to actively close the Mac terminal window, either by clicking the
red window closing button, or using the keyboard, with Command-W.

\item {} 
Initially, for immediate practice running a program, this automatically generated
file, \code{Program.cs}, is convenient.  Hereafter it is an annoyance.
The file name is always the same, and not useful,
and you would need to redo the whole
code for your own program.  A general approach is to \emph{delete} this
file and put in a file of your own:
\begin{itemize}
\item {} 
Make sure Program.cs is selected in the Solution Pad.
You save a step by closing the Edit Pad for Program.cs,
clicking on the X in the Program.cs tab at the top of the Edit Pad.

\item {} 
In the Solution Pad open the context sensitive menu for Program.cs, and select
Remove.

{\hfill\includegraphics[width=326.25pt]{menuRemoveMain.png}\hfill}

\item {} 
You get another popup.  When it appears the right button is selected,
\emph{but you do not want that selection}, Remove From Project.
The image below shows the proper button, the
\emph{left} button*, \textbf{Delete}, being chosen.
Otherwise the file is left in the hello
folder, but it is just not listed as being in the project.

{\hfill\includegraphics[width=436.5pt]{sureRemove.png}\hfill}

\item {} 
If you forgot to close the Edit Pad tab containing Program.cs earlier, you can still
do it, just say not to save changes to the file when asked.

\end{itemize}

\item {} 
To get in code that you want, there are several approaches.  The one we take
now is to start from a completely
new empty file:  Pop up the context sensitive menu for the hello project.
Select the submenu Add...  and  then New File....

{\hfill\includegraphics[width=468.75pt]{addNewFileMenu.png}\hfill}

\item {} 
In the popup New File Dialog Window, click on Empty File (not Empty \emph{Class}).
Enter the name hello.cs.
Click the New button.

{\hfill\includegraphics[width=427.5pt]{makeEmptyFileDialog.png}\hfill}

\item {} 
This should add hello.cs to the hello project and open an editing window for hello.cs.
The file should have no text.

{\hfill\includegraphics[width=272.25pt]{editEmptyHello.png}\hfill}

Much like in most word processors type in (or paste)
the following code.  This is actually an equivalent
\emph{Hello, World!} program to the automatically generated one,
but it is a bit shorter.
It only introduces the syntax we actually \emph{need} at the beginning,
and will be discussing more shortly:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Hello}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Hello World!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This program is deliberately simple, so you can type it into the text
editor quickly and become familiar with how
to create, edit, and save a program.

{\hfill\includegraphics[width=274.5pt]{pasteHello.png}\hfill}

\item {} 
You can run the project just as before.  You should ge the same result, unless
you made a typing error.  In that case look, fix it, and try again.

\item {} 
Now try a bit of editing:  Look at the program to see where output came
from.  Change what is printed and run it, but don't eliminate the console
window (so you can show it off).

\item {} 
Now grab the instructor or teaching assistant so
they can perform a quick inspection of your work and check it off
(including the varied message printed).

\end{enumerate}

Labs need to be completed to receive
credit. If you are unable to make class on a lab day, please make sure
that you complete the work and demonstrate it by the beginning of the
next lab.

At this point, you have accomplished the major objective for this
introductory lab: to create a Xamarin Studio project, and
enter, compile, and run a C\# program.


\subsubsection{For further reinforcement}
\label{data_lab-edit-compile-run:for-further-reinforcement}\begin{enumerate}
\item {} 
Can you make a new program variant print out two \emph{separate} lines?

\item {} 
Download and install Mono Software Development Kit and Xamarin Studio on
your home computer or laptop.

\item {} 
You can now add further projects to your \emph{current} solution.
To add a new project in your solution, in the Solution Pad open the context
sensitive menu for the whole solution (top line), select Add,
and in the submenu select New project.

You see a window much like when creating a solution, except there is no
line for a solution name.  Complete the remaining parts in the same
way, giving a new name for the project.

\end{enumerate}

\index{arithmetic}

\section{Arithmetic}
\label{data_arithmetic:index-0}\label{data_arithmetic::doc}\label{data_arithmetic:arithmetic}\label{data_arithmetic:id1}
We start with the integers and integer arithmetic, not because
arithmetic is exciting, but because the symbolism should be mostly
familiar. Of course arithmetic is important in many cases, but
C\# is often used to manipulate text and other
sorts of data.

\index{csharp}

\subsection{Csharp}
\label{data_arithmetic:id2}\label{data_arithmetic:index-1}\label{data_arithmetic:csharp}
Of course we could write programs to demonstrate arithmetic,
but there is a fair amount of overhead with a full program.
For just testing little bits, there is another alternative:
The Mono system comes with a program \emph{csharp}.  Let us
try it out.

Open a terminal (Linux or OS X) or {\hyperref[monotools:mono-command-prompt]{\emph{Mono Command Prompt}}}
window in Windows, and enter the command \code{csharp}.  You should see  :

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Mono C\PYGZsh{} Shell, type \PYGZdq{}help;\PYGZdq{} for help

Enter statements below.
csharp\PYGZgt{}
\end{Verbatim}

The \code{csharp\textgreater{}} prompt tells you that the C\# interpreter has started
and is awaiting input. This allows you to create small bits of C\#
and test them, interactively, without having to write a full program!

\index{operator!+ with numbers}\index{+!with numbers}
Play along with the examples here, entering what comes after the prompt:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 2 + 3
5
\end{Verbatim}

The csharp program just has a \emph{read, evaluate, and print loop}: the acronym is
\emph{repl}.  It evaluated the expression \code{2 + 3} and printed the result,
on a line without a prompt.
Csharp can evaluate arbitrary C\# expressions.  It is very handy for
testing as you get used to new syntax.

\index{operator!-}\index{-!subtraction}
Subtraction works as you would expect.
Blanks are optional around symbols:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 10 \PYGZhy{} 3
7
\end{Verbatim}

For the binary arithmetic operators,
you are encouraged to add blanks to make the expression
more easily readable by humans.

The csharp program is more line-oriented than the C\# language.
If you press the return key when what you have entered is a complete expression
you see the value as a response.
If your expression is clearly incomplete you get another \code{\textgreater{}} prompt (with no
``csharp''), until you have entered enough for a full expression.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 10\PYGZhy{}
      \PYGZgt{} 3
7
\end{Verbatim}

\index{operator!*}\index{* multiplication}
In math class you could enter something like 4(10) for multiplication:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 4(10)
\PYGZob{}interactive\PYGZcb{}(1,2): error CS0119: Expression denotes a \PYGZsq{}value\PYGZsq{},
where a \PYGZsq{}method group\PYGZsq{} was expected
\end{Verbatim}

Unfortunately the error messages are not always easy to follow:
it is hard to guess the
intention of the user making a mistake.

The issue here is that the multiplication operator must be \emph{explicit} in
C\#.  Recall that an asterisk is used as a multiplication operator:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 4 * 10
40
\end{Verbatim}

\index{( )!grouping}\index{grouping ( )}\index{-!negation}
Enter each of the following expressions into csharp, and think what they
will produce (and then check):

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
2*5
2 + 3 * 4
\end{Verbatim}

If you expected the last answer to be 20, think again: C\# uses
the normal \emph{precedence} of arithmetic operations: Multiplications
divisions, and negations are done before addition and subtraction, unless
there are parentheses forcing the order:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} \PYGZhy{}(2+3)*4
\PYGZhy{}20
\end{Verbatim}

A sequence of operations with equal precedence also work like in math:
left to right in most cases, like for combinations of addition and subtraction:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 10 \PYGZhy{} 3 + 2
9
\end{Verbatim}

\index{remainder \%}\index{\% remainder}\index{operator!/, \%}\index{division}\index{/ division}\index{. !double literal}\index{double}\index{int}\index{type!int}\index{type!double}

\subsection{Division and Remainders}
\label{data_arithmetic:index-6}\label{data_arithmetic:division-and-remainders}\label{data_arithmetic:id3}
We started with the almost direct translations from math.  Division is
more complicated.  We continue in the csharp program:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 5.0/2.0;
2.5
csharp\PYGZgt{} 14.0/4.0;
3.5
\end{Verbatim}

So far so good.  Now consider:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 14/4
3
\end{Verbatim}

What?  Some explanation is in order.  All data has a \emph{type} in C\#.
When you write an explicit number
without a decimal point, like 2, 17, or -237,
it is interpreted as the type of an integer, called \code{int} for short.

When you include a decimal point, the type is \code{double}, representing a more
general real number.  This is true even if the value of the number is an
integer like 5.0: the type is still \code{double}.

Addition, subtraction, and multiplication work as you would expect for
\code{double} values, too:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 0.5 * (2.0 + 4.5)
3.25
\end{Verbatim}

If one or both
of the operands to \code{/} is a \code{double}, the result is a \code{double},
close to the actual quotient.
We say close,
because C\# stores
values with only a limited precision, so in fact results are
only approximate in general.  For example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 1.0/3
0.333333333333333
\end{Verbatim}

Small errors are also possible with the \code{double} type
and the other arithmetic operations.  See {\hyperref[data_types-and-conversions:type-double]{\emph{Type double}}}.

\begin{notice}{note}{Note:}
In C\#, the result of the / operator depends on the
\emph{type} of the operands, not on the \emph{mathematical value} of the operands.
\end{notice}

Division with \code{int} data is handled completely differently.

If you think about it, you learned several ways to do division.
Eventually you learned how to do division resulting in a decimal.
In the earliest grades, however, you would say
\begin{quote}

``14 divided by 4 is 3 with a remainder of 2.''
\end{quote}

Note the quotient is an integer 3, that matches the C\# evaluation of 14/4,
so having a way to generate an integer quotient is not actually too strange.
The problem here is that the answer from grade school is in \emph{two} parts,
the integer quotient 3 and the remainder 2.

C\# has a \emph{separate} operation symbol to generate the remainder part.
There is no standard
single operator character operator for this in regular math,
so C\# grabs an unused symbol:
\code{\%} is the remainder operator.
(This is the same as in many other computer languages.)

Try in the csharp shell:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 14 / 4
3
csharp\PYGZgt{} 14 \PYGZpc{} 4
2
\end{Verbatim}

You see that with the combination of the \code{/} operator and the \code{\%} operator,
you get both the quotient and the remainder from our grade school division.

Now predict and then try each of these expression in csharp:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
23/5
23\PYGZpc{}5
20\PYGZpc{}5
6/8
6\PYGZpc{}8
6.0/8
\end{Verbatim}

Finding remainders will prove more useful than you might think in
the future!  Remember the strange \code{\%} operator.

\begin{notice}{note}{Note:}
The precedence of \code{\%} is the same as \code{/} and \code{*}, and hence
higher than addition and subtraction, \code{+} and \code{-}.
\end{notice}

When you are \emph{done with csharp}, you can enter the special expression

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
quit
\end{Verbatim}

There are some more details about numeric types in {\hyperref[data_types-and-conversions:value-types]{\emph{Value Types and Conversions}}}.

\index{expression}
We have been testing arithmetic expressions, with the word
\emph{expression} used pretty much like with normal math.  More generally in C\#
an \emph{expression} is any syntax that evaluates to a single value of some type.
We will introduce many more types and operations that can be used in expressions.


\subsubsection{Divisible by 17 Exercise}
\label{data_arithmetic:divisible-by-17-exercise}
What is a simple expression that lets you see if an int x is divisible by 17?


\subsubsection{Mixed Arithmetic Exercise}
\label{data_arithmetic:mixed-arithmetic-exercise}
\emph{Think} of the result of one of these at a time; write your prediction,
and \emph{then} test, and write the correct answer afterward if you were wrong.
Then go on to the next....
For the ones you got wrong, can you explain the result after seeing it?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+m}{2} \PYG{p}{*} \PYG{l+m}{5} \PYG{p}{+} \PYG{l+m}{3}
\PYG{l+m}{2} \PYG{p}{+} \PYG{l+m}{5} \PYG{p}{*} \PYG{l+m}{3}
\PYG{l+m}{1.5} \PYG{p}{*} \PYG{l+m}{3}
\PYG{l+m}{7.0}\PYG{p}{/}\PYG{l+m}{2.0}
\PYG{l+m}{7.0}\PYG{p}{/}\PYG{l+m}{2}
\PYG{l+m}{7}\PYG{p}{/}\PYG{l+m}{2.0}
\PYG{l+m}{4.0} \PYG{p}{*} \PYG{l+m}{3} \PYG{p}{/} \PYG{l+m}{8}
\PYG{l+m}{4} \PYG{p}{*} \PYG{l+m}{3} \PYG{p}{/} \PYG{l+m}{8}
\PYG{l+m}{6} \PYG{p}{*} \PYG{p}{(}\PYG{l+m}{2.0}\PYG{p}{/}\PYG{l+m}{3}\PYG{p}{)}
\PYG{l+m}{6} \PYG{p}{*} \PYG{p}{(}\PYG{l+m}{2}\PYG{p}{/}\PYG{l+m}{3}\PYG{p}{)}
\PYG{l+m}{3} \PYG{p}{+} \PYG{l+m}{1}\PYG{l+m}{0} \PYG{p}{\PYGZpc{}} \PYG{l+m}{6}
\PYG{l+m}{1}\PYG{l+m}{0} \PYG{p}{\PYGZpc{}} \PYG{l+m}{6} \PYG{p}{+} \PYG{l+m}{3}
\end{Verbatim}

\index{variable!assignment}\index{assignment statement}\index{statement!assignment}\index{= !assignment}

\section{Variables and Assignment}
\label{data_variables:index-0}\label{data_variables:variables-and-assignment}\label{data_variables::doc}\label{data_variables:id1}
Each piece of data in a C\# program has a \emph{type}.  Several types have been introduced:
\code{int} for integers, \code{double} for numbers allowing a fractional part,
approximating more general real numbers.
There are many other numeric types and also non-numeric types, but we can use \code{int}
and \code{double} for examples now.  Data gets stored in computer memory.  Specific
locations in memory are associated with the type of data stored there
and with a name to refer to it.

A program allocates a named storage spot for a particular type of data with a
\emph{declaration statement}, like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{width}\PYG{p}{;}
\end{Verbatim}

Each declaration must specify a type for the data to be stored and give a name to
refer to it.  These names associated with a data storage location are called
\emph{variables}.

The declaration statement above sets aside a location to store an \code{int}, and names
the location \code{width}.  Several variables of the same type can be
listed together, like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{double} \PYG{n}{x}\PYG{p}{,} \PYG{n}{y}\PYG{p}{,} \PYG{n}{z}\PYG{p}{;}
\end{Verbatim}

identifying three storage locations for variables of type \code{double}.

To be useful, data needs to be stored in these locations.  This is done with
an \emph{assignment statement}.
For example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{width} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\end{Verbatim}

A simple schematic diagram with a name for a location in memory (the box):

\includegraphics[width=72pt]{variableDeclaration.png}

Although we are used to reading left to right, an assignment statement works
\emph{right to left}.  The value on the right side of the equal sign is calculated
and then placed in the memory location associated with the variable on the left
side of the equal sign, either giving an initial value or
\emph{overwriting} any previous value stored there.

\includegraphics[width=72pt]{variableAssignment.png}

\index{initializer}\index{=!initializer}\index{declaration initializer}
Variables can also be initialized as they are declared:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{width} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{k+kt}{double} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{2.5}\PYG{p}{,} \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{2}\PYG{l+m}{7}\PYG{p}{,} \PYG{n}{z} \PYG{p}{=} \PYG{l+m}{0.5}\PYG{p}{;}
\end{Verbatim}

or initializations and plain declarations can be mixed:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{width} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{,} \PYG{n}{height}\PYG{p}{,} \PYG{n}{area}\PYG{p}{;}
\PYG{n}{height} \PYG{p}{=} \PYG{l+m}{7}\PYG{p}{;}
\end{Verbatim}

Stylistically the example above is inconsistent, but it illustrates what is
possible.  Technically an initialization is not an assignment.  We will see
some syntax that is legal in initializers, but not in assignment statements.

We could continue with a further assignment statement:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{area} \PYG{p}{=} \PYG{n}{width} \PYG{p}{*} \PYG{n}{height}\PYG{p}{;}
\end{Verbatim}

Look at this in detail.  The assignment statement starts by evaluating the
expression on the right-hand side: \code{width * height}.  When variables are
used in an expression, their current values are substituted,
like in evaluating an expression in math, so the value is the same as

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
5 * 7
\end{Verbatim}

which finally evaluates to 35.  In the last step of the assignment statement,
the value 35 is then assigned to the variable on the left, \code{area}.

\begin{notice}{warning}{Warning:}
You want \emph{one} spot in memory prepared for \emph{each} variable.  This happens
with declaration, not assignment:  Assignment just changes the value
at the current location.  Do not \emph{declare} the same variable more than once.
You will get an error.  More on the fine points around that in {\hyperref[localscope:local-scope]{\emph{Local Scope}}}.
\end{notice}

\index{csharp}\phantomsection\label{data_variables:more-csharp}
We continue introducing {\hyperref[data_arithmetic:csharp]{\emph{Csharp}}}:
Remember that in csharp you can just give an expression,
and csharp responds with a value.  That syntax and reaction is special to
csharp.   In csharp you can also test regular C\# statements,
like declarations and assignments.  The most recent versions of csharp
do not require you to end a statement with a semicolon, though we tend to
put semicolons after statements in our illustrations (and no semicolon for just
an expression).
As in a regular program, statements
do not give an immediate visible response in csharp.  Still in
csharp you can display a variable value easily:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} int width = 5, height, area;
csharp\PYGZgt{} height = 7;
csharp\PYGZgt{} area = width * height;
csharp\PYGZgt{} area
35
\end{Verbatim}

In the last line, \code{area} is an expression, and csharp will give back its value,
which is just the current value of the variable.

\index{csharp!help}\index{csharp!quit!}\index{csharp!ShowVars}
At this point you should be able to make sense of some more features of csharp.
You can start with the csharp special help command:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} help
\PYGZdq{}Static methods:
  Describe (object)       \PYGZhy{} Describes the object\PYGZsq{}s type
  LoadPackage (package);  \PYGZhy{} Loads the given Package (like \PYGZhy{}pkg:FILE)
  LoadAssembly (assembly) \PYGZhy{} Loads the given assembly (like \PYGZhy{}r:ASSEMBLY)
  ShowVars ();            \PYGZhy{} Shows defined local variables.
  ShowUsing ();           \PYGZhy{} Show active using declarations.
  Prompt                  \PYGZhy{} The prompt used by the C\PYGZsh{} shell
  ContinuationPrompt      \PYGZhy{} The prompt for partial input
  Time(() \PYGZhy{}\PYGZgt{} \PYGZob{} \PYGZcb{})         \PYGZhy{} Times the specified code
  print (obj)             \PYGZhy{} Shorthand for Console.WriteLine
  quit;                   \PYGZhy{} You\PYGZsq{}ll never believe it \PYGZhy{} this quits the repl!
  help;                   \PYGZhy{} This help text
  TabAtStartCompletes \PYGZhy{} Whether tab will complete even on empty lines
\end{Verbatim}

A lot of this is still beyond us but these parts are useful:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
ShowVars ();            \PYGZhy{} Shows defined local variables.
quit;                   \PYGZhy{} You\PYGZsq{}ll never believe it \PYGZhy{} this quits the repl!
help;                   \PYGZhy{} This help text
\end{Verbatim}

We can continue the csharp session above and illustrate ShowVars():

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} ShowVars();
int width = 5
int height = 7
int area = 35
\end{Verbatim}

displaying all the variables currently known to csharp, plus their current values.

We refer to ``current values''.  An important distinction between variables in math
and variables in C\# is that C\# values can \emph{change}.  Follow this csharp sequence:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} int n = 3;
csharp\PYGZgt{} n
3
csharp\PYGZgt{} n = 7;
csharp\PYGZgt{} n
7
\end{Verbatim}

showing we can change the value of a variable.  The most \emph{recent} assignment is remembered
(until the next assignment....)  We can imagine a schematic diagram:

\includegraphics[width=43.5pt]{variableChange.png}

We can carry this csharp session one step further,
illustrating a difference between C\# and math:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} n = n + 1;
csharp\PYGZgt{} n
8
\end{Verbatim}

Clearly \code{n = n + 1} is not a true mathematical equation:  It \emph{is} a C\# assignment,
executing with a
specific sequence of steps.
\begin{enumerate}
\item {} 
First the right hand side expression
is evaluated, \code{n + 1}.

\item {} 
This involves looking up the current value of \code{n},
which we set to 7, so the expression is the same as \code{7 + 1} which is 8.

\item {} 
\emph{After} this evaluation, an assignment is made to the left hand variable,
which happens to be \code{n} again.

\item {} 
Then the \emph{new} value of \code{n} is 8, replacing the old 7.

\end{enumerate}

There are many occasions in which such an operation will be useful.

Assignment syntax does have two strikes against it:
\begin{enumerate}
\item {} 
It appropriates math's equal sign to mean something quite different.

\item {} 
The right to left operation is counter to the English reading direction.

\end{enumerate}

Still this usage is common to many programming languages.

\begin{notice}{warning}{Warning:}
Remember in an assignment that the sides of the equal sign have totally
different meanings.  You assign to a variable on the left side \emph{after}
evaluating the expression on the right.
\end{notice}

We can illustrate a likely mistake in csharp:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} 3 = n;
\PYGZob{}interactive\PYGZcb{}(1,2): error CS0131: The left\PYGZhy{}hand side of an assignment
must be a variable, a property or an indexer
\end{Verbatim}

Students commonly try to assign left to right.  At least in this case you get
an error message so you see a mistake.  If you mean to assign the value of
x to y, and write:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{x} \PYG{p}{=} \PYG{n}{y}\PYG{p}{;}
\end{Verbatim}

you get the opposite effect, changing x rather than y, with \emph{no} error statement.
Be careful!

There is some weirdness in csharp because it adds special syntax for expressions
which does not appear in regular programs, but it also wants to allow syntax
of regular programs.  Some conflict can occur when trying to display
an expression, sometimes leading to csharp giving
a strange error for apparently no reason.  In that case,
try putting \emph{parentheses} around the expression, which is always legal for an
expression, but would never start a regular statement:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} int width = 3;
csharp\PYGZgt{} int height = 5;
csharp\PYGZgt{} width * height
\PYGZob{}interactive\PYGZcb{}(1,2): error CS0246: The type or namespace name \PYGZsq{}width\PYGZsq{} could
not be found. Are you missing a using directive or an assembly reference?
csharp\PYGZgt{} (width * height)
15
\end{Verbatim}

\index{literal}\index{identifier}

\subsection{Literals and Identifiers}
\label{data_variables:index-4}\label{data_variables:literals-and-identifiers}\label{data_variables:id2}
Expressions like \code{27} or \code{32.5} or \code{"hello"} are called \emph{literals},
coming from the fact that they \emph{literally} mean exactly what they
say. They are distinguished from variables, whose value the compiler \emph{cannot} infer
directly from the name alone.

The sequence of characters used to form a variable name (and names
for other C\# entities later) is called an \emph{identifier}. It
identifies a C\# variable or other entity.

\index{keyword}
There are some restrictions on the character sequence that make up
an identifier:
\begin{itemize}
\item {} 
The characters must all be letters, digits, or underscores \code{\_},
and must start with a letter. In particular, punctuation and blanks
are not allowed.

\item {} 
There are some words that are \emph{keywords} for special use in
C\#. You may not use these words as your own identifiers. They
are easy to recognize in editors like in Xamarin Studio,
that know about C\# syntax:  They are colored differently.

\end{itemize}

We will only discuss a small fraction of the keywords in this course, but the curious
may look at the
\href{http://msdn.microsoft.com/en-us/library/x53a06bb.aspx}{full list}.

\index{case sensitive}
C\# is case sensitive: The identifiers \code{last}, \code{LAST}, and
\code{LaSt} are all different. Be sure to be consistent. The compiler
can usually catch these errors, since it is the version used in the \emph{one}
declaration that matters.

\index{identifier!multi-word naming convention}\index{camel case}
What is legal is distinct from what is conventional or good
practice or recommended. Meaningful names for variables are
important for the humans who are looking at programs, understanding
them, and revising them. That sometimes means you would like to use
a name that is more than one word long, like \code{price at opening},
but blanks are illegal! One poor option is just leaving out the
blanks, like \code{priceatopening}. Then it may be hard to figure out
where words split. Two practical options are
\begin{itemize}
\item {} 
underscore separated: putting underscores (which are legal) in
place of the blanks, like \code{price\_at\_opening}.

\item {} 
using \emph{camel-case}: omitting spaces and using all lowercase,
except capitalizing all words after the first, like
\code{priceAtOpening}

\end{itemize}

Use the choice that fits your taste (or the taste or convention of
the people you are working with).  We will tend to use
camel-case for variable inside programs, while we use underscores in
program file names (since different operating systems deal with case
differently).


\subsubsection{Assignment Exercise}
\label{data_variables:assignment-exercise}
\emph{Think} what the result would be in csharp:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{=} \PYG{n}{x} \PYG{p}{*} \PYG{l+m}{3}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{=} \PYG{n}{x} \PYG{p}{*} \PYG{l+m}{5}\PYG{p}{;}
\PYG{n}{x}
\end{Verbatim}

Write your prediction.  Then test.  Can you explain it if you got it wrong?


\subsubsection{Another Assignment Exercise}
\label{data_variables:another-assignment-exercise}
If you had trouble with the last, one try this one, too:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{a} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{n}{a} \PYG{p}{=} \PYG{n}{a}\PYG{p}{/}\PYG{l+m}{2}\PYG{p}{;}
\PYG{n}{a} \PYG{p}{=} \PYG{n}{a} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}
\PYG{n}{a} \PYG{p}{=} \PYG{n}{a} \PYG{p}{*} \PYG{l+m}{2}\PYG{p}{;}
\PYG{n}{a}
\end{Verbatim}

\index{syntax template typography}\index{typography of syntax templates}

\section{Syntax Template Typography}
\label{data_typography:syntax-template-typography}\label{data_typography:index-0}\label{data_typography::doc}\label{data_typography:id1}
When new C\# syntax is introduced, the usual approach will be to
give both specific examples and general templates. In general
templates for C\# syntax the typeface indicates the the category
of each part:

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Typeface
} & \textsf{\relax 
Meaning
}\\
\hline
\code{Typewriter font}
 & 
Text to be written \emph{verbatim}
\\
\hline
\textbf{Bold}
 & 
A place where you can use an arbitrary
identifier.
\\
\hline
\emph{Emphasized}
 & 
A place where you can use an arbitrary
expression (which might be a single variable name).
\\
\hline
Normal text
 & 
A description of what goes in that position,
without giving explicit syntax
\\
\hline\end{tabulary}


An attempt is made with the parts that are not verbatim to be
descriptive of the use expected.

As a start we can give some general syntax for declarations and assignment statements:

\index{statement!declaration}\index{declaration statement}

\subsection{Declaration Syntax Options}
\label{data_typography:declaration-syntax-options}\label{data_typography:index-1}\begin{quote}

\textbf{type} \textbf{variableName} \code{;}
\end{quote}

or with initialization:
\begin{quote}

\textbf{type} \textbf{variableName} \code{=} \emph{initialValue} \code{;}
\end{quote}

or there can be a list of variables of the same type, for instance a list
of three variables:
\begin{quote}

\textbf{type} \textbf{variableName1} \code{,} \textbf{variableName2} \code{,} \textbf{variableName3} \code{;}
\end{quote}

Some or all of the variables in the list could also have initializers.

Space is allocated for each variable named, according to its type.  Where there is
an initializer, an initial value is set for the variable.

\index{assignment statement}\index{statement!assignment}

\subsection{Assignment Syntax}
\label{data_typography:assignment-syntax}\label{data_typography:index-2}\begin{quote}

\textbf{variableName} \code{=} \emph{expression} \code{;}
\end{quote}

The \emph{expression} is evaluated before its value is assigned to \textbf{variableName}.


\section{Strings, Part I}
\label{data_strings1:strings-part-i}\label{data_strings1::doc}
Enough with numbers for a while. Strings of characters are another
important type in C\#.

\index{string}\index{"..." for string literal}
A string in C\# is a sequence of characters. For C\# to
recognize a literal sequence of characters, like \code{hello}, as a string, it
must be enclosed in quotes \code{"} to delimit the string: \code{"hello"}.
Special cases are considered later in {\hyperref[data_strings2:strings2]{\emph{String Special Cases}}}.

\index{string!concatenation with +}\index{concatenation}\index{+!string concatenation}\index{operator!+ string concatenation}

\subsection{String Concatenation}
\label{data_strings1:string-concatenation}\label{data_strings1:index-1}\label{data_strings1:id1}
Because everything in C\# is typed, C\# can give a special meaning to
operators depending on the types involved,
as we saw with \code{/}.
We can operate on numbers with arithmetic operators, including \code{+}.
With strings \code{+} has a completely different meaning. Look at the example
in csharp:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} \PYGZdq{}never\PYGZdq{} + \PYGZdq{}ending\PYGZdq{};
\PYGZdq{}neverending\PYGZdq{}
\end{Verbatim}

The plus operation with strings means \emph{concatenate} the strings: join them
together end to end.

C\# is even a bit smarter.  If you use a \code{+} with a string, presumable you
are looking to produce a string, so even if the second operand to the \code{+} is
\emph{not} a string, it is automatically converted to a string representation before
concatenating:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} int x = 42;
csharp\PYGZgt{} string result;
csharp\PYGZgt{} result = \PYGZdq{}We get \PYGZdq{} + x;
csharp\PYGZgt{} result;
\PYGZdq{}We get 42\PYGZdq{}
\end{Verbatim}

You can chain concatenations.  We could make a full sentence adding a period:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} \PYGZdq{}We get \PYGZdq{} + x + \PYGZdq{}.\PYGZdq{};
\PYGZdq{}We get 42.\PYGZdq{}
\end{Verbatim}

Note to Python programmers:  Unfortunately there is no \code{*}
multiplication operator for strings in C\#.


\subsubsection{Four Copies Exercise}
\label{data_strings1:four-copies-exercise}
In csharp declare and initialize a string variable.  Write an expression that
evaluates to four copies of the string, so it works no matter what value you
gave your string.


\subsubsection{Sum String Exercise}
\label{data_strings1:sum-string-exercise}
In csharp declare and initialize two int's, x and y.  Then enter an expression whose
value is ``x + y is 56'', except that 56 is replaced by the sum of x and y, and is not
a literal, but calculated from the actual values of variables x and y (which do not
need to add up to 56 specifically).

This has a trick to it.


\subsubsection{Ints and Strings Added}
\label{data_strings1:ints-and-strings-added}
In csharp enter

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}
\PYG{k+kt}{int} \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
\end{Verbatim}

\emph{Think} what the csharp response
is to each of these then write one predicted response at a time,
\emph{then} test it,
and put the right answer beside your answer if you were wrong:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{x} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}??\PYGZdq{}} \PYG{p}{+} \PYG{n}{y}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{+} \PYG{n}{y} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}??\PYGZdq{}}\PYG{p}{;}
\PYG{p}{(}\PYG{n}{x} \PYG{p}{*} \PYG{n}{y} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}??\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}??\PYGZdq{}} \PYG{p}{+} \PYG{n}{x} \PYG{p}{*} \PYG{n}{y}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}??\PYGZdq{}} \PYG{p}{+} \PYG{n}{x} \PYG{p}{+} \PYG{n}{y}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}??\PYGZdq{}} \PYG{p}{*} \PYG{n}{y}\PYG{p}{;}
\end{Verbatim}

Can you explain the ones you got wrong, after looking at the actual answer?
Precedence and operation order is important.

\index{Console!WriteLine}\index{WriteLine!Console}

\section{Writing to the Console}
\label{data_print1:write-to-console}\label{data_print1:index-0}\label{data_print1::doc}\label{data_print1:writing-to-the-console}
In interactive use of csharp, you can type an
expression and immediately see the result of its evaluation. This
is fine to test out syntax and maybe do simple calculator
calculations. In a regular C\# program run from a file like in
{\hyperref[data_sampleprogram:sample-program]{\emph{A Sample Scala Program}}},
you must explicitly give instructions to print to a
console or terminal window.  This will be a window like you see
when running csharp.

This printing is accomplished through a function with a long name: \code{Console.WriteLine}.
Like with math, you can pass a function a value to work on, by placing it in
parentheses after the name of the function.  Unlike in high school algebra classes,
in C\# we have many types of data to supply other than numbers.  The simplest
way to use the \code{Console.WriteLine} function is to give it a string.
We can demonstrate in csharp.  The response is just the line that would
be printed in a regular program:

\index{. !class static member}
\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} Console.WriteLine(\PYGZdq{}Hello, world!\PYGZdq{});
Hello, world!
\end{Verbatim}

What is printed to the screen does \emph{not} have the quotes which we needed to
define the literal string \code{"Hello, world!"} inside the program.

\code{Console} is a C\# class maintained by the system, that
interacts with the terminal or console window where text output
appears for the program.  A function defined in that class is \code{WriteLine}.
To refer to a function like \code{WriteLine} in a different class, you must indicate
the location of the function with the ``dot'' notation shown:
class name, then \code{.}, then the function.  This
gives the more elaborate name needed in the program.

The string that gets printed can be the result of evaluating an expression,
for instance concatenating:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} int total = 5;
csharp\PYGZgt{} Console.WriteLine(\PYGZdq{}All together: \PYGZdq{} + total);
All together: 5
\end{Verbatim}

More elaborate use of \code{WriteLine} is discussed in {\hyperref[data_writeline-substitution:format-strings]{\emph{String Format Operation}}}.

\index{Console!Write}
The \code{Console.WriteLine} function automatically makes the printing
position advance to the next line, as when you press the Enter or Return key.
A variant, \code{Console.Write}, prints the parameter exactly, and nothing else.
The statement-at-a-time approach in csharp is not good for illustrating the
differences.

Printing is better shown off in a real program....

\index{program structure}

\section{C\# Program Structure}
\label{data_programstructure:program-structure}\label{data_programstructure:index-0}\label{data_programstructure::doc}\label{data_programstructure:c-program-structure}
We discuss the most basic syntax satisfied by all C\# programs, which are plain text files,
with names ending in \code{.cs}.  There will be additions
later, but any program you can run will include:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{using System;}
\item[] 
\item[] \code{class} \textbf{ClassName}
\item[] \code{\{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] \code{static void Main()}
\item[] \code{\{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] program statements go here....
\item[] 
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

By convention class names are capitalized.

You can see that both the example program \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/painting/painting.cs}{painting/painting.cs} and the lab program
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/hello/hello.cs}{hello/hello.cs} follow this pattern.  The discussion of these parts through
line 6 in
{\hyperref[data_sampleprogram:sample-program]{\emph{A Sample Scala Program}}} are about all we have to say at this point.  For now this
is the boilerplate code.  We will make additions as necessary.  We choose not to
clutter up the basic setup with features that we are not about to use and discuss.

Here is a silly little test illustrating the difference between \code{Console.WriteLine}
and \code{Console.Write}, in example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/write\_test/write\_test.cs}{write\_test/write\_test.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;} 

\PYG{k}{class} \PYG{n+nc}{WriteTest}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}hello\PYGZdq{}}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{s}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}there\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(} \PYG{l+s}{\PYGZdq{}Another line\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Starting \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}yet another line\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

When run, the program prints:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
hellotherehello
Another line
Starting yet another line
\end{Verbatim}

Do you see how the output shows the differences between \code{WriteLine} and \code{Write}?
If we added another printing statement, where would the beginning of
the output appear:
after the final \code{e} or under the \code{S} of Starting?

\index{Xamarin Studio!indentation options setting}\index{indentation options in Xamarin Studio}\index{tabs changed to spaces}

\subsection{Indentation Help}
\label{data_programstructure:indentation-help}\label{data_programstructure:index-1}\label{data_programstructure:id1}
Using conventional indentation helps understand a program and find errors,
like unmatched braces. When you press return in a C\# source file
(i.e. a file with name ending in \code{.cs}), Xamarin Studio makes a guess at the proper
indentation of the next line.  The exact reaction can be set in the \emph{options}.
The simplest approach is to set these options \emph{once} for all new files
in a solution, like your work solution:
\begin{enumerate}
\item {} 
Access the context menu for the whole solution (not one project).

\item {} 
Select Options.

\includegraphics[width=332.25pt]{select_options.png}

\item {} 
In the popup Solution Options Window, you will see ``Code Formatting''
in the left column.  If you do not see ``C\# source code'' and then ``Text file''
right underneath it
click on ``Code Formatting'' to expand the hierarchy.

\includegraphics[width=351.75pt]{set_indent.png}

\item {} 
Click on Text file, and then the right side should show options.
Adjust them to look like the picture: tab and indent widths 3,
first and last check boxes \emph{checked}
(Convert tabs to spaces. Remove trailing spaces),
and have the middle check box (Allow tabs after non-tabs) \emph{unchecked}.

\item {} 
Click OK.

\end{enumerate}

Tabs vs. spaces is not a significant issue inside a consistent environment,
like Xamarin Studio, but if there are tab characters in a file,
they can be expanded different amounts by different display programs.
Then particularly if you mix tab characters and spaces you can get
something very strange.
If only spaces are used, there is no ambiguity in different displays.

The 3 vs. 4 spaces is not a big deal, but 3 appears to be large enough to see
easily, and makes lines with nested indentation have more room.

\index{compiler error!explanation link}

\subsection{Compiler Error Help}
\label{data_programstructure:compiler-error-help}\label{data_programstructure:index-2}
There are an enormous number of possible \emph{syntactic} errors in your source code
that the compiler
can detect.

\index{editor error annotations}\index{syntax error annotations in editor}\index{Xamarin Studio!editor error annotations}
\textbf{Errors shown} \emph{while} \textbf{editing}:  If you use an editor like Xamarin Studio,
some of these errors are even checked while you type and are
noted while you are editing.  They may be indicated with a
red squiggly underline, and possibly a red comment at the right.  Sometimes
the squiggle is just because you are in the middle of something, but if it
is still there after you complete a whole statement, there may well
be an issue to look at.  Sometimes fixing the issue makes the annotation
go away, but sometimes your program may really be fixed,
even though the error annotation
does not go away \emph{until you formally compile/build the whole program}.
This annoying ambiguity leads some people to turn off error annotations,
and just let
the system note errors after a complete compile cycle.

After compiling and getting an error, sometimes reading the error description
carefully  will help you
understand the problem.  Sometimes the error is very cryptic.   In those cases
it might help to look at the C\# .NET error documentation,
\begin{quote}

\href{http://msdn.microsoft.com/en-us/library/ms228296.aspx}{http://msdn.microsoft.com/en-us/library/ms228296.aspx}.
\end{quote}

Each compiler error you make has a number shown in its description.
Many of these error numbers are shown in the left column
of the linked page.  You can click to get a more complete explanation and
examples.

Another important way to learn about the error messages is to leverage your
experience:  After
you have eventually found how to fix your error, \emph{allow the extra time} to
use your new knowledge,
look \emph{back} at the original error message,
and see if the error description text makes more sense now.
That should help next time,
(and there usually is a next time). Even when the error description still
makes no particular sense, you may well get into the same situation again,
with the same error number.  Then
remembering the issue you found in a previous time could help.

Debugging can eat up an enormous amount of time,
so it is really worth your effort to understand the errors that you tend to make
and the errors' relation to the error messages that you get.

\begin{notice}{warning}{Warning:}
It is certainly helpful that the compiler finds \emph{syntactic} errors for you,
but be sure to remember that compiling does \emph{not} mean the program
will ``work'' and correctly do what you desire.  Test your compiled program
thoroughly to reduce the chance of \emph{logical} errors remaining, that
cause \emph{run-time} errors, or just the wrong results.
\end{notice}

\index{sequential execution order}\index{execution!sequential order}\index{playing computer}

\subsection{Sequential Execution}
\label{data_programstructure:index-4}\label{data_programstructure:id2}\label{data_programstructure:sequential-execution}
A function like \code{Main} involves a sequence of statements to execute.
The basic order of execution is \emph{sequential}:
first statement, then second, ....
This is the same as the \emph{textual order}, so it is easy to follow.  Later in
{\hyperref[functions:defining-own-functions]{\emph{Defining Functions of your Own}}}, {\hyperref[decisions:if-statements]{\emph{Decisions}}}, and {\hyperref[while:while-loops]{\emph{While Loops}}},
we will see more complicated
execution orders that do \emph{not} match textual order.
Whatever the order of execution given by the program, it is important to
always keep track of the current state of the program: where we are and
what are the values of variables.

For now consider a small,
artificial example program,
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/update\_vars/update\_vars.cs}{update\_vars/update\_vars.cs},
emphasizing the ability to \emph{reassign} variable values.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{UpdateVars}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}} \PYG{c+c1}{// simple sequential code updating two variables}
      \PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}     
      \PYG{k+kt}{int} \PYG{n}{y} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{l+m}{2}\PYG{p}{;}
      \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{2} \PYG{p}{*} \PYG{n}{y}\PYG{p}{;}       
      \PYG{n}{x} \PYG{p}{=} \PYG{n}{y} \PYG{p}{\PYGZhy{}} \PYG{n}{x}\PYG{p}{;}      
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{n}{x} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}} \PYG{p}{+} \PYG{n}{y}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Can you \emph{predict} the result? Run the program and check.
Particularly if you did not guess right, it is important to
understand what happens, one step at a time. That means keeping
track of what changes to variables are made by each statement.

In the table below, statements are referred to by the numbers labeling
the lines in the code above. We can track the state of each
variable after each line is executed. A dash is shown where a
variable is not defined. For instance after line 7 is executed, a
value is given to x, but y is still undefined. Then y gets a value
in line 8.
The comment space can be used any time
it is helpful.  In particular it should be used  when something
is printed, since this
important action does \emph{not} affect the variable list.

\begin{tabulary}{\linewidth}{|L|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
x
} & \textsf{\relax 
y
} & \textsf{\relax 
Comment
}\\
\hline
5
 & 
-
 & 
-
 & 
Start at beginning of Main
\\
\hline
7
 & 
3
 & 
-
 & 
initialize x
\\
\hline
8
 & 
3
 & 
5
 & 
5=3+2, using the value of x from the previous line
\\
\hline
9
 & 
3
 & 
10
 & 
10=2*5 on the right; use the value of y from the
previous line
\\
\hline
10
 & 
7
 & 
10
 & 
7=10-3 on the right; use the value of x and y from the
previous line
\\
\hline
11
 & 
7
 & 
10
 & 
print: 7 10
\\
\hline\end{tabulary}


The critical point here is to always use the most recently assigned value
of each variable.

The order of execution will always be the order of the lines in our
table. In this simple \emph{sequential} code, that \emph{also} follows the
textual order of the program.

Following each line of execution of a
program in the proper order of execution, carefully,
keeping track of the current values of
variables, will be called \emph{playing computer}. A table like the one
above is an organized way to keep track.

The line numbering is not very exciting in a simple sequential program,
but it will become very important when we get to other execution sequences.
We start with the simple sequential numbering now for consistency, as
we get used to the idea of such a table following execution sequence.

\index{playing computer!exercise}\index{exercise!playing computer}

\subsubsection{Play Computer Exercise}
\label{data_programstructure:index-5}\label{data_programstructure:play-computer-exercise}\label{data_programstructure:playing-computer-exercise}
Here is a similar program,
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/update\_vars2/update\_vars2.cs}{update\_vars2/update\_vars2.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{UpdateVars2}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}} \PYG{c+c1}{// for first Playing Computer Exercise}
      \PYG{k+kt}{int} \PYG{n}{a} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}     
      \PYG{k+kt}{int} \PYG{n}{b} \PYG{p}{=} \PYG{l+m}{2} \PYG{p}{*} \PYG{n}{a}\PYG{p}{;}
      \PYG{n}{a} \PYG{p}{=} \PYG{n}{a} \PYG{p}{*} \PYG{n}{b}\PYG{p}{;}       
      \PYG{n}{b} \PYG{p}{=} \PYG{n}{a} \PYG{p}{\PYGZhy{}} \PYG{n}{b}\PYG{p}{;}  
      \PYG{n}{a} \PYG{p}{=} \PYG{n}{a} \PYG{p}{+} \PYG{n}{b}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{n}{a} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}:\PYGZdq{}} \PYG{p}{+} \PYG{n}{b}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Play computer, completing the table

\begin{tabulary}{\linewidth}{|L|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
a
} & \textsf{\relax 
b
} & \textsf{\relax 
Comment
}\\
\hline
5
 & 
-
 & 
-
 & 
Start at beginning of Main
\\
\hline
7
 & 
5
 & 
-
 & 
initialize a
\\
\hline
8
 &  &  & \\
\hline
9
 &  &  & \\
\hline
10
 &  &  & \\
\hline
11
 &  &  & \\
\hline
12
 &  &  & \\
\hline\end{tabulary}



\subsubsection{Another Play Computer Exercise}
\label{data_programstructure:another-play-computer-exercise}
A silly one on the same line:
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/update\_vars3/update\_vars3.cs}{update\_vars3/update\_vars3.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{UpdateVars3}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}} \PYG{c+c1}{// another sequentail Playing Computer Exercise}
      \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}a\PYGZdq{}}\PYG{p}{;}     
      \PYG{k+kt}{string} \PYG{n}{t} \PYG{p}{=} \PYG{n}{s} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}n\PYGZdq{}}\PYG{p}{;}
      \PYG{n}{s} \PYG{p}{=} \PYG{n}{t} \PYG{p}{+} \PYG{n}{s}\PYG{p}{;}       
      \PYG{n}{t} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}b\PYGZdq{}} \PYG{p}{+} \PYG{n}{t}\PYG{p}{;}  
      \PYG{n}{s} \PYG{p}{=} \PYG{n}{t} \PYG{p}{+} \PYG{n}{s}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{n}{s} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}} \PYG{p}{+} \PYG{n}{t}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Play computer, completing the table

\begin{tabulary}{\linewidth}{|L|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
s
} & \textsf{\relax 
t
} & \textsf{\relax 
Comment
}\\
\hline
5
 & 
-
 & 
-
 & 
Start at beginning of Main
\\
\hline
7
 &  &  & \\
\hline
8
 &  &  & \\
\hline
9
 &  &  & \\
\hline
10
 &  &  & \\
\hline
11
 &  &  & \\
\hline
12
 &  &  & \\
\hline\end{tabulary}



\section{Combining Input and Output}
\label{data_io:combining-input-and-output}\label{data_io::doc}\label{data_io:io}
\index{Console!ReadLine}\index{ReadLine!Console}

\subsection{Reading from the Keyboard}
\label{data_io:index-0}\label{data_io:read-from-console}\label{data_io:reading-from-the-keyboard}
If you want users to type something at the keyboard, you should let them know first!
The jargon for this is to give them a \emph{prompt}:  Instructions written to the screen,
something like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter your name: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

Then the user should respond.
What the user types is automatically shown (\emph{echoed})
in the terminal or console window.  For a program to
read what is typed, another function in the \code{Console} class is used:
\code{Console.ReadLine}.

Here the data for the function comes from a line typed at the keyboard by the user,
so there is no need for a parameter between
the parentheses: \code{Console.ReadLine()}.
The resulting sequence of characters,
typed before the user presses the Enter (Return) key,
form the string \emph{value} of the function.
Syntactically in C\#,
when a function with a value is used, it is an \emph{expression} in the
program, and the
expression evaluation is the value produced by the function.
This is the same as in normal use of functions in math.

With any function producing a value,
the value is \emph{lost} unless it is \emph{immediately} used.
Often this is done by immediately assigning the value to a variable like in

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{name}\PYG{p}{;}
\PYG{n}{name} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

or in the shorter

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{name} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\index{Console!ReadKey}\index{ReadKey}
Fine point:  Notice that in most operating systems you can edit and correct your line
before pressing the Return key.  This is handy,
but it means that the Return key \emph{must} always be pressed to signal the end
of the response.
Hence a whole line must be read, and there is \emph{no} function \code{Console.Read()}.
Just for completeness we mention that you can read a raw single keystroke immediately
(no editing beforehand).  If you want to explore that later, see
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/test\_readkey/test\_readkey.cs}{test\_readkey/test\_readkey.cs}.

\index{string!Parse to int or double}\index{Parse int and double}\index{int!Parse}\index{double!Parse}

\subsection{Numbers and Strings of Digits}
\label{data_io:numbers-and-strings-of-digits}\label{data_io:index-2}\label{data_io:numbers-and-digit-strings}
You may well want to have the user supply you with numbers.
There is a complication.  Suppose you want to get numbers and add them.
What happens with this code, in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/bad\_sum/bad\_sum.cs}{bad\_sum/bad\_sum.cs}?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;} 

\PYG{k}{class} \PYG{n+nc}{BadSum} 
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{,} \PYG{n}{t}\PYG{p}{,} \PYG{n}{sum}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write} \PYG{p}{(} \PYG{l+s}{\PYGZdq{}Enter an integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{s} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(} \PYG{l+s}{\PYGZdq{}Enter another integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{t} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{sum} \PYG{p}{=} \PYG{n}{s} \PYG{p}{+} \PYG{n}{t}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}They add up to \PYGZdq{}} \PYG{p}{+} \PYG{n}{sum}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Here is a sample run:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Enter an integer: 23
Enter another integer: 9
They add up to 239
\end{Verbatim}

C\# has a type for everything and
\code{Console.ReadLine()} gives you a string.
Adding strings with \code{+} is not the same as adding numbers!

We must explicitly convert the strings to the proper kind of number.
There are functions to do that:  \code{int.Parse} takes a string parameter
that should be the characters in an \code{int}, like ``123'' or ``-25'', and
produces the corresponding \code{int} value, like 123 or -25.
In \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/good\_sum/good\_sum.cs}{good\_sum/good\_sum.cs}, we changed the names to emphasize the type
conversions:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;} 

\PYG{k}{class} \PYG{n+nc}{GoodSum} 
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write} \PYG{p}{(} \PYG{l+s}{\PYGZdq{}Enter an integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{k+kt}{string} \PYG{n}{xString} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{xString}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(} \PYG{l+s}{\PYGZdq{}Enter another integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{k+kt}{string} \PYG{n}{yString} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{k+kt}{int} \PYG{n}{y} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{yString}\PYG{p}{)}\PYG{p}{;}
      \PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{n}{y}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}They add up to \PYGZdq{}} \PYG{p}{+} \PYG{n}{sum}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Notice that the values calculated by \code{int.Parse} for the strings
\code{xString} and \code{yString} are immediately remembered in
assignment statements.  Be careful of the distinction here.
The \code{int.Parse} function does not magically \emph{change}
the variable \code{xString} into an \code{int}:  the string \code{xString} is unchanged,
but the corresponding \code{int} value is calculated,
and gets assigned to an \code{int} variable, \code{x}.

Note that this would not work if the string represents the wrong kind of number,
but there is an alternative:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} string s = \PYGZdq{}34.5\PYGZdq{};
csharp\PYGZgt{} int.Parse(s);
System.FormatException: Input string was not in the correct format ....
csharp\PYGZgt{} double.Parse(s);
34.5
\end{Verbatim}

We omitted the long tail of the error message.
There is no decimal point in an \code{int}.
You see the fix with the corresponding function that returns a double.


\subsection{Example Projects and the Source Repository}
\label{data_io:example-projects-and-the-source-repository}
We have started to refer to whole programs that we have written.  You will
want to have your own copies to test and modify for related work.

All of our examples are set up in a Xamarin Studio solution in our
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/archive/master.zip}{zip file that you can download}.

The zip file and the folder it unzips to have the long name
introcs-csharp-examples-master.  We suggest you \emph{rename the folder} simply
\code{examples} to match the name of the Xamarin Studio solution it contains.

There are various way to access our files.
\begin{enumerate}
\item {} 
One way is to look at individual files from your download
under our examples directory.

\item {} 
If you open the examples solution in Xamarin Studio,
you can select files from the Solutions pad.
(Instructions are in the next section.)

\item {} 
In the notes we refer to individual code file names that are hyperlinked.
They link to the \emph{latest version} in our online source repository.
You get a display of color-coded web page with numbered lines.  If you
want to adapt a chunk, you can select it, and copy.
If you want to copy all of a large file, your editing shortcuts
for Select All do \emph{not} work:  You get a bunch of extra html.
An alternative is to click the \textbf{Raw} button in the web page
to the left above the source code.
That brings up a plain text page with just the code.
You can either download it or select all of it, and you
\emph{only} get the code.

\end{enumerate}

We have one main convention in naming our projects:  Most projects are
examples of full, functional programs to run.  Others are intended to be
copied by you as \emph{stubs} for your solutions, for you to elaborate.
These project folders all end with
``\_stub'', like \code{string\_manip\_stub}.  Even the stubs can be compiled
immediately, though they may not accomplish anything.

\index{chunk in source comments}
A further convention is using ``chunk'' comments inside example source files:
To keep the book and the source code in sync, our
\href{http://sphinx-doc.org/}{Sphinx}
building routine directly uses excerpts from
the exact source code that is in the
examples download.  We have to mark the limits of the excerpts that we want
for the book.
Our convention is to have a comment referring to the beginning or the
end of an excerpt ``chunk''.
Hence a comment including ``chunk'' in a source file is
\emph{not} intended as commentary on the code, but merely a marker for
automatically regenerating a revision of the book.


\subsection{Running our Xamarin Studio Examples Solution}
\label{data_io:our-md-projects}\label{data_io:running-our-xamarin-studio-examples-solution}
If you are just starting Xamarin Studio, and you have \emph{not} run our solution before:
\begin{enumerate}
\item {} 
On the Welcome screen select the button Open Solution or File.

\item {} 
You get an open-file dialog.  Navigate to our example solution.
(It must be unzipped already!  We assume you renamed the folder \emph{examples}.)

\item {} 
Select \code{examples/examples.sln}.

\end{enumerate}

The next time you come to the Welcome screen, our examples should be listed in the
Recent Projects, and you can click to open it directly.


\subsection{Copying and Modifying Our Example Xamarin Studio Projects}
\label{data_io:copying-and-modifying-our-example-xamarin-studio-projects}
We strongly encourage you \emph{not} to modify our examples in place, if you want
to keep the changes, because we will make additions and modifications to
our source download, and we would not want you to overwrite any of
your modified files after downloading a later version of the examples.

If you do want to alter our code, we suggest you copy it to a project in your
solution (``work'', discussed in the first lab in the {\hyperref[data_lab-edit-compile-run:steps]{\emph{Steps}}}).
\begin{enumerate}
\item {} 
Open your solution.

\item {} 
Create a new project, maybe with the same name as the one we had.  If it was a
``\_stub'' project, remove the ``\_stub'' from your project's name.

\item {} 
In the Solution Pad open the menu on the new project, select, Add, and then in the
further submenu, select Add Files....

\item {} 
This brings up an operating system open-file dialog.  Switch folders into our
example projects.  Select the files you want to copy.
(It makes things easier if you put the examples folder
right beside your work folder.)

\item {} 
A further dialog window pops up, with the choice \textbf{Copy} selected.
Click to approve copy (as opposed to move or link).

\item {} 
Now the desired files should appear in your project,
along with the unfortunate default Program.cs.  If you have not already
deleted Program.cs, as described in {\hyperref[data_lab-edit-compile-run:steps]{\emph{Steps}}}, do it now.

\item {} 
If you intended to copy everything for a project, test by running the project.
Even our stub projects should compile, though a stub project may not do anything
when you run it until you add your own code to it.  To make successful incremental
additions, it is always good to start from something that compiles!

\end{enumerate}

When creating modifications of previous examples, like the exercise below,
you can often save time by copying in the related example, particularly avoiding
retyping the standard boiler plate code at the top.  However, when you are first
learning and getting used to new syntax, typing reinforces learning.
Perhaps after looking over the related example, you are encouraged to write your
version from scratch, to get used to all the parts of the code.  Later, when
you can produce such text automatically, feel free to switch to just
copying from a place that you had it before.


\subsubsection{Interview Exercise/Example}
\label{data_io:interviewproblem}\label{data_io:interview-exercise-example}
Write a program that prompts the user for a name (like Elliot)  and a time
(like 10AM) and prints out a sentence like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Elliot has an interview at 10AM.
\end{Verbatim}

If you are having a hard time and want a further example,
or want to compare to your work,
see our solution, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/interview/interview.cs}{interview/interview.cs}.


\subsubsection{Exercise for Addition}
\label{data_io:additionproblem}\label{data_io:exercise-for-addition}
Write a version, \code{add3.cs}, that
prompts the user for three numbers, \emph{not necessarily integers},
and lists all three, and their sum, in
similar format to \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/good\_sum/good\_sum.cs}{good\_sum/good\_sum.cs}.


\subsubsection{Exercise for Quotients}
\label{data_io:quotientproblem}\label{data_io:exercise-for-quotients}
Write a program, \code{quotient.cs}, that
prompts the user for two integers, and then prints them out in a
sentence with an integer division problem like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
The quotient of 14 and 3 is 4 with a remainder of 2.
\end{Verbatim}

Review {\hyperref[data_arithmetic:division-and-remainders]{\emph{Division and Remainders}}} if you forget the integer
division or remainder operator.


\section{String Special Cases}
\label{data_strings2:strings2}\label{data_strings2::doc}\label{data_strings2:string-special-cases}
\index{escape code \textbackslash{}}\index{\textbackslash{} as character escape code}\index{character escape code \textbackslash{}}
There are some special cases for creating literal strings.
For instance you might want quotes
as characters inside your string.  In this case you need special
symbolism using a character \emph{escape code}, starting with  \code{\textbackslash{}} backslash.
Then the character after the backslash has a special meaning.

For instance a quote character after a backslash, \code{\textbackslash{}"},
does not mean the end of a string literal.  It means a quote character
is literally used \emph{in} the string:  \code{"He said, \textbackslash{}"Hello!\textbackslash{}", over and over."}

We can illustrate with csharp, first with a simple string:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} Console.WriteLine(\PYGZdq{}Hello world!\PYGZdq{});
Hello world!
csharp\PYGZgt{} Console.WriteLine(\PYGZdq{}He said, \PYGZbs{}\PYGZdq{}Hello!\PYGZbs{}\PYGZdq{}, over and over.\PYGZdq{});
He said, \PYGZdq{}Hello!\PYGZdq{}, over and over.
\end{Verbatim}

There are many other special cases of escape code.  The main ones
you are likely to use are:

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Escape code
} & \textsf{\relax 
Meaning
}\\
\hline
\code{\textbackslash{}"}
 & 
\code{"} (quote)
\\
\hline
\code{\textbackslash{}'}
 & 
\code{'} ( single quote in char literal)
\\
\hline
\code{\textbackslash{}\textbackslash{}}
 & 
\code{\textbackslash{}} (backslash)
\\
\hline
\code{\textbackslash{}n}
 & 
newline
\\
\hline\end{tabulary}


Hence if you really want a backslash character in a literal,
you need to write two of them.

The newline character indicates further text will appear on the next line down
when \emph{printed} with the \code{Console.WriteLine} function.

Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} Console.WriteLine(\PYGZdq{}Windows path: c:\PYGZbs{}\PYGZbs{}Users\PYGZbs{}\PYGZbs{}aharrin\PYGZdq{});
Windows path: c:\PYGZbs{}Users\PYGZbs{}aharrin
csharp\PYGZgt{} Console.WriteLine(\PYGZdq{}a\PYGZbs{}nbc\PYGZbs{}n\PYGZbs{}ndef\PYGZdq{})
a
bc

def
\end{Verbatim}

\index{string!@}\index{@ string literal}\index{verbatim string with @}
Literal strings that are simply delimited by quotes \code{"}
must start and end on the same line.
There is also a notation for \emph{@-quoting}, with an at-sign \code{@} before the first
quote.  In an @-quoted string, all characters are treated verbatim, including
all backslashes.  Also the string may go on for several lines, and all newlines
are included literally.  (The csharp program does not recognize
multi-line @-quoted strings.)
This fragment in a program would produce the same output as the statements in
the csharp example above:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
       \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{@\PYGZdq{}Windows path: c:\PYGZbs{}Users\PYGZbs{}aharrin\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
       \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{@\PYGZdq{}a}
\PYG{l+s}{bc}

\PYG{l+s}{def\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

The only thing this example does not show off well is the amount of
left margin indentation.
That is significant in a multiline @-quoted string.
A whole simple program with this code is in example
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/at\_sign\_strings/at\_sign\_strings.cs}{at\_sign\_strings/at\_sign\_strings.cs}.

\index{csharp!verbatim string display}
Caution:  When you give csharp an expression evaluating to a string at the
prompt, you get back a verbatim string with \emph{quotes added around it},
but no \code{@} to remind you that it is verbatim:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} \PYGZdq{}Windows path: c:\PYGZbs{}\PYGZbs{}Users\PYGZbs{}\PYGZbs{}aharrin\PYGZdq{}
\PYGZdq{}Windows path: c:\PYGZbs{}Users\PYGZbs{}aharrin\PYGZdq{}
csharp\PYGZgt{} \PYGZdq{}a\PYGZbs{}nbc\PYGZbs{}n\PYGZbs{}ndef\PYGZdq{}
\PYGZdq{}a
bc

def\PYGZdq{}
\end{Verbatim}


\subsection{Multiline String Exercise}
\label{data_strings2:multiline-string-exercise}\begin{enumerate}
\item {} 
Write a statement that initializes a string \code{s} with a \textbf{single}
string literal that, when printed, shows something on one line then three
empty lines, and then a final line with text.

\item {} 
Declare the same string with a different string literal expression, that
produces the same string.  (Just one of your literals should start
with \code{@}.)

\end{enumerate}


\section{Substitutions in Console.WriteLine}
\label{data_writeline-substitution:substitutions-in-console-writeline}\label{data_writeline-substitution:substitution-in-writeline}\label{data_writeline-substitution::doc}

\subsection{Output With \texttt{+}}
\label{data_writeline-substitution:output-with}
An elaboration of a ``Hello, World'' program, could greet the user,
after obtaining the user's name.  If the user enters the name
Elliot, the program could print
\begin{quote}

Hello, Elliot!
\end{quote}

This is a very simple
input-process-output program (in fact with almost no ``process'').
Think how would you code it.

You need to obtain a name, remember it and use it in your output.
A solution is in the next section.

\index{WriteLine!\{ \} for format}\index{\{ \} !Format}

\subsection{String Format Operation}
\label{data_writeline-substitution:index-0}\label{data_writeline-substitution:string-format-operation}\label{data_writeline-substitution:format-strings}
A common convention is fill-in-the blanks. For instance,
\begin{quote}

Hello, \_\_\_\_\_!
\end{quote}

and you can fill in the name of the person greeted, and combine
given text with a chosen insertion. C\# has a similar
construction, better called fill-in-the-braces,
that can be used with \code{Console.WriteLine}.

Instead of inserting user input with the \code{+} operation as in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/hello\_you1/hello\_you1.cs}{hello\_you1/hello\_you1.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{HelloYou1}
\PYG{p}{\PYGZob{}}
    \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main} \PYG{p}{(}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}   
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}What is your name?\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
        \PYG{k+kt}{string} \PYG{n}{name} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Hello, \PYGZdq{}} \PYG{p}{+} \PYG{n}{name} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}

\PYG{p}{\PYGZcb{}}
\end{Verbatim}

look at a variation, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/hello\_you2/hello\_you2.cs}{hello\_you2/hello\_you2.cs}, shown below.
Both programs
look exactly the same to the user:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{HelloYou}
\PYG{p}{\PYGZob{}}
    \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main} \PYG{p}{(}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}   
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}What is your name?\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
        \PYG{k+kt}{string} \PYG{n}{name} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Hello, \PYGZob{}0\PYGZcb{}!\PYGZdq{}}\PYG{p}{,} \PYG{n}{name}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}

\PYG{p}{\PYGZcb{}}
\end{Verbatim}

All the new syntax is in the line:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Hello, \PYGZob{}0\PYGZcb{}!\PYGZdq{}}\PYG{p}{,} \PYG{n}{name}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\code{Console.WriteLine} actually can take parameters \emph{after} an initial string,
but only when  the string is in the form of a \emph{format string},
with expression(s) in braces where substitutions are to be made,
(like in fill-in-the-blanks). Here the format string is \code{"Hello, \{0\}!"}.

The remaining parameters, after the initial string,
give the values to be substituted.  To
know \emph{which} further parameter to substitute, the parameters after the
initial string are implicitly numbered,
\emph{starting from 0}.
Starting with 0 is consistent with other numbering sequences in C\#.
So here, where there is just one value to substitute (\code{name}), it gets the index 0,
and where it is substituted, the braces get 0 inside, to indicate
that parameter with index 0 is to be substituted.

Everything in the initial string that is \emph{outside} the braces is just
\emph{repeated verbatim}.  In particular, if the only parameter is a string
with no braces, it is printed completely
verbatim (reducing to the situations where we have used \code{Console.WriteLine} before).

A more elaborate silly examples that you could test in csharp would be:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{first} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Peter\PYGZdq{}}\PYG{p}{;}
\PYG{k+kt}{string} \PYG{n}{last} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Piper\PYGZdq{}}\PYG{p}{;}
\PYG{k+kt}{string} \PYG{n}{what} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}pick\PYGZdq{}}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} \PYGZob{}1\PYGZcb{}, \PYGZob{}0\PYGZcb{} \PYGZob{}1\PYGZcb{}, \PYGZob{}2\PYGZcb{}.\PYGZdq{}}\PYG{p}{,} \PYG{n}{first}\PYG{p}{,} \PYG{n}{last}\PYG{p}{,} \PYG{n}{what}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

It would print:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Peter} \PYG{n}{Piper}\PYG{p}{,} \PYG{n}{Peter} \PYG{n}{Piper}\PYG{p}{,} \PYG{n}{pick}\PYG{p}{.}
\end{Verbatim}

where parameter 0 is \code{first} (value \code{"Peter"}),
parameter 1 is \code{last} ( value \code{"Piper"}), and
parameter 2 is \code{what} (value \code{"pick"}).

Make sure you see why the given output is exactly what is printed.

Or try in csharp:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{7}\PYG{p}{;}
\PYG{k+kt}{int} \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} plus \PYGZob{}1\PYGZcb{} is \PYGZob{}2\PYGZcb{}; \PYGZob{}0\PYGZcb{} times \PYGZob{}1\PYGZcb{} is \PYGZob{}3\PYGZcb{}.\PYGZdq{}}\PYG{p}{,} \PYG{n}{x}\PYG{p}{,} \PYG{n}{y}\PYG{p}{,} \PYG{n}{x}\PYG{p}{+}\PYG{n}{y}\PYG{p}{,} \PYG{n}{x}\PYG{p}{*}\PYG{n}{y}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

and see it print:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
7 plus 5 is 12; 7 times 5 is 35.
\end{Verbatim}

Note the following features of the parameters after the first string:
\begin{itemize}
\item {} 
These parameters can be any expression,
and the expressions get evaluated before printing.

\item {} 
These parameters to be substituted can be of any type.

\item {} 
These parameters are automatically converted to a string form, just as in the
use of the string \code{+} operation.

\end{itemize}

In fact the simple use of format strings
shown so far can be completed replaced by long expressions with \code{+},
if that is your taste.  We later discusses fancier formatting in {\hyperref[forexamples:tables]{\emph{Tables}}},
that \emph{cannot} be duplicated with a simple string \code{+} operation.
We will use the simple numbered substitutions for now just
to get used to the idea of substitution.

\index{format!literal \{\}}
A technical point: Since braces have special meaning in a format
string, there must be a special rule if you want braces to actually
be included in the final \emph{formatted} string. The rule is to double
the braces: \code{"\{\{"} and \code{"\}\}"}. The fragment

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{a} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{,} \PYG{n}{b} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}The set is \PYGZob{}\PYGZob{}\PYGZob{}0\PYGZcb{}, \PYGZob{}1\PYGZcb{}\PYGZcb{}\PYGZcb{}.\PYGZdq{}}\PYG{p}{,} \PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

produces

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
The set is \PYGZob{}2, 3\PYGZcb{}.
\end{Verbatim}


\subsubsection{Format Reading Exercise}
\label{data_writeline-substitution:format-reading-exercise}
What is printed?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{}\PYGZob{}1\PYGZcb{}\PYGZob{}1\PYGZcb{}\PYGZob{}2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}Mi\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}ssi\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}ppi\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

Check yourself.


\subsubsection{Exercise for Format}
\label{data_writeline-substitution:quotientformat}\label{data_writeline-substitution:exercise-for-format}
Write a program, \code{quotient\_format.cs}, that behaves like
{\hyperref[data_io:quotientproblem]{\emph{Exercise for Quotients}}}, but generate the sentence using
\code{Console.WriteLine} with a format string and no \code{+} operator.


\subsubsection{Madlib Exercise}
\label{data_writeline-substitution:madlib-exercise}
Write a program, \code{my\_mad\_lib.cs}, that prompts the user for
words that fit specified gramatical patterns ( a noun, a verb, a color,
a city....) and plug them into a multiline format string so they fit
grammatically, and
print the usually silly result.
If you are not used to mad libs, try running (not
looking at the source code) the example project mad\_lib, and then try it
again with different data.
If this exercise seems like too big of a challenge yet,
see our example source code,
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/mad\_lib/mad\_lib.cs}{mad\_lib/mad\_lib.cs}, and then \emph{start over} on your own.

\index{method!overloading}\index{overloading!methods}

\subsection{Overloading}
\label{data_writeline-substitution:overloading}\label{data_writeline-substitution:index-2}\label{data_writeline-substitution:id1}
The \code{WriteLine} function can take parameters in different ways:
\begin{itemize}
\item {} 
It can take a single parameter of an type (and print its string representation).

\item {} 
It can take a string parameter followed by any number of parameters used to
substitute into the initial format string.

\item {} 
It can take no parameters, and just advance to the next line (not used yet in
this book).

\end{itemize}

Though each of these uses has the same name, \code{Console.WriteLine},
they are technically all different functions:  A function is not just recognized
by its name, but by its \emph{signature},
which includes the name \textbf{and} the number and types of parameters.
The technical term for using the same name with different signatures for different
functions is \emph{overloading} the function (or method).

This only makes practical sense for a group of closely related functions, where the
use of the same name is more helpful than confusing.

\index{type!value}\index{value type}

\section{Value Types and Conversions}
\label{data_types-and-conversions:value-types}\label{data_types-and-conversions:index-0}\label{data_types-and-conversions::doc}\label{data_types-and-conversions:value-types-and-conversions}
\index{int!value range}\index{type!int}\index{overflow}

\subsection{Type int}
\label{data_types-and-conversions:type-int}\label{data_types-and-conversions:index-1}\label{data_types-and-conversions:id1}
A variable is
associated with a space in memory.  This space has a fixed size associated with the type
of data.
The \code{int} and \code{double} types are examples of \emph{value types},
which means that this memory space holds an encoding of the complete data for the
value of the variable.  The fixed space means that an \code{int} cannot be a totally
arbitrary integer of an enormous size.  In fact an \code{int} variable can only hold
an integer in a specific range.  See {\hyperref[context_computerscience:data-representation]{\emph{Data Representation}}} for the
general format of the underlying encoding in bits.

An \code{int} is held in a memory space of 32 bits, so it can have at
most \(2^{32}\) values, and the encoding is chosen so about half are positive and
half are negative: An \code{int} has maximum value \(2^{31} - 1 = 2147483647\) and
a minimum value of \(-2^{31} = -2147483648\).  The extreme values are also
named constants in C\#, \code{int.MaxValue} and \code{int.MinValue}.

In particular this means \code{int} arithmetic does not always work.  What is worse,
it fails \emph{silently}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} int i = int.MaxValue;
csharp\PYGZgt{} i;
2147483647
csharp\PYGZgt{} i + 5;
\PYGZhy{}2147483644
\end{Verbatim}

Add two positive numbers and get a negative number!  Getting such a wrong
answer is called \emph{overflow}.
Be very careful if you are
going to be using big numbers!  Note: with addition,
overflow will give the wrong sign,
but the sign may not give such a clue
if another operation overflows, like multiplication.

\index{type!long}\index{long type}\index{short type}\index{byte type}

\subsection{Type long}
\label{data_types-and-conversions:type-long}\label{data_types-and-conversions:id2}\label{data_types-and-conversions:index-2}
Most everyday uses of integers fit in this range of an \code{int},
and many modern computers are designed
to operate on an \code{int} very efficiently, but sometimes you need a
larger range.  Type \emph{long} uses twice as much space.

The same kind of silent overflow errors happen with \code{long} arithmetic, but only
with much larger numbers.

When we get to {\hyperref[arrays:array]{\emph{Arrays}}}, you will see that a program may store
an enormous number of integers, and then the total space may be an
issue.  If some numbers fit in a \code{long}, but not an \code{int},
\code{long} must be used, taking us twice the space of an array of \code{int}
elements.  If all the integers have even more limited ranges,
they might be stored in the smaller space of a \code{short}
or a \code{byte}.
We will not further discuss or use types \code{short} or \code{byte} in this book.
Here we will only use the integral types \code{int} and \code{long}.

\index{type!double}\index{double type}\index{precision}\index{float type}\index{type!float}

\subsection{Type double}
\label{data_types-and-conversions:id3}\label{data_types-and-conversions:type-double}\label{data_types-and-conversions:index-3}
A \code{double} is also a value type, stored in a fixed sized space.  There are
even more issues with \code{double} storage than with an \code{int}:  Not only do you need
to worry about the total magnitude of the number, you also need to choose
a \emph{precision}:  There are an infinite number of real values, just between 0 and 1.
Clearly we cannot encode for all of them!  As a result a \code{double} has a limited
number of digits of accuracy.  There is also an older type \code{float} that takes up
half of the space of a \code{double}, and has a smaller range and less accuracy.  This at
least gives a reason for the name \code{double}:  double the storage space of a \code{float}.

To avoid a ridiculously large number of
trailing 0's, a big double literal can be
expressed using a variant of scientific notation:
\begin{quote}

\code{1.79769313486232E+308} means \(1.7976931348623157(10^{308})\)
\end{quote}

C\# does not have the typography for raised exponents.  Instead
literal values can use the E to mean
``times 10 to the power'', and the E is followed by and exponent integer
that can be positive or negative.
The whole double literal may not contain any embedded blanks.  Internally
these numbers are stored with powers of 2, not 10:  See
{\hyperref[context_computerscience:data-representation]{\emph{Data Representation}}}.

Arithmetic with the \code{double} type does not overflow silently as with
the integral types.
We show behavior that could be important if you do scientific computing
with enormous numbers:  There are values for Infinity and Not a Number,
abbreviated NaN.  See them used in csharp:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} double x = double.MaxValue;
csharp\PYGZgt{} x;
1.79769313486232E+308
csharp\PYGZgt{} double y = 10 * x;
csharp\PYGZgt{} y;
Infinity
csharp\PYGZgt{} y  + 1000;
Infinity
csharp\PYGZgt{} y  \PYGZhy{} 1000;
Infinity
csharp\PYGZgt{} 1000/y;
0
csharp\PYGZgt{} double z = 10 \PYGZhy{} y;
csharp\PYGZgt{} z;
\PYGZhy{}Infinity
csharp\PYGZgt{} double sum = y + z;
csharp\PYGZgt{} sum;
NaN
csharp\PYGZgt{} sum/1000;
NaN
\end{Verbatim}

Once a result gets too big, it gets listed as infinity.
As you can see,
there is some arithmetic allowed with a finite number and infinity!
Still some operations are not legal.
Once a result turns into \code{NaN}, no arithmetic operations change
further results away from \code{NaN},
so there is a lasting record of a big error!

Note that Infinity, -Infinity and NaN are just representations when displayed
as strings.  The numerical constants are
\code{Double.PositiveInfinity}, \code{Double.NegativeInfinity}, and \code{Double.NaN}.

\begin{notice}{warning}{Warning:}
There is no such neat system for showing off small inaccuracies in \code{double}
arithmetic accumulating
due to limited precision.  These inaccuracies \emph{still} happen silently.
\end{notice}

\index{numeric type range}\index{range of numeric types}\index{byte type}\index{short type}\index{type!byte and short}

\subsection{Numeric Types and  Limits}
\label{data_types-and-conversions:index-4}\label{data_types-and-conversions:numeric-types-and-limits}\label{data_types-and-conversions:numeric-type-limits}
The listing below shows how the storage size in bits translates into the limits
for various numerical types.  We will not discuss or use \code{short},
\code{byte} or \code{float} further.
\begin{description}
\item[{long}] \leavevmode
64 bits; range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

\item[{int}] \leavevmode
32 bits; range -2,147,483,648 to 2,147,483,647

\item[{short}] \leavevmode
16 bits; range -32,768 to 32,767

\item[{byte}] \leavevmode
8 bits; range 0 to 255 (no negative values)

\item[{double}] \leavevmode
64 bits; maximum magnitude: \(1.7976931348623157(10^{308})\);
about 15 digits of accuracy

\item[{float}] \leavevmode
32 bits; maximum magnitude: \(3.402823(10^{38})\); about 7 digits of accuracy

\item[{decimal}] \leavevmode
128 bits; maximum value: 79228162514264337593543950335;
28 digits of accuracy;  can exactly represents decimal values
for financial operations; briefly discussed in \emph{optional}
{\hyperref[overload-op:decimal-type]{\emph{Decimal Type}}}.

\item[{char}] \leavevmode
See {\hyperref[data_types-and-conversions:integer-char]{\emph{char as integer}}}.

\end{description}

\index{cast}

\subsection{Casting}
\label{data_types-and-conversions:cast}\label{data_types-and-conversions:casting}\label{data_types-and-conversions:index-5}
While the mathematical ideas of 42 and 42.0 are the same, C\# has specific types.
There are various places where numerical types get converted automatically by C\#
or explicitly by the programmer.
A major issue is whether the new type can accurately represent the original value.

Going from \code{int} to \code{double} has no issue:  Any \code{int} can be exactly
represented as a \code{double}.  Code like the following is fine:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} int i = 33;
csharp\PYGZgt{} double d = i;
csharp\PYGZgt{} double x;
csharp\PYGZgt{} x = 11;
csharp\PYGZgt{} double z = i + 2.5;
csharp\PYGZgt{} ShowVars();
int i = 33
double d = 33
double x = 11
double z = 35.5
\end{Verbatim}

The \code{double} variable \code{d} is initialized with the value of an \code{int} variable.
The \code{double} variable \code{x} is assigned a value using an \code{int} literal.
The \code{double} variable \code{z} is initialized with the value of a sum involving
both an \code{int} variable and a \code{double} literal.  As we have discussed before in
{\hyperref[data_arithmetic:arithmetic]{\emph{Arithmetic}}}, the \code{int} is converted to a \code{double} before the addition
operation is done.

The other direction for conversion is more problematic:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} double d= 2.7;
csharp\PYGZgt{} int i;
csharp\PYGZgt{} i = d;
\PYGZob{}interactive\PYGZcb{}(1,4): error CS0266: Cannot implicitly convert type \PYGZsq{}double\PYGZsq{} to \PYGZsq{}int\PYGZsq{}.
An explicit conversion exists (are you missing a cast?)
\end{Verbatim}

The \code{int} \code{i} cannot accurately hold the value 2.7.
Since the compiler does this checking, looking only at types, not values, this even
fails if the the \code{double} happens to have an integer value:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} double d = 2.0;
csharp\PYGZgt{} int i = d;
\PYGZob{}interactive\PYGZcb{}(1,4): error CS0266: Cannot implicitly convert type \PYGZsq{}double\PYGZsq{} to \PYGZsq{}int\PYGZsq{}.
An explicit conversion exists (are you missing a cast?)
\end{Verbatim}

\index{truncate in cast}
If you really want to possibly lose precision and convert a \code{double} to
an \code{int} result, you \emph{can} do it, but you must be explicit, using a \emph{cast}
as the csharp error messages suggest.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} double d= 2.7;
csharp\PYGZgt{} int i;
csharp\PYGZgt{} i = (int)d;
csharp\PYGZgt{} i;
2
\end{Verbatim}

The desired result type name in parentheses \code{(int)} is a \emph{cast}, telling the compiler
you really intend the conversion.  Look what is lost!  The cast does not
\emph{round} to the nearest integer, it \emph{truncates} toward 0, dropping the fractional
part, .7 here.

\index{Round function}
Rounding is possible, but if you really want the \code{int} type, it takes two steps,
because the function \code{Math.Round} does round to a mathematical integer, but leaves
the type as \code{double}!  To round \code{d} to an \code{int} result we could use:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} i = (int)Math.Round(d);
csharp\PYGZgt{} i;
3
\end{Verbatim}

You can also use an explicit cast from int to double.  This is generally not needed,
because of the automatic conversions, but there is one place where it is
important:  if you want \code{double} division but have \code{int} parts.  Here is a
quick artificial test:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} int sum = 14;
csharp\PYGZgt{} int n = 4;
csharp\PYGZgt{} double avg = sum/n;
csharp\PYGZgt{} avg;
3
\end{Verbatim}

Oops, integer division.  Instead, continue with:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} avg = (double)sum/n;
csharp\PYGZgt{} avg;
3.5
\end{Verbatim}

We get the right decimal answer.

This is a bit more subtle than it may appear:
The cast to double, \code{(double)}
is an operation in C\# and so it has a \emph{precedence} like all operations.  Casting
happens to have precedence higher than any arithmetic operation, so the expression is
equivalent to:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{avg} \PYG{p}{=} \PYG{p}{(}\PYG{p}{(}\PYG{k+kt}{double}\PYG{p}{)}\PYG{n}{sum}\PYG{p}{)}\PYG{p}{/}\PYG{n}{n}\PYG{p}{;}
\end{Verbatim}

On the other hand, if we switch the order the other way with parentheses around the
division:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} avg = (double)(sum/n);
csharp\PYGZgt{} avg;
3
\end{Verbatim}

then working \emph{one} step at a time, \code{(sum/n)} is \emph{integer} division,
with result 3.  It is the 3 that is then cast to a double (too late)!

See the appendix {\hyperref[precedence:precedence]{\emph{Precedence of Operators}}}, listing all C\# operations discussed in this book.

\index{type!char}\index{char}

\subsection{Type char}
\label{data_types-and-conversions:index-8}\label{data_types-and-conversions:id4}\label{data_types-and-conversions:type-char}
The type for an individual character is \code{char}.  A \code{char} literal value is
a \emph{single} character enclosed in \emph{single} quotes, like \code{'a'} or \code{'\$'}.
The literal for a
single quote character itself and the literal for a newline use
\emph{escape codes}, like in {\hyperref[data_strings2:strings2]{\emph{String Special Cases}}}:
The literals are \code{'\textbackslash{}'{'}} and \code{'\textbackslash{}n'} respectively.

Be careful to distinguish a \code{char} literal like \code{'A'}
from a string literal \code{"A"}.

\index{Unicode}\phantomsection\label{data_types-and-conversions:integer-char}
\textbf{Char as integer}:  Though the \code{char} type has character literals
and prints as a character,
internally a \code{char} is a \emph{type of integer}, stored in 16 bits,
with the correspondence
between numeric codes and characters given by the \emph{Unicode} standard.
Unicode allows special symbol characters and alphabets of many languages.
We will stick to the standard American keyboard for these characters.

Besides different alphabets, Unicode also has characters for all sorts of
symbols: emoticons, chess pieces, advanced math....  See
\href{http://www.unicode.org/charts}{http://www.unicode.org/charts}.  All the symbols can be represented as escape
codes in C\#, starting with \code{\textbackslash{}u} followed by 4 hexadecimal digits.  For example
\code{\textbackslash{}u262F} produces a yin-yang symbol.

We mention the \code{char} type being numeric mostly because of errors
that you can make that would otherwise be hard to figure out.  This code does
not concatenate the \code{char} symbols:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} Console.WriteLine(\PYGZsq{}A\PYGZsq{} + \PYGZsq{}\PYGZhy{}\PYGZsq{});
110
\end{Verbatim}

What?
We mentioned that modern computers are set up to easily work with the \code{int}
type.  In arithmetic with \emph{smaller} integral types the operands are first
automatically converted to type \code{int}.
An \code{int} sum is an \code{int}, and that is
what is printed.

You can look at the numeric values inside a \code{char} with a cast!

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} (int)\PYGZsq{}A\PYGZsq{};
65
csharp\PYGZgt{} (int)\PYGZsq{}\PYGZhy{}\PYGZsq{};
45
\end{Verbatim}

So the earlier 110 is correct:  65 + 45 = 110.

For completeness:
It is also possible to cast from small \code{int} back to \code{char}.
This may be useful for dealing with the alphabet
in sequence (or simple classical cryptographic codes):

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} \PYGZsq{}A\PYGZsq{} + 1;
66
csharp\PYGZgt{} (char)(\PYGZsq{}A\PYGZsq{} + 1);
\PYGZsq{}B\PYGZsq{}
\end{Verbatim}

The capital letter one place after A is B.

\index{type!Boolean or bool}\index{Boolean or bool}

\subsection{Type Boolean or bool}
\label{data_types-and-conversions:type-boolean}\label{data_types-and-conversions:type-boolean-or-bool}\label{data_types-and-conversions:index-10}
There is one more very important value type, that we introduce here
for completeness, though we will not use it until
{\hyperref[decisions:if-statements]{\emph{Decisions}}}.
Logical conditions are either true or false.  The type with just these
two values is \emph{Boolean}, or \emph{bool} for short.  The
type is named after George Boole, who invented what we now call
\emph{Boolean algebra}.  Though it seemed like a useless mathematical curiosity
when Boole invented it, a century later Boolean algebra turned out to be
at the heart of the implementation of computer hardware.

\begin{notice}{note}{Note:}
The Boolean literals are \code{true} and \code{false}, with \emph{no} quotes
around them.
\end{notice}

With quotes they would be of type string, not Boolean!


\subsection{Overflow to Positive Exercise}
\label{data_types-and-conversions:overflow-to-positive-exercise}
We gave an example above in {\hyperref[data_types-and-conversions:type-int]{\emph{Type int}}},
adding two positive \code{int} values and
clearly having an error, since the result was negative.  Declare
and initialize two positive \code{int} variables \code{x} and \code{y}.  Experiment
with the initializations so
\begin{enumerate}
\item {} 
Their product is too big to fit in an \code{int} AND

\item {} 
The wrong overflow result for \code{x*y} is \emph{positive}, not negative.

\end{enumerate}

\index{problem solving!strategy}

\section{Learning to Solve Problems}
\label{data_learning-to-problem-solve:learning-to-solve-problems}\label{data_learning-to-problem-solve:index-0}\label{data_learning-to-problem-solve::doc}\label{data_learning-to-problem-solve:learn-solve}
This section might have been placed earlier,
but from reading all the way to here,
you should realize that you will have a \emph{lot} of data and concepts to deal with.

The manner in which you deal with all the data and ideas is very important
for effective learning.
It might be rather different than what you needed if you were in a situation
where \emph{rote} recall is the main important thing.

Different learning styles mean different things are useful to different people.
Consider what is mentioned here and try out some approaches.

The idea of this course is \emph{not} to regurgitate the book, but to learn to solve problems
(generally involving producing a computer program).
In this highly connected and wired world
you have access to all sorts of data.  The data is not an end in itself, the question is
\emph{doing} the right things with the tools out there to solve a new creative problem.

In this course there is a lot of data tied into syntax and library function names and ....
It can seem overwhelming.  It need not be. Take a breath.

First basic language syntax:  When learning any new language, there is a lot to take in.
We introduce C\# in chunks.  For a while there will always be the new current topic coming.
You do NOT need to memorize \emph{everything} immediately!
\begin{itemize}
\item {} 
Some things that you use rarely, you may never memorize, like,
``What is the exact maximum magnitude of a \code{double}?''
At \emph{some} point that might be useful.
Can you find it?  It happens to be in {\hyperref[data_types-and-conversions:numeric-type-limits]{\emph{Numeric Types and  Limits}}}.
It is also in online .Net documentation
that you can Google or bookmark.

\item {} 
Some things you will use all the time, but of course they start off as new and maybe strange.
Knowing where to go to check is still useful but not sufficient. For much-used material
that you do not find yourself absorbing immediately,
consider writing down a summary of the current topic.
Both thinking of a summary and writing help reinforce things and get you to remember faster.
Also, if you have the current things of interest summarized in one place, they are easy to look
up!

\item {} 
If you need some syntax to solve a simple early problem,
first try to remember the syntax, then check.  With frequently
used material and with this sort of repetition,
most everyone will remember most everything shortly.  If there are a few things
that just do not stick, keep them in your list.  Then go on to new material.  The list of
what you need to check on will keep changing as you get more experience and get to more topics.
If you keep some of the old lists, you will be amazed how much stuff that you sweated over,
is later ho-hum or automatic.

\item {} 
In the earliest exercises
the general steps that you need should be pretty apparent,
and you can just concentrate on
translating simple ideas into C\# syntax
(mostly from the material most recently introduced).
In this case the focus is mostly on syntax.

\end{itemize}

Memorizing syntax is not going to directly get you to solve real problems.  In any domain:
programming, construction, organizing political action, ..., you need to analyze the problem
and figure out a sequence of steps, knowing what \emph{powers and resources you have}.

For example with political action:
if you know demonstrations are possible in front of City Hall, you can make a high-level
plan to have one, but then you have to attend to details:  Do you need city permission?
Who do you call? ... You do not have to have all that in your head when coming up with the
idea of the demonstration, but you better know how to find the information allowing you
to follow through to make it happen.

With programming, syntax details are like the details above: not the first thing to think of,
and maybe not things that you have memorized.  What \emph{is} important to break down a problem
and plan a solution, is to know the basic \emph{capacities} you have in programming.  As you get
into larger projects and have more experience, ``basic capacities'' will be bigger and bigger ideas.
For now, as beginners, based on the sections of the book so far,
it is important to know:
\begin{itemize}
\item {} 
You can get information from a user and return information via keyboard and screen.

\item {} 
You can remember and recall and use information using variables.

\item {} 
You can deal directly with various kinds of data: numbers and strings at this point.

\item {} 
There are basic operations you can do with the data (arithmetic, concatenating string,
converting between data types).

\item {} 
At a slightly higher level, you might already have the idea of basic recurring patterns,
like solving a straightforward problem with \textbf{input-processing-output}.

\item {} 
You will see shortly that you have more tools:  decision, repetition, more built-in
ways to deal with data (like more string operations shortly), creating your own data types....

\end{itemize}

At slightly more detailed level, \emph{after} thinking of overall plans:
\begin{itemize}
\item {} 
There are multiple kinds of number types.  What is appropriate for your use?

\item {} 
There are various ways of formatting and presenting data to output. What shall you use?

\end{itemize}

\emph{Finally}, you actually need to translate specific instructions into C\# (or whatever language).
Of course if you remember the syntax, then this level of step is pretty automatic.
Even if you do \emph{not} remember, you have something very specific to look up!  If you are
keeping track of your sources of detailed information, this is hopefully only one further
step.

Contrast this last-step translation with the earlier creative organizational process:
If you do not have \emph{in your head} an idea of the basic tools available,
how are you going to plan?
How are you going to even know how to start looking something up?

So far basic ideas for planning a solution has been discussed, and you can see that you do not
need to think of everything at once or have everything equally prominent in your brain.

Also, when you are coding, you do not need to to have all the details of syntax in your head,
even for the \emph{one} instruction that you are dealing with at the moment.  You want to have
the main idea, and you want to get it written down, but once it is written down, you can make
multiple passes, examining and modifying what you have.  For example, Dr. Harrington does a lot of
Python programming, where semicolons are not needed.  He can get the main ideas down
in C\# without the required
semicolons.  He \emph{could} wait for the compiler to stop him on every one that is missed,
and maybe have the compiler misinterpret further parts, and give bogus error messages.
\emph{More effective} is having
a list of things to concentrate on in later rounds of manual checking.
For example, checking for semicolons: Scan the statements;
look at the ends; add semicolons where missing.  You can go through a large program very
quickly and efficiently doing this and have one less thing to obsess about when first writing.

This list of things-to-check-separately should come from experience.
Keep track of the errors you make.  Some people even keep an error log.
What errors keep occurring?
Make entries in things-to-check-separately,
so you will make scans checking for the specific things that you frequently slip up on.

This things-to-check-separately list, too, will evolve.  Revise it occasionally.
If Dr. Harrington does enough
concentrated C\#, \emph{maybe} he will find that entering semicolons becomes automatic,
and he can take the separate round of semicolon checking off his list....

What to do \emph{after} you finish an exercise is important, too.  The natural thing psychologically,
particularly if you had a struggle, is to think, ``Whew, outta here!!!!''

On something that came automatically or flowed smoothly, that is not a big deal -
you will probably get it just as fast the next time. If you had a hard time and only eventually
got to success, you may be doing yourself a disservice with ``Whew, outta here!!!''

We have already mentioned how not everything is equally important, and some things are more
important to keep in your head than others.  The same idea applies to all the steps in solving
a possibly long problem.  Some parts were easy; some were hard; there may have been many steps.
If all of that goes into your brain in one continuous stream of stuff that you
remember at the same level, then you are going to leave important nuggets mixed in
with an awful lot of unimportant
and basically useless information, and have it all fade into oblivion, or be next to
impossible to cycle through looking for the nuggets.
Why do the problem anyway if you are just going to bury important information further
down in your brain?

What is important?  The most obvious thing you will need at a higher level of recall is what
\emph{just messed you up}, what you missed until doing this problem:  After finishing the
actual problem, \emph{actively} follow up and ask yourself:
\begin{itemize}
\item {} 
What did I get in the end that I was missing initially? What was the connection I made?

\item {} 
Does this example fit in to some larger idea/abstraction/generalization in a way that
I did not see before?

\item {} 
How am I going to look at this so I can make a similar connection
in a similar (or maybe only partly similar) problem?

\item {} 
Is there a kernel here that I can think of as a new tool in my bag of tricks?

\end{itemize}

Your answers to these questions are the most important things to take away from your
recent hard work.
The extra consideration puts them more in
the ``priority'' part of your brain, so you can really learn from your effort.  When you need
the important ideas
next, you do not need to play through all the details of
the stuff you did to solve the exact earlier problem.

Keep coming back to this section and check up on your process:  It is really important.

\index{labs!division sentences}

\section{Lab: Division Sentences}
\label{data_lab-division-sentences:lab-division-sentences}\label{data_lab-division-sentences:index-0}\label{data_lab-division-sentences::doc}\label{data_lab-division-sentences:lab-division}

\subsection{Overview}
\label{data_lab-division-sentences:overview}
In this lab, we're going to begin to look at what makes computers \emph{do
their thing} so to speak.

It is rather insightful to look at how Wikipedia summarizes the
computer:
\begin{quote}

A computer is a programmable machine designed to sequentially and
automatically carry out a sequence of arithmetic or logical
operations. The particular sequence of operations can be changed
readily, allowing the computer to solve more than one kind of
problem.
\end{quote}

In other words, a computer is a calculator--and much
more. Furthermore, the definition of a computer goes on to include
access to storage and peripherals, such as consoles (graphical displays),
printers, and the network. We already got a glimpse of this access
when we explored \code{Console.WriteLine} in the first lab exercise.

We have discussed all the syntax and concepts needed in recent sections
on {\hyperref[data_arithmetic:arithmetic]{\emph{Arithmetic}}}, {\hyperref[data_variables:variables-and-assignment]{\emph{Variables and Assignment}}},
{\hyperref[data_io:io]{\emph{Combining Input and Output}}}, and {\hyperref[data_types-and-conversions:cast]{\emph{Casting}}}.  Also you can make things easier for yourself using
{\hyperref[data_writeline-substitution:substitution-in-writeline]{\emph{Substitutions in Console.WriteLine}}} to format output.

Before writing your final program, you might like to review some of
the parts, testing in the {\hyperref[data_arithmetic:csharp]{\emph{Csharp}}} program, so you get immediate feedback
for the calculations.


\subsection{Requirements}
\label{data_lab-division-sentences:requirements}
We want to develop a program that can do the following:
\begin{itemize}
\item {} 
Prompt the user for input of two integers, which we will call
\emph{numerator} and \emph{denominator}. For clarity, we are only looking at
integers, because this assignment is about rational numbers. A
rational number can always be expressed as a quotient of two integers.

\item {} 
Calculate the floating point division result (e.g. 10/4 = 2.5).

\item {} 
Calculate the quotient and the remainder (e.g. 10/4 = 2 with a
remainder of 2 = 2 2/4).

\end{itemize}

Your final program should work as in this sample run, and use the same
labeled format:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Please enter the numerator? 14
Please enter the denominator? 4
Integer division result = 3 with a remainder 2
Floating point division result = 3.5
The result as a mixed fraction is 3 2/4.
\end{Verbatim}

For this lab the example format \code{3 2/4} is sufficient.
It would look better as \code{3 1/2}, but a general
efficient way to reduce fractions to
lowest terms is not covered until the section on the algorithm {\hyperref[gcdexamples:gcd]{\emph{Greatest Common Divisor}}}.

To do the part requiring a decimal quotient you are going to need to have a
\code{double} value, though your original data was of type \code{int}.
You could use the approach in {\hyperref[data_types-and-conversions:cast]{\emph{Casting}}}, with an explicit cast.
Another approach mentioned in that section was to do the cast implicitly
in a \code{double} declaration with initialization from an \code{int}.  If we
already had \code{int} variables, \code{numerator} and
\code{denominator}, that were previously assigned their values,
we could use:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{double} \PYG{n}{numeratorDouble} \PYG{p}{=} \PYG{n}{numerator}\PYG{p}{;} \PYG{c+c1}{// implicit cast}
\PYG{k+kt}{double} \PYG{n}{quotientDouble} \PYG{p}{=} \PYG{n}{numeratorDouble}\PYG{p}{/}\PYG{n}{denominator}\PYG{p}{;}
\PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
\end{Verbatim}

Remember: at least one operand in a quotient must be \code{double}
to get a \code{double} result.

To help you
get started with your program code,
we provided this simple \emph{stub} in the example file
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/do\_the\_math\_stub/do\_the\_math.cs}{do\_the\_math\_stub/do\_the\_math.cs}.
You are encouraged to copy this into your own project as reviewed
after the lab in {\hyperref[data_lab-division-sentences:xamarinstudio-reminders]{\emph{Xamarin Studio Reminders and Fixes}}}.

\index{comment}\index{/* ... */ comment}\index{*/ end /* comment}\index{// comment}
The body of \code{Main} presently contains only \emph{comments}, skipped by the compiler.
We illustrate two forms (being inconsistent for your information only):
\begin{itemize}
\item {} 
\code{//} to the end of the \emph{same} line

\item {} 
\code{/*} to \code{*/} through any number of lines.

\end{itemize}

Save the stub in a project of
your own and replace the comments with your code to complete it:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{DoTheMath} \PYG{p}{\PYGZob{}}   \PYG{c+c1}{// Lab stub}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{c+cm}{/* Prompt the user for the numerator using}
\PYG{c+cm}{         Console.Write().}

\PYG{c+cm}{         Convert this text into int numerator using}
\PYG{c+cm}{         int.Parse().}

\PYG{c+cm}{         Do the same for the denominator.}

\PYG{c+cm}{         Calculate quotient and remainder (as integers)}
\PYG{c+cm}{         Use Console.WriteLine() to display the labels}
\PYG{c+cm}{         as illustrated in the sample output in the lab.}

\PYG{c+cm}{         Do the same but using floating point division }
\PYG{c+cm}{         and not doing the remainder calculation.   }

\PYG{c+cm}{         Create the sentence with the mixed fraction.}
\PYG{c+cm}{         Be careful of the places there are *not* spaces.}
\PYG{c+cm}{      */}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Be sure to run it and test it thoroughly. Show your output to a TA.

\index{Xamarin Studio!empty project - no console error}\index{Xamarin Studio!file not in project error}

\subsection{Xamarin Studio Reminders and Fixes}
\label{data_lab-division-sentences:xamarinstudio-reminders}\label{data_lab-division-sentences:index-2}\label{data_lab-division-sentences:xamarin-studio-reminders-and-fixes}
Be careful to open your Xamarin Studio solution and add a new \textbf{C\# Console project} to
it, and add your new file directly into the project (through the Solution pad).
There are two main places to
mess up here.  We emphasize them and mention fixes if you make the easy mistakes:
\begin{enumerate}
\item {} 
It is easy to select Empty Project instead of C\# and Console Project.  If you
do that, a correct program will compile successfully, but it will run
in limbo, with no console attached to it, and all \code{Console.ReadLine()} calls
return \code{null}, which is likely to make the program have a run-time error.
One way to fix it:
\begin{itemize}
\item {} 
If you discovered this while running your program, there is no good access to
the running process.  (You lack a console!)
In this case you need to close your solution, ending the running process,
and open the solution again.

\item {} 
Double click on the project in the Solution Pad
(if that does anything, or right-click it and select Options).
An elaborate Project Options dialog window appears.

\item {} 
In the left pane under Run, select General.
In the right pane, two check boxes should appear.  Make sure you have the first
checked: Run on external console.  That should check the second one
automatically.  Close the window and you should be set.

Be careful, it is possible to uncomment the second checkbox,
which makes your execution console close instantly at the end
of your program, so you miss any last thing printed.  Recheck if
necessary.

\end{itemize}

\item {} 
Another common error is to proceed like with most text processors,
and open the top File menu,
and choose to open and edit a new file for your program.
\emph{You cannot*} \emph{run} \textbf{this program from Xamarin Studio.}
The file you edit must show in the solution pad in Xamarain Studio, as
a source file in your project.  If you have a separate project set up,
but without this file or any other showing in the Solutions pad, an attempt to
run the project with say no \code{Main} method (in fact no program at all).
The fix:
\begin{itemize}
\item {} 
You will shortly need to navigate in an operating system open file dialog to where
you put the file created from the File menu.  If you do not
remember where that was, a good trick is to click in the edit window of the file
and then go to the File menu and select Save As.  The dialog should
show where the file currently is.  Cancel the dialog.

\item {} 
Right click on the project in the Solution pad, and choose Add and then
Add Files....  Browse to where the file is and select it; click Open.
Unless you have some
reason to keep a copy in the original place, select Move, and Ok.
Now the orphaned file is moved into your project.  You should see it list
under the project in the Solution pad.
You can proceed to edit and run it.

\end{itemize}

\item {} 
If you lose the display of the Solution pad somehow, you can go to the View menu,
select Pads, and then select Solution.

\end{enumerate}


\section{Chapter Review Questions}
\label{data_reviewdataop:chapter-review-questions}\label{data_reviewdataop::doc}\begin{enumerate}
\item {} 
Most of C\# arithmetic is just like normal math.  The exceptions are
most important:  What are they?

\item {} 
What are the consequences of numerical value types each being stored in
a fixed amount of memory space?

\item {} 
What is the order of operations if several of the same level,
are chained together like \code{x + y + z}?
This can matter in C\# (including in a question below).

\item {} 
Which of these individual
two-line fragments could fit into a legal C\# program?
Explain:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{w} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
\PYG{n}{w} \PYG{p}{=} \PYG{l+m}{4}\PYG{p}{;}

\PYG{n}{x} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{=} \PYG{n}{x}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{;}

\PYG{n}{y} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
\PYG{n}{y} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}hello\PYGZdq{}}\PYG{p}{;}

\PYG{n}{z} \PYG{p}{=} \PYG{l+m}{3.5}
\PYG{n}{z} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}

\PYG{n}{q} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
\PYG{n}{q} \PYG{p}{+} \PYG{l+m}{1} \PYG{p}{=} \PYG{n}{q}\PYG{p}{;}
\end{Verbatim}

\item {} 
For the legal pairs above, what could the type of the variable have been
declared?  You can check them in csharp, giving the declaration first.

\item {} 
What are the final values of \code{x} and \code{y}  after this fragment?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{3}
\PYG{k+kt}{int} \PYG{n}{y} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{l+m}{2}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{n}{y}\PYG{p}{;}
\PYG{n}{y} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{n}{y}\PYG{p}{;}
\end{Verbatim}

Test in csharp after you have decided.

\item {} 
Which of these expressions are legal in C\#?
Think of the results.
Explain.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+s}{\PYGZdq{}a\PYGZdq{}} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}b\PYGZdq{}}
\PYG{l+s}{\PYGZdq{}a\PYGZdq{}} \PYG{p}{+} \PYG{l+s+sc}{\PYGZsq{}b\PYGZsq{}}
\PYG{l+s}{\PYGZdq{}a\PYGZdq{}} \PYG{p}{+} \PYG{l+m}{2}
\PYG{l+m}{2} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}a\PYGZdq{}}
\PYG{l+s}{\PYGZdq{}a\PYGZdq{}} \PYG{p}{+} \PYG{l+m}{2} \PYG{p}{*} \PYG{l+m}{3}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}a\PYGZdq{}} \PYG{p}{+} \PYG{l+m}{2} \PYG{p}{+} \PYG{l+m}{3}
\PYG{l+m}{2} \PYG{p}{+} \PYG{l+m}{3} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}a\PYGZdq{}}
\PYG{l+m}{2} \PYG{p}{+} \PYG{l+m}{3} \PYG{p}{*} \PYG{l+s}{\PYGZdq{}a\PYGZdq{}}
\end{Verbatim}

Think first; try in csharp; reconsider if necessary.

\item {} 
Write a single \code{WriteLine} statement that would produce output
on two separate lines, not one.  Accomplish the same thing a second time
with fundamentally
different syntax.

\item {} 
What is printed?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}1\PYGZcb{} \PYGZob{}0\PYGZcb{} \PYGZob{}2\PYGZcb{} \PYGZob{}1\PYGZcb{} \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{l+s+sc}{\PYGZsq{}B\PYGZsq{}}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}or not\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
Which of these casts is necessary, and which could be left out
(and be legal and mean the same thing)? Before testing,
think what the values of the variables will be
for the first two or three:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{=} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{)}\PYG{l+m}{5.8}\PYG{p}{;}
\PYG{k+kt}{double} \PYG{n}{y} \PYG{p}{=} \PYG{p}{(}\PYG{k+kt}{double}\PYG{p}{)}\PYG{l+m}{6}\PYG{p}{;}
\PYG{k+kt}{char} \PYG{n}{c} \PYG{p}{=} \PYG{p}{(}\PYG{k+kt}{char}\PYG{p}{)}\PYG{p}{(}\PYG{l+s+sc}{\PYGZsq{}a\PYGZsq{}} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{)}
\PYG{k+kt}{int} \PYG{n}{z} \PYG{p}{=} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{)}\PYG{l+s+sc}{\PYGZsq{}a\PYGZsq{}} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}
\end{Verbatim}

\end{enumerate}


\chapter{Defining Functions of your Own}
\label{functions:defining-functions-of-your-own}\label{functions::doc}\label{functions:defining-own-functions}
\index{function!definition}

\section{A First Function Definition}
\label{firstfunc:index-0}\label{firstfunc::doc}\label{firstfunc:a-first-function}\label{firstfunc:a-first-function-definition}
If you know it is the birthday of a friend, Emily, you might tell
those gathered with you to sing ``Happy Birthday to Emily''.

We can make C\# display the song. \emph{Read}, and run if you like,
the example program \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/birthday1/birthday1.cs}{birthday1/birthday1.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Birthday1}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main} \PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday, dear Emily.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Here the song is just a part of the \code{Main} method that is in
every program.

Note that we are using a function already provided to us,
\code{Console.WriteLine}.  We can use it over and over, wherever we like.
We can alter its behavior by including a different parameter.
Now we look further at writing and using your own functions.

If we
want this song to be just part of a larger program, and be able to refer
to it repeatedly and easily, we might like
to package it separately.
You would probably not repeat the whole song to let others know
what to sing. You would give a request to sing via a descriptive
name like ``Happy Birthday to Emily''.

In C\# we can also give a name like \code{HappyBirthdayEmily}, and
associate the name with whole song by using a new
\emph{function definition}, also called a \emph{method}. We will see many variations
on method definitions.  Later we will see definitions that are
attached to a particular object.
For now the simpler cases do not involve creating a type of object,
but there is an extra word, \code{static},
needed to distinguish a function definition
\emph{not} attached to  on object.
We will also shortly look at functions more like
the functions from math class, that produce or \emph{return} a value.  In
this simple case we will not deal with returning a value.
This also requires a special word in the heading:  \code{void}.  A \code{void}
function will just be a shorthand name for something to do, a procedure
to follow, in this case
printing out the Happy Birthday song for Emily.  (Note that
the \code{Main} method for a program is also \code{static void}.
This \emph{does} your whole program and is not attached to an object.)

\emph{Read} for now:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Birthday2}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{HappyBirthdayEmily}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday, dear Emily.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}   
      \PYG{n}{HappyBirthdayEmily}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Hip hip hooray!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{HappyBirthdayEmily}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

There are several parts of the syntax for a function definition to
notice:

Line 5: The \emph{heading} starts with \code{static void}, the name of the function,
and then parentheses.

A more general syntax for functions that just \emph{do}
something is
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{static void} \textbf{FunctionName}\code{()}
\item[] \code{\{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statements in the function body...
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

Recall the conventions in {\hyperref[data_typography:syntax-template-typography]{\emph{Syntax Template Typography}}}.

Lines 6-11: The remaining lines form the function \emph{body}.  They are enclosed
in braces.  By convention the lines inside the braces are indented by a
consistent amount. Three spaces is a common indentation.

The whole definition does just that: \emph{defines} the meaning of the
name \code{HappyBirthdayEmily}, but it does not do anything else yet -
for example, the definition itself does not yet make anything be
printed. This is our first example of altering the order of
execution of statements from the normal sequential order. This is
important: the statements in the function \emph{definition} are \emph{not}
executed as C\# first passes over the lines.
The only part of a program that is automatically executed is \code{Main}.
Hence \code{Main} better refer to the newly defined function....

Look at the first statement inside Main, line 15:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{HappyBirthdayEmily}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

Note that the \code{static void} of the function definition is missing,
but we still have the function name and parentheses.
When \code{Main} is running, C\# goes back and looks up
the definition, and only then, executes the code inside the
function definition. The term for this action is a \emph{function call}
or function \emph{invocation}.  In this simple situation the format is
\begin{quote}

\emph{FunctionName}\code{()}
\end{quote}

While the convention for variable identifiers is to start with a lowercase
letter, the convention for function names is to start with a capital letter.
Hence \code{HappyBirthdayEmily}, not \code{happyBirthdayEmily}.

Can you predict what the program will do?  Note the two function calls
to \code{HappyBirthdayEmily}.  To see, load and run \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/birthday2/birthday2.cs}{birthday2/birthday2.cs}.

\index{function!execution sequence}\index{execution sequence!function}
The \emph{execution} sequence for the program is different from the
\emph{textual} sequence.  Execution always starts in Main:
\begin{enumerate}
\item {} 
Line 13: Main is where execution starts, and initially proceeds
sequentially.

\item {} 
Line 15: the function is called while this location is
remembered.

\item {} 
Lines 5-11: Jump!  The code of the function is executed for the first
time, printing out the song.

\item {} 
End of line 15: Back from the function call; continue on.

\item {} 
Line 16:  Just to mix things up, print out a ``Hip, hip, hooray''.

\item {} 
Line 17: the function is called again while this location is
remembered.

\item {} 
Lines 5-11: The function is executed again, printing out the song
again.

\item {} 
End of line 17: Back from the function call, but at this point
there is nothing more in \code{Main}, and execution stops.

\end{enumerate}

Functions alter execution order in several ways: by statements not
being executed as the definition is first read, and then when the
function is called during execution, jumping to the function code,
and back at the the end of the function execution.

Understanding the jumping around in the code with function calls is
crucial.  Be sure you follow the sequence detailed above.  In particular,
be sure to distinguish function \textbf{definition} from function \textbf{call}.

If it also happens to be Andre's birthday, we might define a
function \code{HappyBirthdayAndre}, too. Think how to do that before
going on ....


\section{Multiple Function Definitions}
\label{multfunc::doc}\label{multfunc:multiple-function-definitions}\label{multfunc:id1}
Here is example program \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/birthday3/birthday3.cs}{birthday3/birthday3.cs} where we add a function
\code{HappyBirthdayAndre}, and call them both. Guess what happens, and
then load and try it:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Birthday3}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}   
       \PYG{n}{HappyBirthdayEmily}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
       \PYG{n}{HappyBirthdayAndre}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{HappyBirthdayEmily}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday, dear Emily.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{HappyBirthdayAndre}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}   
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday, dear Andre.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Again, definitions are remembered and execution starts in \code{Main}.
The order in which the function definitions are given does not matter
to C\#.  It is a human choice.  For variety I show \code{Main} first.  This
means a human reading in order gets an overview of what is happening
by looking at Main, but does not know the details until reading the
definitions of the birthday functions.

Detailed order of execution:
\begin{enumerate}
\item {} 
Line 5: Start on \code{Main}

\item {} 
Line 7. This location is remembered as execution jumps to
\code{HappyBirthdayEmily}

\item {} 
Lines 11-17 are executed and Emily is sung to.

\item {} 
Return to the end of Line 7: Back from \code{HappyBirthdayEmily}
function call

\item {} 
Line 8: Now \code{HappyBirthdayAndre} is called as this location is
remembered.

\item {} 
Lines 19-25: Sing to Andre

\item {} 
Return to the end of line 8: Back from \code{HappyBirthdayAndre}
function call, done with \code{Main};
at the end of the program

\end{enumerate}

The calls to the birthday functions
\emph{happen} to be in the same order as their definitions, but that is
arbitrary. If the two lines of the body of \code{Main} were swapped,
the order of
operations would change, but if the order of the whole function
definitions were changed,
it would make no difference in execution.

Functions that you write can also call other functions you write.
In this case Main calls each of the birthday functions.

\index{compiler error!bad place for heading syntax}\index{\{ \} !matching}\index{function!compiler error with heading}
\begin{notice}{warning}{Warning:}
A common compiler error is caused by failing to match the braces
that wrap a function body.  A new function heading can only
exist outside all other function declarations and inside a class.
If you have too few or extra \code{'\}'} you are likely to find
a perfectly fine looking function heading with an error,
for instance, about not
allowing \code{static} here....
Check your earlier lack or excess of braces!
\end{notice}

\index{( ) !matching}\index{{[} {]} !matching}\index{Xamarin Studio!delimiter matching}
Xamarin Studio, like other modern code editors, can show you
matching delimiters.  If you place your cursor immediately after a delimiter
\{ \} ( ) {[} {]}, the matching one should become highlighted.


\subsection{Poem Function Exercise}
\label{multfunc:poem-function-exercise}
Write a program, \code{poem.cs}, that defines a function that
prints a \emph{short} poem or song verse. Give a meaningful name to the
function. Have the program call the function three times,
so the poem or verse is repeated three times.

\index{function!parameter}\index{parameter}

\section{Function Parameters}
\label{funcparam:index-0}\label{funcparam::doc}\label{funcparam:function-parameters}\label{funcparam:id1}
As a young child, you probably heard Happy Birthday sung to a
couple of people, and then you could sing to a new person, say
Maria, without needing to hear the whole special version with
Maria's name in it word for word. You had the power of
\emph{abstraction}. With examples like the versions for Emily and Andre,
you could figure out what change to make it so the song could be
sung to Maria!

Unfortunately, C\# is not that smart. It needs explicit rules.
If you needed to explain \emph{explicitly} to someone how Happy Birthday
worked in general, rather than just by example, you might say
something like this:

First you have to be \emph{given} a person's name. Then you sing the
song with the person's name inserted at the end of the third line.

C\# works something like that, but with its own syntax. The term
``person's name'' serves as a stand-in for the actual data that
will be used, ``Emily'', ``Andre'', or ``Maria''. This is just like
the association with a variable name in C\#. ``person's name''
is not a legal C\# identifier, so we will use just \code{person} as
this stand-in.  It will be a variable in the program,
so it needs a type in C\#.  The names are strings,
so the type of \code{person} is \code{string}.

In between the parentheses of the function definition heading, we insert the variable
name \code{person}, preceded  by its type, \code{string}.
Then in the body of the definition
of the function, \code{person} is used in place of the real data for any
specific person's name. Read and then run example program
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/birthday4/birthday4.cs}{birthday4/birthday4.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Birthday4}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{HappyBirthday}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{person}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}   
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday, dear \PYGZdq{}} \PYG{p}{+} \PYG{n}{person} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
    
    \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}   
        \PYG{n}{HappyBirthday}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Emily\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{HappyBirthday}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Andre\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}

\PYG{p}{\PYGZcb{}}
\end{Verbatim}

In the definition heading for \code{HappyBirthday}, \code{person} is
referred to as a \emph{parameter}, or a \emph{formal parameter}. This
variable name is a \emph{placeholder} for the real name of the person
being sung to.  In the definition we give instructions for singing
Happy Birthday \emph{without} knowing the exact name of the person who might be sung to.

\code{Main} now has two calls to the same function,
but between the parentheses, where there was the \textbf{placeholder} \code{person}
in the definition, now we have the \textbf{actual people} being sung to.
The value between the parentheses here in the function call
is referred to as an \emph{argument} or \emph{actual parameter} of the
function call. The argument supplies the actual data to be used in
the function execution. When the call is made, C\# does this by
associating the \textbf{formal} parameter name \code{person} with the \textbf{actual}
parameter data, as in an assignment statement. In the first call,
this actual data is \code{"Emily"}. We say the actual parameter value
is \emph{passed} to the function for execution.

The execution in greater detail:
\begin{enumerate}
\item {} 
Lines 13: Execution starts in Main.

\item {} 
Line 15: Call to \code{HappyBirthday}, with actual parameter
\code{"Emily"}.

\item {} 
Line 5: \code{"Emily"} is passed to the function, so
\code{person = "Emily"}.

\item {} 
Lines 7-10: The song is printed, with \code{"Emily"} used as the
value of \code{person} in line 9: printing

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Happy} \PYG{n}{Birthday}\PYG{p}{,} \PYG{n}{dear} \PYG{n}{Emily}\PYG{p}{.}
\end{Verbatim}

\item {} 
End of line 15 after returning from the function call

\item {} 
Line 16: Call to \code{HappyBirthday}, this time with actual
parameter \code{"Andre"}

\item {} 
Line 5: \code{"Andre"} is passed to the function, so
\code{person = "Andre"}.

\item {} 
Lines 7-10: The song is printed, with \code{"Andre"} used as the
value of \code{person} in line 9: printing

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Happy} \PYG{n}{Birthday}\PYG{p}{,} \PYG{n}{dear} \PYG{n}{Andre}\PYG{p}{.}
\end{Verbatim}

\item {} 
End of line 16 after returning from the function call,
and the program is over.

\end{enumerate}

The beauty of this system is that the same function definition can
be used for a call with a different actual parameter variable, and
then have a different effect. The value of the variable person is
used in the third line of \code{HappyBirthday}, to put in whatever
actual parameter value was given.

\index{abstraction}
This is the power of \emph{abstraction}. It is one application of the
most important principal in programming. Rather than have a number
of separately coded parts with only slight variations, see where it
is appropriate to combine them using a function whose parameters
refer to the parts that are different in different situations. Then
the code is written to be simultaneously appropriate for the
separate specific situations, with the substitutions of the right
parameter values.

\begin{notice}{note}{Note:}
Be sure you completely understand \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/birthday4/birthday4.cs}{birthday4/birthday4.cs}
and the sequence of execution!  It illustrates extremely
important ideas that many people miss the first time!  It is
essential to understand the difference between
\begin{enumerate}
\item {} 
\emph{Defining} a function (lines 5-11)
with the heading including \emph{formal} parameter name and type,
where the code is merely instructions to be remembered,
not acted on immediately.

\item {} 
\emph{Calling} a function with an \emph{actual} parameter value to be
substituted for the formal parameter,
(with \emph{no} type included!) and have the function
code actually \emph{run} when the instruction containing the call
is run.  Also note that the function can be
called multiple times with different expressions as the
actual parameter (line 15 and again in line 16).

\end{enumerate}
\end{notice}

We can combine function parameters with user input, and have the
program be able to print Happy Birthday for anyone. Check out the
\code{Main} method and run \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/birthday\_who/birthday\_who.cs}{birthday\_who/birthday\_who.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Birthday\PYGZus{}Who}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{HappyBirthday}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{person}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday, dear \PYGZdq{}} \PYG{p}{+} \PYG{n}{person} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Happy Birthday to you!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{string} \PYG{n}{userName}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Who would you like to sing Happy Birthday to?\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{userName} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{HappyBirthday}\PYG{p}{(}\PYG{n}{userName}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This last version illustrates several important ideas:
\begin{enumerate}
\item {} 
There are more than one way to get information into a function:
\begin{enumerate}
\item {} 
Have a value passed in through a parameter (from line 18 to line 5).

\item {} 
Prompt the user, and obtain data from the keyboard (lines 16-17).

\end{enumerate}

\item {} 
It is a good idea to separate the \emph{internal} processing of data
from the \emph{external} input from the user by the use of distinct
functions. Here the user interaction is in \code{Main}, and the data
is manipulated in \code{HappyBirthday}.

\item {} 
In the first examples of actual parameters, we used literal
values. In general an actual parameter can be an expression. The
expression is evaluated before it is passed in the function call.
One of the simplest expressions is a plain variable name, which is
evaluated by replacing it with its associated value.
Note this important situation in the example:
We have the
value of \code{userName} in \code{Main} becoming the value of \code{person}
in \code{HappyBirthday}.  We used different names to illustrate the
important fact:

\begin{notice}{note}{Note:}
Only the \emph{value} of the actual parameter is passed, not any
variable name, so there is \emph{no need} to have a match between a variable name
used in
an actual parameter and the formal parameter name.
\end{notice}

\end{enumerate}


\subsection{Birthday Function Exercise}
\label{funcparam:birthdayfunctionex}\label{funcparam:birthday-function-exercise}
Make your own further change to \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/birthday4/birthday4.cs}{birthday4/birthday4.cs} and save it in your
own project as
\code{birthday\_many.cs}: Add a function call
(but \emph{not} another function \emph{definition}), so Maria gets a verse, in
addition to Emily and Andre. Also print a blank line between
verses. (There are two ways to handle the blank lines:
You may \emph{either} do this by adding a print line to the
function definition, \emph{or} by adding a print line between all calls to
the function.  Recall that if you give Console.WriteLine an empty
parameter list, it just goes to the next line.)

\index{function!parameter}\index{parameter}

\section{Multiple Function Parameters}
\label{funcparam2:more-func-param}\label{funcparam2:multiple-function-parameters}\label{funcparam2:index-0}\label{funcparam2::doc}
A function can have more than one parameter in a parameter list.  The
list entries are
separated by commas. Each formal parameter name is preceded by its type.
The example program \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/addition1/addition1.cs}{addition1/addition1.cs}
uses
a function, \code{SumProblem},  with two parameters
to make it easy to display many sum problems. Read and
follow the code, and then run:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Addition2}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{SumProblemString}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{y}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{n}{y}\PYG{p}{;}
      \PYG{k+kt}{string} \PYG{n}{sentence} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}The sum of \PYGZdq{}} \PYG{p}{+} \PYG{n}{x} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} and \PYGZdq{}} \PYG{p}{+} \PYG{n}{y} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} is \PYGZdq{}} \PYG{p}{+} \PYG{n}{sum} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}.\PYGZdq{}}\PYG{p}{;}
      \PYG{k}{return} \PYG{n}{sentence}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{SumProblemString}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{SumProblemString}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{3}\PYG{l+m}{4}\PYG{l+m}{5}\PYG{p}{,} \PYG{l+m}{5}\PYG{l+m}{3}\PYG{l+m}{5}\PYG{l+m}{7}\PYG{l+m}{9}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter an integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{k+kt}{int} \PYG{n}{a} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter another integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{k+kt}{int} \PYG{n}{b} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{SumProblemString}\PYG{p}{(}\PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{parameter!actual and formal}\index{actual parameter}\index{formal parameter}
The actual parameters in the function call are evaluated left to
right, and then these values are associated with the formal
parameter names in the function definition, also left to right. For
example a function call with actual parameters,
\code{F(actual1, actual2, actual3)}, calling a function \code{F} with
definition heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{F}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{formal1}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{formal2}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{formal3}\PYG{p}{)}
\end{Verbatim}

acts approximately as if the first lines executed inside the called
function \code{F} were

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{formal1} \PYG{p}{=} \PYG{n}{actual1}\PYG{p}{;}
\PYG{n}{formal2} \PYG{p}{=} \PYG{n}{actual2}\PYG{p}{;}
\PYG{n}{formal3} \PYG{p}{=} \PYG{n}{actual3}\PYG{p}{;}
\end{Verbatim}

Functions provide extremely important functionality to programs,
allowing tasks to be defined once and performed repeatedly with
different data. It is essential to see the difference between the
\textbf{formal} parameters used to describe what is done inside the function
definition (like x and y in the definition of SumProblem) and the
\textbf{actual} parameters (like 2 and 3 or 12345 and 53579)
which \emph{substitute} for the formal parameters when the function is
actually executed. \code{Main} uses three different sets
of actual parameters in the three calls to SumProblem.

\begin{notice}{warning}{Warning:}
It is easy to confuse the heading in a function \emph{definition} and a \emph{call}
to actually execute that function.  Be careful.  In particular,
do \emph{not} list the types of parameters
in a call's \emph{actual} parameter list.  The actual parameters are expressions
involving terms that are \emph{already defined}, not just being declared.
\end{notice}


\subsection{Quotient Function Exercise}
\label{funcparam2:quotient-function-exercise}\label{funcparam2:quotientfunctionex}
Modify \code{quotient\_format.cs} from
{\hyperref[data_writeline-substitution:quotientformat]{\emph{Exercise for Format}}} and save it
as \code{quotient\_prob.cs}.
You should create a function \code{QuotientProblem} with \code{int}
parameters.  Like in the earlier versions, it should print a full
sentence with inputs, integer quotient, and remainder.
\code{Main}
should test the \code{QuotientProblem} function
on several sets of literal values, and also test the function with
input from the user.

\index{function!return}\index{return}\index{execution sequence for function}

\section{Returned Function Values}
\label{funcreturn:returned-function-values}\label{funcreturn:index-0}\label{funcreturn::doc}\label{funcreturn:id1}
You probably have used mathematical functions in algebra class, but
they all had calculated values associated with them. For instance
if you defined
\begin{quote}

F(x)=x$^{\text{2}}$
\end{quote}

then it follows that F(3) is 3$^{\text{2}}$ = 9, and F(3)+F(4) is
3$^{\text{2}}$ + 4$^{\text{2}}$ = 9 + 16 = 25.

Function calls in expressions get
replaced during evaluation by the value of the function.

The corresponding definition and examples in C\# would be the
following, taken from example program \code{return1.cs}. \emph{Read}
\emph{and run}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Return1}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{F}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
       \PYG{k}{return} \PYG{n}{x}\PYG{p}{*}\PYG{n}{x}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{F}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{F}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{)} \PYG{p}{+} \PYG{n}{F}\PYG{p}{(}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The new C\# syntax is the \emph{return statement}, with the word
\code{return} followed by an expression. Functions that return values
can be used in expressions, just like in math class. When an
expression with a function call is evaluated, the function call is
effectively replaced temporarily by its returned value. Inside the
C\# function, the value to be returned is given by the
expression in the \code{return} statement.

Since the function returns data, and all data in C\# is typed,
there must be a type given for the value returned.  Note that the
function heading does not start with \code{static void}.
In place of \code{void} is \code{int}.  The \code{void} in earlier function headings
meant nothing was returned.  The \code{int} here means that a value \emph{is}
returned and its type is \code{int}.

After the function \code{F}
finishes executing from inside

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{F}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

it is as if the statement temporarily became

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+m}{9}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

and similarly when executing

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{F}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{)} \PYG{p}{+} \PYG{n}{F}\PYG{p}{(}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

the interpreter first evaluates F(3) and effectively replaces the
call by the returned result, 9, as if the statement temporarily
became

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+m}{9} \PYG{p}{+} \PYG{n}{F}\PYG{p}{(}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

and then the interpreter evaluates F(4) and effectively replaces
the call by the returned result, 16, as if the statement
temporarily became

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+m}{9} \PYG{p}{+} \PYG{l+m}{1}\PYG{l+m}{6}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

resulting finally in 25 being calculated and printed.

C\# functions can return any type of data, not just numbers, and
there can be any number of statements executed before the return
statement. Read, follow, and run the example program
\code{return2.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Return2}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{LastFirst}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{firstName}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{lastName}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{string} \PYG{n}{separator} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}, \PYGZdq{}}\PYG{p}{;}
      \PYG{k+kt}{string} \PYG{n}{result} \PYG{p}{=} \PYG{n}{lastName} \PYG{p}{+} \PYG{n}{separator} \PYG{p}{+} \PYG{n}{firstName}\PYG{p}{;}
      \PYG{k}{return} \PYG{n}{result}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

    \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{LastFirst}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Benjamin\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}Franklin\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{LastFirst}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Andrew\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}Harrington\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Many have a hard time following the flow of execution with functions.
Even more is involved when there are return values.
Make sure you completely follow the details of the execution:
\begin{enumerate}
\item {} 
Lines 12: Start at Main

\item {} 
Line 14: call the function, remembering where to return

\item {} 
Line 5: pass the parameters: \code{firstName = "Benjamin"};
\code{lastName = "Franklin"}

\item {} 
Line 7: Assign the variable \code{separator} the value \code{", "}

\item {} 
Line 8: Assign the variable \code{result} the value of
\code{lastName + separator + firstName} which is
\code{"Franklin" + ", " + "Benjamin"}, which evaluates to
\code{"Franklin, Benjamin"}

\item {} 
Line 9: Return \code{"Franklin, Benjamin"}

\item {} 
Line 14: Use the value returned from the function call so the line
effectively becomes  \code{Console.WriteLine("Franklin, Benjamin");},
so print it.

\item {} 
Line 15: call the function with the new actual parameters,
remembering where to return

\item {} 
Line 5: pass the parameters: \code{firstName = "Andrew"};
\code{lastName = "Harrington"}

\item {} 
Lines 7-9: ... calculate and return \code{"Harrington, Andrew"}

\item {} 
Line 15: Use the value returned by the function and print
\code{"Harrington, Andrew"}

\end{enumerate}

Compare \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/return2/return2.cs}{return2/return2.cs} and \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/addition1/addition1.cs}{addition1/addition1.cs},
from the previous
section. Both use functions. Both print, but where the printing \emph{is
done} differs. The function \code{SumProblem} prints directly inside
the function and returns nothing. On the other hand
\code{LastFirst} does not print anything but returns a string. The
caller gets to decide what to do with the returned string, and above it is
printed in \code{Main}.

\index{example!addition2.cs}\index{addition2.cs example}
In general functions should do a single thing.
You can easily combine a sequence of functions, and you have more
flexibility in the combinations
if each does just one unified thing.  The function
SumProblem in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/addition1/addition1.cs}{addition1/addition1.cs} does two thing:
It creates a sentence,
and prints it.  If that is all you have, you are out of luck if you want
to do something different with the sentence string.  A better approach is
to have a function that just creates the sentence, and returns it for
whatever further use you want.  After returning that value,
printing is one possibility, done in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/addition2/addition2.cs}{addition2/addition2.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Addition2}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{SumProblemString}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{y}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{n}{y}\PYG{p}{;}
      \PYG{k+kt}{string} \PYG{n}{sentence} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}The sum of \PYGZdq{}} \PYG{p}{+} \PYG{n}{x} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} and \PYGZdq{}} \PYG{p}{+} \PYG{n}{y} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} is \PYGZdq{}} \PYG{p}{+} \PYG{n}{sum} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}.\PYGZdq{}}\PYG{p}{;}
      \PYG{k}{return} \PYG{n}{sentence}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{SumProblemString}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{SumProblemString}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{3}\PYG{l+m}{4}\PYG{l+m}{5}\PYG{p}{,} \PYG{l+m}{5}\PYG{l+m}{3}\PYG{l+m}{5}\PYG{l+m}{7}\PYG{l+m}{9}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter an integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{k+kt}{int} \PYG{n}{a} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter another integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{k+kt}{int} \PYG{n}{b} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{SumProblemString}\PYG{p}{(}\PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This example constructs the sentence using the string \code{+} operator.
Generating a string with substitutions using a format string
in \code{Console.Write} is neater, but
we are forced to directly print the string,
and not remember it for later arbitrary use.

\index{string!Format}\index{Format method for string}\phantomsection\label{funcreturn:string-format}
It is common to want to construct and immediately print a string,
so having \code{Console.Write} is definitely handy when we want it.,
However it is an example of combining two separate steps!  Sometimes
(like here) we just want to have the resulting string, and do something else
with it.  We introduce
the C\# library function  \code{string.Format}, which does just what we want:
The parameters
have the same form as for \code{Console.Write}, but the formatted string is
\emph{returned}.

Here is a revised version of the function \code{SumProblemString},
from example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/addition2a/addition2a.cs}{addition2a/addition2a.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
   \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{SumProblemString}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{y}\PYG{p}{)} \PYG{c+c1}{// with string.Format}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{n}{y}\PYG{p}{;}
      \PYG{k}{return} \PYG{k+kt}{string}\PYG{p}{.}\PYG{n}{Format}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}The sum of \PYGZob{}0\PYGZcb{} and \PYGZob{}1\PYGZcb{} is \PYGZob{}2\PYGZcb{}.\PYGZdq{}}\PYG{p}{,} \PYG{n}{x}\PYG{p}{,} \PYG{n}{y}\PYG{p}{,} \PYG{n}{sum}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\end{Verbatim}

The only caveat with \code{string.Format} is that
there is \emph{no} special function corresponding to \code{Console.WriteLine},
with an automatic terminating newline.
You can generate a newline with string.Format:  Remember the
escape code \code{"\textbackslash{}n"}.  Put it at the end to go on to a new line.

\textbf{In class recommendation}:  Improve example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/painting/painting.cs}{painting/painting.cs}
with a function used for repeated similar operations.
Copy it to a file \code{painting\_input.cs} in your
own project and modify it.


\subsection{Interview String Return Exercise/Example}
\label{funcreturn:interviewstringex}\label{funcreturn:interview-string-return-exercise-example}
Write a program by that accomplishes the same thing as
{\hyperref[data_io:interviewproblem]{\emph{Interview Exercise/Example}}}, but introduce a function
\code{InterviewSentence} that takes name
and time strings as parameters and returns the interview sentence string.
For practice use \code{string.Format} in the function.
With this setup you can manage input from the user and output to the
screen entirely in \code{Main}, while using \code{InterviewSentence} to generate
the sentence that you want to \emph{later} print.

(Here we are having you work on getting used to
function syntax while keeping the
body of your new function very simple.  Combining that with longer, more
realistic function bodies is coming!)

If you want a further example on this idea of returning
something first and then using the result,
or if you want to compare your work to ours,
see our solution, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/interview2/interview2.cs}{interview2/interview2.cs}.


\subsection{Quotient String Return Exercise}
\label{funcreturn:quotient-string-return-exercise}\label{funcreturn:quotientstringex}
Create \code{quotient\_return.cs} by modifying \code{quotient\_prob.cs} in
{\hyperref[funcparam2:quotientfunctionex]{\emph{Quotient Function Exercise}}} so that the program accomplishes the same
thing, but everywhere:
\begin{itemize}
\item {} 
Change the QuotientProblem function into one
called \code{QuotientString} that merely \emph{returns} the string rather
than printing the string directly.

\item {} 
Have \code{Main} print
the result of each call to the \code{QuotientString} function.

\end{itemize}

Use \code{string.Format} to create the sentence that you return.

\index{function!consumer and writer}\index{consumer of functions}\index{writer of functions}

\section{Two Roles: Writer and Consumer of Functions}
\label{writerconsumer:index-0}\label{writerconsumer:two-roles-writer-and-consumer-of-functions}\label{writerconsumer:two-roles}\label{writerconsumer::doc}
The remainder of this section covers finer
points about functions that you might skip on a first reading.

We are only doing tiny examples so far to get the basic idea of
functions. In much larger programs, functions are useful to manage
complexity, splitting things up into logically related, modest
sized pieces. Programmers are both writers of functions and
consumers of the other functions called inside their functions. It
is useful to keep those two roles separate:

The user of an already written function needs to know:
\begin{enumerate}
\item {} 
the name of the function

\item {} 
the order and meaning of parameters

\item {} 
what is returned or produced by the function

\end{enumerate}

\emph{How} this is accomplished is not relevant at this point. For
instance, you use the work of the C\# development team, calling
functions that are built into the language. You need know the three
facts about the functions you call. You do not need to know exactly
\emph{how} the function accomplishes its purpose.

On the other hand when you \emph{write} a function you need to figure
out exactly how to accomplish your goal, name relevant variables,
and write your code, which brings us to the next section.

The jargon for these parts are the \emph{interface} (for the consumer)
and the \emph{implementation} (for the programmer, who must be sure
to satisfy the public interface).

\index{local variables' scope}\index{scope!local}

\section{Local Scope}
\label{localscope:local-scope}\label{localscope:index-0}\label{localscope::doc}\label{localscope:id1}
For the logic of writing functions, it is important that the writer
of a function knows the names of variables inside the function. On
the other hand, if you are only using a function, maybe written by
someone unknown to you, you should not care what names are given to
values used internally in the implementation of the function you
are calling. C\# enforces this idea with \emph{local scope} rules:
Variable names initialized and used inside one function are
\emph{invisible} to other functions. Such variables are called \emph{local}
variables. For example, an elaboration of the earlier program
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/return2/return2.cs}{return2/return2.cs} might have its \code{lastFirst} function with its local
variable \code{separator}, but it might also have another function
that defines a \code{separator} variable, maybe with a different value
like \code{"\textbackslash{}n"}. They would not conflict. They would be
independent. This avoids lots of errors!

For example, the following code in the example program
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/bad\_scope/bad\_scope.cs}{bad\_scope/bad\_scope.cs} causes a compilation error
if the last line is uncommented.
Read it, uncomment the line, and try to run it, and see:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{BadScope}
\PYG{p}{\PYGZob{}}
   \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
      \PYG{n}{F}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{F}\PYG{p}{(}\PYG{p}{)}  
   \PYG{p}{\PYGZob{}}  \PYG{c+c1}{// F doesn\PYGZsq{}t know about the x defined in Main}
      \PYG{c+c1}{//Console.WriteLine(x); //ERROR if uncommented}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The compilation error that Mono gives is pretty clear:
\begin{quote}

The name `x' does not exist in the current context.
\end{quote}

The the error occurs in the function \code{F}.  The \emph{context} there just includes
the local variables already declared in \code{F}.  And \code{x} is declared in
\code{Main}, not in \code{F}, so it \emph{does not exist} inside \code{F}.
We will fix this error below.

If you do want local data from one function to go to another,
define the called function so it includes parameters! Read and
compare and try the program \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/good\_scope/good\_scope.cs}{good\_scope/good\_scope.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{GoodScope}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
      \PYG{n}{F}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{F}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

\PYG{p}{\PYGZcb{}}
\end{Verbatim}

With parameter passing, the parameter name \code{x} in the function
\code{F} does not need to match the name of the actual parameter in
the calling function \code{Main}. (Just the \code{int} value is passed.)
The definition of \code{F} could just as well have been:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{F}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{whatever}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{whatever}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\begin{notice}{warning}{Warning:}
It is a very common error to declare a variable in one function
and try to use it by name in a different function.  If you get
an error about a variable not existing, look to see where it was
declared (or if you remembered to declare it at all)!
\end{notice}

In general the \emph{scope} of a variable is
the places in the program where its value can be referenced and used.
The scope of a local variable is just inside
the function where it is declared.

\index{constant}\index{global constant}\index{scope!class}\index{class!scope}

\section{Static Variables}
\label{staticvariables:index-0}\label{staticvariables:static-variables}\label{staticvariables::doc}\label{staticvariables:id1}
You may define \emph{static variables} (variables defined
with the word \code{static} inside the class,
but \emph{outside} of any function definition).
These variables are visible inside all of your functions in the class.
Instead of local scope, static variables have \emph{class scope}.
It is good programming practice generally to avoid defining static variables and
instead to put your variables inside functions and explicitly pass
them as parameters where needed. There are exceptions.  For now a
good reason for using static variables is constants:
A \emph{constant} is a name that you give a fixed data value to.
If you have a static definition of a constant,
then you can then use the name of the fixed data value in
expressions in any function in the class.
A simple example program is \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/constant/constant.cs}{constant/constant.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{UseConstant}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k+kt}{double} \PYG{n}{PI} \PYG{p}{=} \PYG{l+m}{3.14159265358979}\PYG{p}{;} \PYG{c+c1}{// constant, value not reset}

   \PYG{k}{static} \PYG{k+kt}{double} \PYG{n+nf}{CircleArea}\PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{radius}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{return} \PYG{n}{PI}\PYG{p}{*}\PYG{n}{radius}\PYG{p}{*}\PYG{n}{radius}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{static} \PYG{k+kt}{double} \PYG{n+nf}{Circumference}\PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{radius}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{return} \PYG{l+m}{2}\PYG{p}{*}\PYG{n}{PI}\PYG{p}{*}\PYG{n}{radius}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}circle area with radius 5: \PYGZdq{}} \PYG{p}{+} \PYG{n}{CircleArea}\PYG{p}{(}\PYG{l+m}{5}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}circumference with radius 5:\PYGZdq{}} \PYG{p}{+} \PYG{n}{Circumference}\PYG{p}{(}\PYG{l+m}{5}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

See that \code{PI} is used in two functions without being declared locally.

By convention, names for constants are all capital letters
(and underscores joining multiple words).

\index{function!not use return value}\index{return!value not used}

\section{Not using Return Values}
\label{notusereturn:not-using-ret-val}\label{notusereturn:index-0}\label{notusereturn::doc}\label{notusereturn:not-using-return-values}
Some functions return a value, and get used as an expression
in a larger calling statement.
The calling statement uses the value returned.
Usually the only effect of such a value-returning function is from the
value returned.

Some functions are \code{void}, and get used as a whole instruction in your code:
Without returning a value, the only way to be useful is to do something that
leaves some lasting \emph{side effect}:
make some change to the system that persists after
the termination of the function and its local variables disappear.
The only such effect that we have seen so
far is to print something that remains on the console screen.
Later we will talk about other persistent changes
to values in objects, locations in files, ....

Usually there is this division in the behavior of functions,
returning a value or not:
\begin{enumerate}
\item {} 
\code{void}: do something as a whole instruction,
with a side effect in the larger system.

\item {} 
Return a value to use in a larger calling statement

\end{enumerate}

It is legal to do \emph{both}: accomplish something with a side effect
in the system, \emph{and}
return a value.  Sometimes you care about both,
and sometimes you use the function only for its side effect.
We will see examples of that later, like in {\hyperref[dictionaryexamples:sets]{\emph{Sets}}}.

This later advanced use will mean that the compiler needs to
\emph{permit} the programmer to ignore a
returned value, and use a function returning a value as a whole statement.

\begin{notice}{warning}{Warning:}
This means that the compiler cannot catch a common logical error:
forgetting to immediately use a returned value that your program logic
really needs.
\end{notice}

For example with this definition:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{CalcResult}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{param}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k+kt}{int} \PYG{n}{result}\PYG{p}{;}
   \PYG{c+c1}{// ....}
   \PYG{n}{result} \PYG{p}{=} \PYG{p}{.}\PYG{p}{.}\PYG{p}{.}\PYG{p}{.}\PYG{p}{;}
   \PYG{k}{return} \PYG{n}{result}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

you might try to use \code{CalcResult} in this bad code, intending to use the \code{result}
from CalcResult:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{BadUseResult}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k+kt}{int} \PYG{n}{result} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
   \PYG{n}{CalcResult}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{result}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

In fact you would always print 0, ignoring the \code{result}
calculated in \code{CalcResult}.
The reason is the {\hyperref[localscope:local-scope]{\emph{Local Scope}}} rules:  The local variable name \code{result}
disappears when the \code{CalcResult} function returns.
It is not used in the calling function, \code{BadUseResult}, and the
separately declared \code{result} of \code{BadUseResult}
retains its original 0 value.

Here we set up the worst situation: where there is a logical error,
but not an error shown by the compiler.  More commonly a student leaves out
the \code{int result = 0;} line, incorrectly relying on the declaration of \code{result}
in \code{CalcResult}.  At least in that situation a compiler error brings attention
to the problem:
The last line would try to use the variable \code{result}
without it being declared.

You can use the result from \code{CalcResult}, like with any other
value-returning function, with either

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{k}{value} \PYG{p}{=} \PYG{n}{CalcResult}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}  \PYG{c+c1}{//store the returned value in an assignment!}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{k}{value}\PYG{p}{)}\PYG{p}{;}   \PYG{c+c1}{//  and then use the remembered value}
\end{Verbatim}

or

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{CalcResult}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// immediately use the returned value}
\end{Verbatim}

This second version works as long as you do \emph{not} need the
returned value later, in another place, since you do not remember it past that
one statement!

\index{library class}\index{multiple source files using library class}

\section{Library Classes}
\label{libraryclass:library-classes}\label{libraryclass:index-0}\label{libraryclass::doc}\label{libraryclass:id1}
\index{library!UIF}
In {\hyperref[funcreturn:returned-function-values]{\emph{Returned Function Values}}}, the suggestion was made to look at
the Painter class and split out repeated ideas into functions, leading to
a function to prompt the user and return a double value.
The same section included
the example program \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/addition2/addition2.cs}{addition2/addition2.cs}.
In that case there were repeated prompts for
integers.  Clearly another common situation is to prompt for a string.
We can create
functions to do all these things and more, and embed them into a class
specially written for a new
interactive program.

A neater thing is to put them as a class in a separate library
that can be used directly for multiple programs.  We can create functions
\code{PromptLine},
\code{PromptInt}, and  \code{PromptDouble}, and put them in their own class, \code{UIF}
(for User Input First version)
in project ui's file \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/ui/uif.cs}{uif.cs}.
We explain the namespace line after the code:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{c+c1}{/// User Input First version (bombs in Parse with mistyping)}
   \PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{UIF}  
   \PYG{p}{\PYGZob{}}
      \PYG{c+c1}{/// After displaying the prompt, return a line from the keyboard.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{PromptLine}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{prompt}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{return} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// After displaying the prompt, }
      \PYG{c+c1}{/// return an integer entered from the keyboard.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{PromptInt}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{prompt}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{PromptLine}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// After displaying the prompt, }
      \PYG{c+c1}{/// return a double entered from the keyboard.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{double} \PYG{n+nf}{PromptDouble}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{prompt}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k+kt}{double}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{PromptLine}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// After displaying the prompt, }
      \PYG{c+c1}{/// return  true if \PYGZsq{}y\PYGZsq{} is entered from the keyboard}
      \PYG{c+c1}{/// and false otherwise.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{bool} \PYG{n+nf}{Agree}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{prompt}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{l+s}{\PYGZdq{}y\PYGZdq{}} \PYG{p}{=}\PYG{p}{=} \PYG{n}{PromptLine}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}} 
   \PYG{p}{\PYGZcb{}} 
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{namespace}\index{IntroCS namespace}
We have been \code{using System} in every program.  \code{System} is a \emph{namespace} that
collects a particular group of class names, making them available to the program,
and distinguishes them form any classes in a different namespace that might have the
same class names.

Once we start writing and using multiple classes at once, it is a good idea for us to
specify our own namespace.  We will consistently use \code{IntroCS} in our multi-file
examples in this book.

\index{public}
Specifying a namespace makes it possible for all other classes in the
same namespace to reference \emph{public} parts of the current class, and vice-versa.

Public classes and functions start their heading with \code{public}.

The code included in a namespace is enclosed in braces, so the general syntax is
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{namespace} \emph{name}
\item[] \code{\{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] class definition(s)...
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

We will keep user input library classes like this one, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/ui/uif.cs}{uif.cs},
in a project ui.

Notice that the functions we want accessible in \code{UIF}
are all marked \code{public}, so that any class can use them.

We can write a modified example addition program, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/addition3/addition3.cs}{addition3/addition3.cs},
as an example of using \code{UIF}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{k}{class} \PYG{n+nc}{Addition3} \PYG{c+c1}{// using UIF}
   \PYG{p}{\PYGZob{}}
      \PYG{c+c1}{/// Return a sentence stating the sum of x and y.}
      \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{SumProblemString}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{y}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{n}{y}\PYG{p}{;}
         \PYG{k+kt}{string} \PYG{n}{sentence} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}The sum of \PYGZdq{}} \PYG{p}{+} \PYG{n}{x} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} and \PYGZdq{}} \PYG{p}{+} \PYG{n}{y} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} is \PYGZdq{}} \PYG{p}{+} \PYG{n}{sum} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}.\PYGZdq{}}\PYG{p}{;}
         \PYG{k}{return} \PYG{n}{sentence}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
      
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{SumProblemString}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;} 
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{SumProblemString}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{3}\PYG{l+m}{4}\PYG{l+m}{5}\PYG{p}{,} \PYG{l+m}{5}\PYG{l+m}{3}\PYG{l+m}{5}\PYG{l+m}{7}\PYG{l+m}{9}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{a} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter an integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}      \PYG{c+c1}{//NEW}
         \PYG{k+kt}{int} \PYG{n}{b} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter another integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{//NEW}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{SumProblemString}\PYG{p}{(}\PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

To allow access to UIF, we have added the IntroCS namespace for the class.
To reference the static functions in the different class \code{UIF}, we put \code{UIF.}
(with the dot) at the start of each reference to a static function in
the class \code{UIF}.

\begin{notice}{warning}{Warning:}
In Xamarin Studio, if you use a file from a library project (without
just copying the present version of that file into the current project),
be sure that the current project includes
a \emph{reference} to the library project.
If you expand the references in the Xamarin Studio
project addition3, by clicking on the References line in the solution pad,
you should see the project ui.
\end{notice}

Shortly you will see the optional section for making your own
{\hyperref[libraryclass:library-projects-in-xamarinstudio]{\emph{Library Projects in Xamarin Studio (Optional)}}}.

Though we have not discussed all the C\# syntax needed yet, there is also an
improved class \code{UI} in the ui project that we discuss later.
It includes all the function
names in \code{UIF}, and keeps your program from bombing out
if the user enters an illegal format for a number.

\index{documentation of functions}\index{function!documentation ///}\index{/// documentation}

\subsection{Function Documentation}
\label{libraryclass:index-4}\label{libraryclass:id2}\label{libraryclass:function-documentation}
In keeping with {\hyperref[writerconsumer:two-roles]{\emph{Two Roles: Writer and Consumer of Functions}}}, in future you will be a \emph{consumer} of the library
classes.  It is particularly important to document library classes with the
interface information users will need.
Documentation could be written in a separate document, but much developer history has
shown that such documentation does not tend to either get written in the first place,
or not updated well to stay consistent with updates in the code.
Inconsistent documentation is useless.  Documentation is much more
likely to be seen and maintained by the implementers if it sits right with the
code, like our comments before the class and function headings.

You will note that instead of the usual line comment syntax \code{//}, we have added
an extra \code{/}, making \code{///}.  That will also start a comment.  (The third \code{/}
is technically just a part of the comment.)  There is a special reason for the
notation:  Though it is convenient for the \emph{implementer} of code to have the documentation
right with the code, a \emph{user} of the functions only needs the interface information
found in good documentation.  The \code{///} lines before heading are specially recognized
by \emph{separate} automatic documentation generating programs.

There are many documentation
generating programs and conventions.
For now we will just use plain text in the \code{///} lines.
This is recognized by the Xamarin Studio system. If you open our \code{examples} solution,
in Xamarin Studio, and edit window for
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/addition3/addition3.cs}{addition3/addition3.cs},
you can place your mouse over \code{UIF} and a popup window shows the \code{UIF} class heading
documentation.

If you move the mouse over \code{PromptInt}, you should see the popup label showing
the function signature and the function documentation.
If you change the two \code{///} lines
in \code{uif.cs} above the \code{PromptInt} heading to start with just \code{//}.
you should no longer be able to see the documentation part of the popup for
\code{PromptInt} in the \code{addition3.cs} edit window. (Be sure to change back to \code{///}.)

There are more elaborate documentation conventions that can be used for
Xamarin Studio and other documentation generation programs, not discussed here.

This documentation also works inside a single program file.  If you have a long
program with lots of functions defined, this can also be helpful when calling
one of your own functions.  You can avoid jumping
around to be reminded of the signature and use of your functions.


\subsection{Library Projects in Xamarin Studio (Optional)}
\label{libraryclass:library-projects-in-xamarin-studio-optional}\label{libraryclass:library-projects-in-xamarinstudio}
Xamarin Studio has a multi-step process for
creating a library project and for separately
referencing it in other projects.  The \emph{advantage} of this approach is when you
want to change the implementation but not the interface to library functions,
you just do it once, in the library project.
Other projects reference that project.

Some students find the Xamarin Studion overhead of setting up and referencing
library projects onerous.
As a  practical matter with files that you want to reuse but are not likely to change,
you can just copy the source file into the new project, and avoid the
Xamarin Studio library setup overhead.
Many of our already created example projects use a library version
of UIF and several other utility files.  You can do the same with your solutions,
following the instructions below, or you can just copy in the needed utility
files for each project.

Hence the rest of the section here is \emph{optional}:

Try adding a reference yourself.  Follow these instructions:
\begin{enumerate}
\item {} 
In your own Xamarin Studio solution, start to add a project,
but \emph{instead} of leaving
Console Project selected in the dialog window, select \textbf{Library Project}.

\item {} 
Then add the project name ui, and continue like when starting
previous projects.

\item {} 
Copy in the \code{.cs} files from
our ui project, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/ui/uif.cs}{uif.cs} and \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/ui/ui.cs}{ui.cs}.
Now you have your library project.

\item {} 
Create another regular Console project, addition3, in your \emph{same} solution,
and copy in our \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/addition3/addition3.cs}{addition3/addition3.cs}, so that is the only file.

\begin{notice}{warning}{Warning:}
Xamarin Studio remembers the last kind of project you created.
That is fine when you are creating a sequence of Console projects.
However, if you have just explicitly chosen to create a library
project, the default for your next project will also be library,
and really mess up your next Console project.  Fix such an error
after the fact as in the first
entry in {\hyperref[data_lab-division-sentences:xamarinstudio-reminders]{\emph{Xamarin Studio Reminders and Fixes}}}.
\end{notice}

\item {} 
In the Solutions pad, in your addition3 project,
click on the References entry just inside the project.
You should see that the project is automatically set up to reference System.

\item {} 
Open the local menu for the References, and select Edit References.

\item {} 
Click the Projects tab in the window that pops up.  This limits the length
of the list that you search.

\item {} 
Possibly after scrolling down, find the recently made ui project and
check the box beside it.

\item {} 
Click OK in the bottom right corner of the window.
Now look at the References again.  You should see ui listed!

\item {} 
Run your addition3 project.

\end{enumerate}

You only need to add a library project once,
but every further project that needs it,
must have a \emph{reference} to the library project added.
You might try another for yourself
with the next exercise!

Again this approach allows you to change the implementation of
your library class in just one copy in one project,
which can be referenced from many places.
If you copy the file into different projects, and then decide the code
needs to be updated, you are stuck \emph{finding} and editing \emph{all} the copies!
Not good.  Our library files uif.cs, ui.cs, and later fio.cs,
should not be moving targets, so copying should not cause a problem.  This
may simplify your life, but the tradeoff is not getting used to using
library references, which are useful in the larger scheme of things.


\subsection{Quotient UI Exercise}
\label{libraryclass:quotient-ui-exercise}\label{libraryclass:quotientuiex}
Create \code{quotient\_u\_i.cs} by modifying \code{quotient\_return.cs} in
{\hyperref[funcreturn:quotientstringex]{\emph{Quotient String Return Exercise}}} so that the program accomplishes the same
thing, but use the UIF class for all user input.

\index{function!summary of syntax}

\section{Static Function Summary}
\label{funcsummary:index-0}\label{funcsummary:id1}\label{funcsummary::doc}\label{funcsummary:static-function-summary}
This chapter has introduced static functions:  those used in procedural programming
as opposed to {\hyperref[a-first-class:instance-methods]{\emph{Instance Methods}}} used to
implement object-oriented programming.

References in square brackets link to fully discussions of summary items below.

\index{( )!function definition}

\subsection{Function definition}
\label{funcsummary:index-1}\label{funcsummary:function-definition}\begin{enumerate}
\item {} 
The general syntax for defining a static function is
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{static} \textbf{returnTypeOrVoid} \textbf{FunctionName} \code{(}  formal parameter list \code{)}
\item[] \code{\{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statements in the function body...
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

\item {} 
The \emph{formal parameter list} can be empty or contain one or more comma separated
\emph{formal parameter} entries.  {[}{\hyperref[funcparam:function-parameters]{\emph{Function Parameters}}}{]}
Each formal parameter entry has the form
\begin{quote}

\textbf{type} \textbf{parameterName}
\end{quote}

\item {} 
If the function is going to be called from outside its class, the heading needs
to start with \code{public} before the \code{static}. {[}{\hyperref[libraryclass:library-classes]{\emph{Library Classes}}}{]}

\item {} 
If \textbf{returnTypeOrVoid} in the heading is not \code{void}, there must be a
\emph{return statement} in the function body.  A return statement has the form
\begin{quote}

\code{return} \emph{expression} \code{;}
\end{quote}

where the expression should be of the same type as in \textbf{returnTypeOrVoid}.
Execution of the function terminates immediately when a return statement
is reached. {[}{\hyperref[funcreturn:returned-function-values]{\emph{Returned Function Values}}}{]}

\item {} 
Execution of a program starts at a function with a heading including
\begin{quote}

\code{static void Main}
\end{quote}

Thus far we have only discussed having an empty parameter list in the heading
of the definition
of \code{Main}, and we defer discussion of {\hyperref[onedim:command-line-param]{\emph{Parameters to Main}}} until
we have introduced {\hyperref[onedim:one-dim-arrays]{\emph{One Dimensional Arrays}}}.

\item {} 
There are various conventions for putting documentation just above the headings
of function definitions.  The official format, specified by C\# and recognized by
Xamarin Studio, involves putting the function interface description on
consecutive lines
starting with \code{///}.  {[}{\hyperref[libraryclass:function-documentation]{\emph{Function Documentation}}}{]}

\end{enumerate}

\index{( )!function call}

\subsection{Function Calls}
\label{funcsummary:function-calls}\label{funcsummary:index-2}\begin{enumerate}
\item {} 
A function call takes the form

\textbf{FunctionName} \code{(}  actual parameter list \code{)}

A function call makes the function definition be \emph{executed}.

\item {} 
The actual parameter list is a comma separated list of the \emph{same}
length as the formal parameter list.  Each entry is an expression.
The entries in an actual parameter list do \emph{not} include type declarations.

Effectively, the function execution starts by assigning to each
formal parameter variable the corresponding value from
evaluating the actual parameter expression.
In particular, that means the actual parameter values must be allowed
in an assignment statement for a variable of the formal parameter's type!
{[}{\hyperref[funcparam2:more-func-param]{\emph{Multiple Function Parameters}}}{]}

\item {} 
If the function has return type \code{void}, it can only be used syntactically
as an entire statement (with a semicolon added). After the function
call completes, execution continues with the next statement.

\item {} 
If there is a non-void return type, then the function call is syntactically
an expression in the statement where is appears.
The execution of such a function must reach a return statement.  The value
of the function-call expression is the value of the expression in this
return statement.
{[}{\hyperref[funcreturn:returned-function-values]{\emph{Returned Function Values}}}{]}

\item {} 
A function with a return value can also legally be used as a whole statement.
In this case the return value is lost.  Though legal, this is often an error!
{[}{\hyperref[notusereturn:not-using-ret-val]{\emph{Not using Return Values}}}{]}

\end{enumerate}


\subsection{Scope}
\label{funcsummary:scope}\begin{enumerate}
\item {} 
A variable declared inside a function definition is called a \emph{local variable}.
This declaration may be in either the formal parameter
list or in the body of the function.  {[}{\hyperref[localscope:local-scope]{\emph{Local Scope}}}{]}

\item {} 
A local variable comes into existence after the function is called, and ceases
to exist after that function call terminates.  A local variable is invisible
to the rest of the program.  Its \emph{scope} is just within that function.  Its
lifetime is just through a single
function call.  Its \emph{value} may be transferred outside of the function scope
by standard means, principally:
\begin{itemize}
\item {} 
If it is the expression in a return statement, its value is
sent back to the caller.

\item {} 
It can be passed as an
actual parameter to a further function called within its scope.

\end{itemize}

{[}{\hyperref[localscope:local-scope]{\emph{Local Scope}}}{]}

\end{enumerate}


\subsection{Static Variables}
\label{funcsummary:static-variables}\begin{enumerate}
\item {} 
There may be a declaration prefaced by the word \code{static} that appears
\emph{inside} a class and \emph{outside} of any function definition in the class.
Static variables are visible within each function of the class, and may
be used by the functions.  {[}{\hyperref[staticvariables:static-variables]{\emph{Static Variables}}}{]}

\item {} 
A common use of a static variable is to give a name to a constant
value used in multiple functions in the class.
{[}{\hyperref[staticvariables:static-variables]{\emph{Static Variables}}}{]}

\end{enumerate}


\section{Chapter Review Questions}
\label{reviewfunc:chapter-review-questions}\label{reviewfunc::doc}\begin{enumerate}
\item {} 
Write the function definition heading for a static function called
\code{Q1} which
has two \code{int} parameters, \code{x} and \code{y}, and returns a \code{double}.

\item {} 
The function above must have what kind of a statement in its body?

\item {} 
Each of these lines has a call to the function above, \code{Q1}.  Which
are legal?  Explain:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{double} \PYG{n}{d} \PYG{p}{=} \PYG{n}{Q1}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}

\PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{n}{Q1}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}

\PYG{k+kt}{double} \PYG{n}{y} \PYG{p}{=} \PYG{n}{Q1}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{)} \PYG{p}{+} \PYG{l+m}{5.5}\PYG{p}{;}

\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{Q1}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}2\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}5\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}

\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{Q1}\PYG{p}{(}\PYG{l+m}{2.5}\PYG{p}{,} \PYG{l+m}{5.5}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}

\PYG{n}{Q1}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{,} \PYG{l+m}{2}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
Suppose \code{Q1} does nothing except produce the value to return, like
most functions returning a \code{double}.  Which
line in the previous problem is legal, but has \emph{no} effect?

\item {} 
Write the function definition heading for a static function called
\code{Q4} which
has one \code{string} parameter, \code{s}, and returns nothing.

\item {} 
Which of these lines with a call to the function above, \code{Q4},
is legal?  Explain:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Q4}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}hi\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}

\PYG{k+kt}{string} \PYG{n}{t} \PYG{p}{=} \PYG{n}{Q4}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}hi\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}

\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{Q4}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}hi\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}

\PYG{n}{Q4}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}hi\PYGZdq{}} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}ho\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}

\PYG{n}{Q4}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}hi\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}ho\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}

\PYG{n}{Q4}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
Can you have more than one function/method in the same
class definition with the same name?

\item {} 
What is a function/method signature?
Can you have more than one function/method declared in the same
class definition with the same signature?

\item {} 
In each part,
is this a legal program?  If so, what is printed?  If not, why not?

Each version uses the same code, except for different versions of
\code{Main}.  Here is the common code with the body of \code{Main} omitted:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{class} \PYG{n+nc}{Local1}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{Q}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{)}  \PYG{c+c1}{// 1}
   \PYG{p}{\PYGZob{}}                    \PYG{c+c1}{// 2}
      \PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}        \PYG{c+c1}{// 3}
      \PYG{n}{x} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{n}{a}\PYG{p}{;}        \PYG{c+c1}{// 4}
      \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}         \PYG{c+c1}{// 5}
   \PYG{p}{\PYGZcb{}}                    \PYG{c+c1}{// 6}

   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{c+c1}{// see each version}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}
\begin{enumerate}
\item {} 
Insert:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{n}{Q}\PYG{p}{(}\PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
Insert instead:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
   \PYG{n}{Q}\PYG{p}{(}\PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
Insert instead:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}                   \PYG{c+c1}{// 7}
\PYG{p}{\PYGZob{}}                                    \PYG{c+c1}{// 8}
   \PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{,} \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}                 \PYG{c+c1}{// 9}
   \PYG{n}{y} \PYG{p}{=} \PYG{n}{Q}\PYG{p}{(}\PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}                         \PYG{c+c1}{// 10}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}} \PYG{p}{+} \PYG{n}{y}\PYG{p}{)}\PYG{p}{;}   \PYG{c+c1}{// 11}
\PYG{p}{\PYGZcb{}}                                    \PYG{c+c1}{// 12}
\end{Verbatim}

\end{enumerate}

\item {} 
In the previous problem consider the common code with part c.
Note the line numbers as comments.
\begin{enumerate}
\item {} 
In what line(s) is \code{Q} being defined?

\item {} 
In what line(s) is \code{Q} called?

\item {} 
What is the return type of \code{Q}?

\item {} 
What is a formal parameter to \code{Q}?

\item {} 
What is used as an actual parameter to \code{Q}?

\item {} 
What is the scope of the \code{x} in line 3?

\item {} 
What is the scope of the \code{x} in line 9?

\end{enumerate}

\end{enumerate}


\chapter{Basic String Operations}
\label{basicstringops:basic-string-operations}\label{basicstringops::doc}\label{basicstringops:basic-string-ops}\phantomsection\label{stringindexing:string-indexing}
\index{string!index {[} {]}}\index{{[} {]}!string index}

\section{String Indexing}
\label{stringindexing:index-0}\label{stringindexing::doc}\label{stringindexing:id1}
Strings are composed of characters.  In literals be careful of the different
kinds of quotes: single for individual characters for type \code{char} and double for strings
of 0 or more characters.  For example,
\code{'u'} (single quotes) is a char type literal, while \code{"u"} is a string
literal, referencing a string object. While \code{"you"} is a legal string
literal, \code{'you'} generates a compiler error
(too many characters for a char literal).

Many of the operations on strings depend upon referring to the
positions of characters in the string.
A position is given by a numerical \emph{index} number.
In C\#, positions are counted \emph{starting at 0}, not 1.
The indices of the characters in the string ``coding'' are labeled:

\begin{tabulary}{\linewidth}{|L|L|L|L|L|L|L|}
\hline

Index
 & 
0
 & 
1
 & 
2
 & 
3
 & 
4
 & 
5
\\
\hline
Character
 & 
c
 & 
o
 & 
d
 & 
i
 & 
n
 & 
g
\\
\hline\end{tabulary}


There are 6 characters in \code{"coding"}, while the last index is 5.

\begin{notice}{warning}{Warning:}
Because the indices start at 0, not 1,
the index of the last character is one less that the length of the
string. This is a common source of errors!
\end{notice}

You can easily create an expression that refers
to an individual character inside a string.  Use
square braces around the index of the character:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}coding\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]}\PYG{p}{;}
\PYG{l+s+sc}{\PYGZsq{}d\PYGZsq{}}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{;}
\PYG{l+s+sc}{\PYGZsq{}c\PYGZsq{}}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}\PYG{p}{[}\PYG{l+m}{5}\PYG{p}{]}\PYG{p}{;}
\PYG{l+s+sc}{\PYGZsq{}g\PYGZsq{}}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{greeting} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Bonjour\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{greeting}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]}\PYG{p}{;}
\PYG{l+s+sc}{\PYGZsq{}o\PYGZsq{}}
\end{Verbatim}

Note from the single quotes that the result is a \code{char} in each case.

\index{subscript}
C\# does not allow the typography for normal mathematical subscripts,
like \(s_2\).
There is a correspondence with index notation, so \code{s{[}2{]}} is
sometimes spoken as ``s sub 2''.  The indices are sometimes referred to as
\emph{subscripts}.

In this introduction, we have used literal integers for the subscripts.
The most common situation in practice is to have a variable or a more
complicated expression as the
subscript.  An expression inside square braces is always
evaluated to find the resulting index:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}coding\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{int} \PYG{n}{n} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{n}\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{]}\PYG{p}{;}
\PYG{l+s+sc}{\PYGZsq{}d\PYGZsq{}}
\end{Verbatim}

When we get to loops, we will find this is useful.


\subsection{Indexing Exercise}
\label{stringindexing:indexing-exercise}
What is printed by this fragment?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{str} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}fragment\PYGZdq{}}\PYG{p}{;}
\PYG{k+kt}{int} \PYG{n}{k} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{str}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{str}\PYG{p}{[}\PYG{n}{k}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{str}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{*}\PYG{n}{k} \PYG{p}{\PYGZhy{}} \PYG{l+m}{2}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

Write an expression that would give you the n in \code{str}, above.

Play with csharp:  declare other strings and \code{int} variables, and make up
string indexing expressions for which you predict the value and then test.

\index{string!method}\index{. !object field reference}

\section{Some Instance Methods and the Length Property}
\label{stringmethods:index-0}\label{stringmethods::doc}\label{stringmethods:some-instance-methods-and-the-length-property}
Strings are a special type in C\#. We have
used string literals as parameters to functions and we have used the
special concatenation operator \code{+}.
Thus far we have not emphasized the use of objects, or even noted
what is an object.  In fact strings are objects.  Like other objects,
strings have a general notation for functions that are specially tied to the
particular type of object.  These functions are called \emph{instance methods}.
They always act on an object of the particular class, but a reference to the
object is not placed inside the parameter list, but \emph{before} the method name and
a dot as in:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}hello\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{ToUpper}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}HELLO\PYGZdq{}}
\end{Verbatim}

\code{ToUpper} (the method converting to upper case)
does a particular action that makes sense
with strings.  It takes \code{s}
(the string object reference before the dot in this example)
and returns a \emph{new} string in upper case, based on \code{s}.  Since this action
depends only on the string itself, no further parameters are necessary,
and the parentheses after the method name are empty.  The general method syntax is
\begin{quote}

\emph{object-reference}\code{.}\textbf{methodName} \code{(}\emph{further-parameters} \code{)}
\end{quote}

More string methods are listed below, some with further parameters.

\index{property}\index{class!property}
Data can also be associated with object \emph{properties}.
A property of a string is its \code{Length} (an \code{int}).  References to property values
use dot notation but do not have a parameter list in parentheses at the end:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Hello\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
\PYG{l+m}{5}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
\PYG{l+m}{0}
\end{Verbatim}

Be careful: Though 5 is the length of \code{s} in the example above,
the last character in \code{s} is \code{s{[}4{]}}.  Using \code{s{[}5{]}} would generate
an \code{IndexOutOfRangeException}.

String objects have associated string methods which can be used to
manipulate string values.
There are an enormous number of string methods, but here are just a few
of the most common ones to get you started. The
string object to which the method is being applied is referred to as
\textbf{this} string in the descriptions.  After the methods,
the length property is also listed.
In the heading \emph{this} object is not shown explicitly, so be careful
when applying these methods and the length property: In actual use
in your programs they must be
preceded by a reference to a string, followed by a dot, as shown in
all the  examples.  The reference to \emph{this} string can be
a variable name, a literal, or any expression evaluating to a string.


\subsection{Summary of String Length and Some Instance Methods}
\label{stringmethods:string-methods-length}\label{stringmethods:summary-of-string-length-and-some-instance-methods}\begin{description}
\item[{\code{int IndexOf(string target)}}] \leavevmode
Returns the index of the beginning of the first occurrence of the
string \code{target}
in \textbf{this} string object. Returns -1 if \code{target} not found. Examples:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{greeting} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Bonjour\PYGZdq{}}\PYG{p}{,} \PYG{n}{part} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}jo\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{greeting}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{n}{part}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{3}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{greeting}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}jot\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}
\end{Verbatim}

\item[{\code{string Substring(int start)}}] \leavevmode
Returns the substring of \textbf{this} string object starting from index \code{start}
through to the end of the string object.  Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{name} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Sheryl Crow\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{name}\PYG{p}{.}\PYG{n}{Substring}\PYG{p}{(}\PYG{l+m}{7}\PYG{p}{)}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}Crow\PYGZdq{}}
\end{Verbatim}

\item[{\code{string Substring(int start, int len)}}] \leavevmode
Returns the substring of \textbf{this} string object starting from index \code{start},
including a total of \code{len} characters.  Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{name} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Sheryl Crow\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{name}\PYG{p}{.}\PYG{n}{Substring}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{,}\PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}ryl C\PYGZdq{}}
\end{Verbatim}

Java programmers:  Note the second parameter is \emph{not} the same as in Java.

\item[{\code{string ToUpper()}}] \leavevmode
Return a string like \textbf{this} string, except all in upper case.  Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{l+s}{\PYGZdq{}Hi Jane!\PYGZdq{}}\PYG{p}{.}\PYG{n}{ToUpper}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}HI JANE!\PYGZdq{}}
\end{Verbatim}

\item[{\code{string ToLower()}}] \leavevmode
Return a string like \textbf{this} string, except all in lower case.  Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{l+s}{\PYGZdq{}Hi Jane!\PYGZdq{}}\PYG{p}{.}\PYG{n}{ToLower}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}hi jane!\PYGZdq{}}
\end{Verbatim}

\item[{\code{int Length}}] \leavevmode
Property referring to the length of \textbf{this} string object. Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{greeting} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Bonjour\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{greeting}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}  \PYG{c+c1}{//no parentheses}
\PYG{l+m}{7}
\end{Verbatim}

\end{description}

\index{immutable}
\begin{notice}{warning}{Warning:}
All of these methods that return a string return a \emph{new} string.  No string method
alters the original string.  Strings are \emph{immutable}:
They are objects that cannot be changed
after they are first produced.  This is a common source of errors.
\end{notice}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Hello\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{ToUpper}\PYG{p}{(}\PYG{p}{)}
\PYG{l+s}{\PYGZdq{}HELLO\PYGZdq{}}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}
\PYG{l+s}{\PYGZdq{}Hello\PYGZdq{}}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{ToUpper}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}
\PYG{l+s}{\PYGZdq{}HELLO\PYGZdq{}}
\end{Verbatim}

See that you need an explicit assignment if you \emph{want} the variable associated
with the original string to change.

Further string methods are introduced in {\hyperref[stringmethods2:more-string-methods]{\emph{More String Methods}}}.

Time to reflect, thinking back to {\hyperref[data_learning-to-problem-solve:learn-solve]{\emph{Learning to Solve Problems}}}.
Without forcing all the code details on yourself,
how can you concisely say what powers you have with strings so far?
Remember that kernel.

With strings you can:
Index characters, find a part; extract a part; convert case; determine length.
These may not be evocative phrases for you.  Find your own.

When we get to loops, we will find this is useful.

Here is a brief example of a function using several of these methods,

\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/parenthesized/parenthesized.cs}{parenthesized/parenthesized.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Parenthesized}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}} 
      \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}What (really) happened?\PYGZdq{}}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Original: \PYGZdq{}} \PYG{p}{+} \PYG{n}{s}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}In parentheses: \PYGZdq{}} \PYG{p}{+} \PYG{n}{InsideParen}\PYG{p}{(}\PYG{n}{s}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{c+c1}{/// Assume s contains parentheses.}
   \PYG{c+c1}{/// Return the substring between the first parentheses.}
   \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{InsideParen}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{int} \PYG{n}{first} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s+sc}{\PYGZsq{}(\PYGZsq{}}\PYG{p}{)} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}  
      \PYG{k+kt}{int} \PYG{n}{past} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s+sc}{\PYGZsq{})\PYGZsq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{k+kt}{int} \PYG{n}{len} \PYG{p}{=} \PYG{n}{past} \PYG{p}{\PYGZhy{}} \PYG{n}{first}\PYG{p}{;}
      \PYG{k}{return} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Substring}\PYG{p}{(}\PYG{n}{first}\PYG{p}{,} \PYG{n}{len}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

It is a silly assumption, but until we get to {\hyperref[decisions:if-statements]{\emph{Decisions}}},
we will have to assume there \emph{is}
a parenthesized expression in the parameter string.


\subsubsection{String Methods Exercise}
\label{stringmethods:string-methods-exercise}\begin{enumerate}
\item {} 
What is printed by this fragment?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{w} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}quickly\PYGZdq{}}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{w}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{w}\PYG{p}{[}\PYG{n}{w}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{\PYGZhy{}}\PYG{l+m}{2}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{w}\PYG{p}{.}\PYG{n}{Substring}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{w}\PYG{p}{.}\PYG{n}{Substring}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{w}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}ti\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{w}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}ick\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{k+kt}{int} \PYG{n}{k} \PYG{p}{=} \PYG{n}{w}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}c\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} \PYGZob{}1\PYGZcb{} \PYGZob{}2\PYGZcb{} \PYGZob{}3\PYGZcb{}\PYGZdq{}}\PYG{p}{,}
   \PYG{n}{k}\PYG{p}{,} \PYG{n}{w}\PYG{p}{[}\PYG{n}{k}\PYG{p}{]}\PYG{p}{,} \PYG{n}{w}\PYG{p}{[}\PYG{n}{k}\PYG{p}{\PYGZhy{}}\PYG{l+m}{3}\PYG{p}{]}\PYG{p}{,} \PYG{n}{w}\PYG{p}{.}\PYG{n}{Substring}\PYG{p}{(}\PYG{n}{k}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
What is printed by this fragment?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}HELLO!\PYGZdq{}}\PYG{p}{,} \PYG{n}{t} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{ToLower}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{+}\PYG{n}{t}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\end{enumerate}

Play with csharp:  Declare other strings and make up
string expressions with these methods
for which you predict the value and then test.

\index{string!problem solving}\index{problem solving}

\section{A Creative Problem Solution}
\label{problem-solving-replace:index-0}\label{problem-solving-replace:a-creative-problem-solution}\label{problem-solving-replace::doc}\label{problem-solving-replace:solve-string-replace}
Thus far the exercises and examples suggested have been of
a very simple form, where the idea of the steps should
have been pretty clear, and the main issue was just
translating syntax into C\#, one instruction at a time.

We still have a lot of syntax to concentrate on,
but still, early on, we wanted to get in some real thought
of problem solving.  To get very interesting you
need a number of options that might be combined in
a variety of ways.  The short list of
string methods just introduced
is likely give us enough to think about....

Here is a basic string manipulation problem:
given a string, like,
\code{"It was the best of times."},
find and replace a specified part of it by another string.
For instance replace \code{"best"} by \code{"worst"}.
In this example we would get the result:
\code{"It was the worst of times."}.

It is very important to give concrete examples to
illustrate the idea desired.  Our human brains may be
very quick to see a solution like this in a very
concrete case, but what about making it general?

First this seems like a basic logical operation worthy
of a function or method, so we need a heading.
(Confession:  there are methods in the class
string for replacement, but this is a good learning exercise,
so we are starting over on our own.)  Since
we cannot change the string class, we will write a
static function to generate the new string.

For simplicity at the moment we will only change
the first occurrence, and for now we will assume the
replacement makes sense.  The following heading
(with documentation) should work:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
    \PYG{c+c1}{/// Return s with the first occurence of target}
    \PYG{c+c1}{/// replaced by replacement.}
    \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{replaceFirst}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{target}\PYG{p}{,}
                               \PYG{k+kt}{string} \PYG{n}{replacement}\PYG{p}{)}
\end{Verbatim}

As soon as we have the calling interface, it is good to be thinking
of the tests it should pass.  Here is a Main program written
to test the function in different ways and display the results:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
    \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main} \PYG{p}{(}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
        \PYG{k+kt}{string} \PYG{n}{str1} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}It was the best of times.\PYGZdq{}}\PYG{p}{;}
        \PYG{k+kt}{string} \PYG{n}{str2} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Of times it was the best.\PYGZdq{}}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}str1=\PYGZdq{}} \PYG{p}{+} \PYG{n}{str1}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}str2=\PYGZdq{}} \PYG{p}{+} \PYG{n}{str2}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
        \PYG{c+c1}{// to embed a quote inside a string constant, precede it by backslash(\PYGZbs{}).}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Let us do some \PYGZbs{}\PYGZdq{}cutting and pasting\PYGZbs{}\PYGZdq{} of strings!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
        \PYG{k+kt}{string} \PYG{n}{str3} \PYG{p}{=} \PYG{n}{replaceFirst}\PYG{p}{(}\PYG{n}{str1}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}best\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}worst\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}str3 = str1 with best =\PYGZgt{} worst: \PYGZdq{}} \PYG{p}{+} \PYG{n}{str3}\PYG{p}{)}\PYG{p}{;}
        \PYG{k+kt}{string} \PYG{n}{str4} \PYG{p}{=} \PYG{n}{replaceFirst}\PYG{p}{(}\PYG{n}{str2}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}best\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}worst\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}str2 with best =\PYGZgt{} worst: \PYGZdq{}} \PYG{p}{+} \PYG{n}{str4}\PYG{p}{)}\PYG{p}{;}
        \PYG{k+kt}{string} \PYG{n}{str5} \PYG{p}{=} \PYG{n}{replaceFirst}\PYG{p}{(}\PYG{n}{str3}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}worst\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}best\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}str3 with worst =\PYGZgt{} best: \PYGZdq{}} \PYG{p}{+} \PYG{n}{str5}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Writing tests \emph{first} is a good idea to focus you on what really
needs to be accomplished, and then running tests later is a snap!

The human brain and eyes are fabulous in the way they process
many things in parallel and use tools you have accumulated over
a lifetime.  In particular this substitution idea should
seem pretty reasonable, and given any \emph{specific concrete} example,
you are likely to be able to solve it instantly, with very little
conscious effort.  Once it becomes a programming problem, with
parameters stated in general, with just placeholder names
like \code{s} and \code{target}, and given the limited set of approaches
you have in a programming language, then the complexion of this
problem changes completely.  Many students guess the general problem will
be nearly as simple as the concrete examples they do in their heads,
and then get very discouraged when the answer does not flow out of
them.  In fact it takes practice and experience, and it is easier
to handle if you acknowledge that up front!

So let's start in with the practice, and gain some experience.
With \code{s}, \code{target}, and \code{replacement} all being general, this
problem could easily be too much to contemplate at once,
so let us replace \emph{concrete} examples by generality gradually.
The idea is to get to the end.  Rather than trying to jump a chasm,
we can take small steps and go around.

A basic idea is to make small incremental
changes, test at each stage, and gradually see more of the tests
(that you have already written) be satisfied.  Also, if you make a
mistake and screw up something that worked before, you can generally
focus on the small addition to see where the mistakes were.
\footnote{
We will not go far into the history of software engineering
practice here, but these incremental problem solving methods
were first widely
introduced as a part of \emph{extreme programming}.
That name gives you an idea of the newness at the time.
}

This also avoids you needing to keep too much in your head at once.

We do have code written already:  The test code.  Start by writing
something that will trivially satisfy the first concrete test.
The body of the function can be just:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{return} \PYG{l+s}{\PYGZdq{}It was the worst of times\PYGZdq{}}\PYG{p}{;}
\end{Verbatim}

This is a tiny, easy, silly looking step, but it does accomplish
two things:  It makes sure we can produce output
in the proper string form, and the test code runs, passing the
first test.

Now we gradually get more complicated.  We will continue to assume
\code{target} and \code{replacement} are as in the original example,
and \code{target} is in the same place in \code{s},
but suppose we imagine each
of the other characters in \code{s} may be something different:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+s}{\PYGZdq{}???????????best??????????\PYGZdq{}}
\end{Verbatim}

Now we have to start thinking about what we have to work with.
We have a string, and we have string methods.
Have a look at the ideas of each method (exact syntax
not important at the moment).  Clearly we are going to have to
deal with parts of strings, and the methods to deal with parts
involve indices, so let us add to our visual model:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Index}\PYG{p}{:} \PYG{l+m}{0}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{3}\PYG{l+m}{4}\PYG{l+m}{5}\PYG{l+m}{6}\PYG{l+m}{7}\PYG{l+m}{8}\PYG{l+m}{9}\PYG{l+m}{0}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{3}\PYG{l+m}{4}\PYG{l+m}{5}\PYG{l+m}{6}\PYG{l+m}{7}\PYG{l+m}{8}\PYG{l+m}{9}\PYG{l+m}{0}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{3}\PYG{l+m}{4}
    \PYG{n}{s}\PYG{p}{:} \PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{n}{best}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}\PYG{p}{?}
\end{Verbatim}

Continue in class....  The example program stub is
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/string\_manip\_stub/string\_manip.cs}{string\_manip\_stub/string\_manip.cs}.

In general, when given a
project with ``stub'' in it, you should copy the files into a project
of your own and make modifications.  Though the original version
should compile and run, it does not do much without your additions.
In stubs where you need to
complete a function with a return value, you will often see
a dummy choice for the return statement, just so the stub compiles.
Where the return type is string \code{"Not implemented"} is a handy
temporary choice.

When you have that function version, test it.
You will need to rename
our incremental variations so the current version has the name
used in Main.

What might further advances toward full generality be,
in small steps?  We pinned \code{best} at a specific location.
We could remove that assumption.  The location will still be
important, but we do not know it ahead of time....

A further advance would be a version that is complete
in all ways, except we still assume \code{target} is in \code{s},
but beyond that, do not assume what the three parameters are.

Finally we should allow \code{s} to not contain \code{target}
(though this requires the central idea of the next chapter).

The testing regime in \code{Main} is clear to understand and write,
but pretty primitive.  You have to look at a lot of output
every time you test.  We will come up with better testing schemes
later.
\phantomsection\label{lab-string-ops:lab-string-ops}
\index{labs!string manipulations}

\section{Lab: String Operations}
\label{lab-string-ops:index-0}\label{lab-string-ops::doc}\label{lab-string-ops:lab-string-operations}

\subsection{Goals for this lab:}
\label{lab-string-ops:goals-for-this-lab}\begin{enumerate}
\item {} 
Explore some of the properties of the pre-defined String class.

\item {} 
Write conditional statements.

\item {} 
Think about problem solving.

\end{enumerate}

This lab depends on the introductory material earlier in this
chapter, particularly keep handy {\hyperref[stringmethods:string-methods-length]{\emph{Summary of String Length and Some Instance Methods}}}.
Be mindful of the processes developed in class filling in
{\hyperref[problem-solving-replace:solve-string-replace]{\emph{A Creative Problem Solution}}}.

Parts 2 and 4 also depend on {\hyperref[decisions:if-statements]{\emph{Decisions}}}
through {\hyperref[comparisonops:more-conditional-expressions]{\emph{More Conditional Expressions}}}.

Design, compile and run a single C\# program to accomplish all of
the following tasks. Add one part at a time and test before trying the
next one. The program can just include a Main method, or it is neater to
split things into separate methods (all static void, with names like
ShowLength, SentenceType, LastFirst1, LastFirst),
and have Main call all the ones
you have written so far (or for testing purposes, just the one you
are working on, with the other function calls commented out).
\textbf{Use the UIF class for user input.}  You can copy the file into your project.

Alternately practice using an Xamarin Studio library reference:
Create a new project in a solution
in which you already have added the ui library project.  Make the ui project
be a reference for the lab project.

Make sure your program has \code{namespace IntroCS;} to match the ui project.
Beware of modifying the sample Program.cs generated by Xamarin Studio - it will use
the project name for a namespace.  We are never going to use that.
\begin{enumerate}
\item {} 
Read a string from the keyboard
and print the length of the string, with a label.

\item {} 
Read a sentence (string) from a line of input, and print whether
it represents a \emph{declarative} sentence (i.e. ending in a period),
\emph{interrogatory} sentence (ending in a question mark), or an
\emph{exclamation} (ending in exclamation point) or is not a sentence
(anything else).

This may be the first time you write a conditional
statement. (This needs the next chapter.)
It makes sense to only make small changes at once and build
up to final code. First you might just code it to check if a sentence is
declarative or not. Then remember you can test further cases with
\code{else if (...)}.

\item {} 
Read a whole name from a line of input.  Assume first and last names
are separated by a space (no middle name).
Print last name first followed by a comma
and a space, followed by the first name.
For example, if the input is
\code{"Marcel Proust"}, the output is \code{"Proust, Marcel"}.

\item {} 
Improve the previous part,
so it also allows a single name without spaces,
like ``Socrates'', and prints the original without change. If there are
two parts of the name, it should work as in the original version.
(This needs the next chapter.)

\end{enumerate}

Run the program (with parts 1, 2 and 4 active)
from a terminal window and show your TA when you are
done.  You should run it twice to show off both paths through
part 4.  Alternately have the main program just call part 4 twice!


\section{Chapter Review Questions}
\label{reviewstring:chapter-review-questions}\label{reviewstring::doc}\begin{enumerate}
\item {} 
What is printed by this fragment?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}question\PYGZdq{}}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Substring}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Substring}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}ti\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}to\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{k+kt}{int} \PYG{n}{j} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}u\PYGZdq{}}\PYG{p}{)}\PYG{p}{,} \PYG{n}{k} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}o\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} \PYGZob{}1\PYGZcb{} \PYGZob{}2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{j}\PYG{p}{,} \PYG{n}{k}\PYG{p}{,} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Substring}\PYG{p}{(}\PYG{n}{j}\PYG{p}{,} \PYG{n}{k}\PYG{p}{\PYGZhy{}}\PYG{n}{j}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
What is printed by this fragment?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Word\PYGZdq{}}\PYG{p}{;}
\PYG{n}{s}\PYG{p}{.}\PYG{n}{ToUpper}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
What is printed by this fragment?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{a} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}hi\PYGZdq{}}\PYG{p}{,} \PYG{n}{b} \PYG{p}{=} \PYG{n}{a}\PYG{p}{.}\PYG{n}{ToUpper}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{a}\PYG{p}{+}\PYG{n}{b}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
Are strings mutable or immutable: which?

\item {} 
What is the distinction syntactically between the use of a
method and a property?

\item {} 
Suppose we have a string \code{s}.
Is this expression legal, or what should it be?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{(}\PYG{p}{)}
\end{Verbatim}

\end{enumerate}

\index{statement!if}\index{if}

\chapter{Decisions}
\label{decisions:if-statements}\label{decisions:index-0}\label{decisions::doc}\label{decisions:decisions}

\section{Conditions I}
\label{conditions:conditions-i}\label{conditions:simple-conditions}\label{conditions::doc}
Thus far, within a given function, instructions have been executed
sequentially, in the same order as written.  Of course that is often
appropriate!  On the other hands if you are planning your instruction
sequence,
you can get to a place where you say, ``Hm, that depends....'', and
a choice must be made.  The simplest choices are two-way: do one
thing if a condition is true, and another (possibly nothing) if the
condition is not true.

More syntax for conditions will be introduced later,
but for now consider simple arithmetic comparisons that directly
translate from math into C\#. First start csharp an enter:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{1}\PYG{p}{;}
\end{Verbatim}

Now think of which of these expressions below are true and which false,
and then enter each one into your csharp session to test:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+m}{2} \PYG{p}{\PYGZlt{}} \PYG{l+m}{5}
\PYG{l+m}{3} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}
\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{1}\PYG{l+m}{0}
\PYG{l+m}{2}\PYG{p}{*}\PYG{n}{x} \PYG{p}{\PYGZlt{}} \PYG{n}{x}
\end{Verbatim}

You see the C\# values, either \code{true} or \code{false} (with no
quotes!). These are the only possible \emph{Boolean} values (named after
19th century mathematician George Boole). You can also use the
abbreviation for the type \code{bool}.  It is the type of the
results of true-false conditions or tests.

The simplest place to use conditions is in a decision made with an
\code{if} statement.

We will consider {\hyperref[comparisonops:more-conditional-expressions]{\emph{More Conditional Expressions}}} later, but this is a
quick start with the easiest ones.


\section{Simple \texttt{if} Statements}
\label{ifstatements::doc}\label{ifstatements:simple-if-statements}\label{ifstatements:id1}
Run the example program, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/suitcase/suitcase.cs}{suitcase/suitcase.cs}.
Try it at least twice, with
inputs: 30 and then 55. As you can see, you get an extra result,
depending on the input. The main code is:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
         \PYG{k+kt}{double} \PYG{n}{weight} \PYG{p}{=} 
                \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptDouble}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}How many pounds does your suitcase weigh? \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{weight} \PYG{p}{\PYGZgt{}} \PYG{l+m}{5}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}There is a \PYGZdl{}25 charge for luggage that heavy.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Thank you for your business.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

The lines labeled 3-5 are an \code{if} statement. It reads pretty much
like English. If it is true that the weight is greater than 50,
then print the statement about an extra charge. If it is not true
that the weight is greater than 50, then skip the part
right after the condition about
printing the extra luggage charge.
In any event, when
you have finished with the \code{if} statement (whether it actually does
anything or not), go on to the next statement.
In this case that is the statement
printing ``Thank you''.
An \code{if} statement only breaks the  normal sequential order
\emph{inside} the \code{if} statement itself.

The general C\# syntax for a simple \code{if} statement is
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{if (} \emph{condition} \code{)}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement
\end{DUlineblock}
\end{DUlineblock}
\end{quote}

The condition is an expression that is true or false, of {\hyperref[data_types-and-conversions:type-boolean]{\emph{Type Boolean or bool}}}.

\index{compound statement!\{ \}}\index{\{ \}!compound statement}\index{statement!compound}
Often you want multiple statements executed when the condition
is true.  We have used braces before.  We have not said
what they do technically, syntactically:  braces around
a group of statements technically makes a single
\emph{compound statement}.  So the pattern commonly written is:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{if (} \emph{condition} \code{) \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] one or more statements
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

If the condition is true, then do the statement(s) in braces. If the
condition is not true, then skip the statements in braces.  The
indentation pattern is also illustrated.  Recall the compiler
does not care about the amount of whitespace, but humans do.
In general indent the statements inside a compound statement.
Later in:ref:\emph{missing-braces} we will see
that there is good reason to use this format
with braces \emph{even} if there is just one statement inside the braces.

Another fragment as an example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{balance} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{transfer} \PYG{p}{=} \PYG{p}{\PYGZhy{}}\PYG{n}{balance}\PYG{p}{;}
    \PYG{c+c1}{// transfer enough from the backup account:}
    \PYG{n}{backupAccount} \PYG{p}{=} \PYG{n}{backupAccount} \PYG{p}{\PYGZhy{}} \PYG{n}{transfer}\PYG{p}{;}
    \PYG{n}{balance} \PYG{p}{=} \PYG{n}{balance} \PYG{p}{+} \PYG{n}{transfer}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The assumption
in the example above is that if an account goes negative, it is
brought back to 0 by transferring money from a backup account in
\emph{several} steps.

In the examples above the choice is between doing something (if the
condition is \code{true}) or nothing (if the condition is \code{false}).
Often there is a choice of two possibilities, only one of which
will be done, depending on the truth of a condition....


\subsection{Simple If Exercise}
\label{ifstatements:simple-if-exercise}
Think of two different inputs you could give that would make the
execution of the code fragment proceed differently.  What would happen in
each case?  (Assume we have access to the class UIF.)
\begin{enumerate}
\item {} 
Consider:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{v} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter a word: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{v}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{3}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{v} \PYG{p}{=} \PYG{n}{v} \PYG{p}{+} \PYG{n}{v}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Now we have \PYGZdq{}} \PYG{p}{+} \PYG{n}{v}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
Consider:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter a integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}The magnitude of \PYGZdq{}} \PYG{p}{+} \PYG{n}{x} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} is \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{x} \PYG{p}{=} \PYG{p}{\PYGZhy{}}\PYG{n}{x}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\end{enumerate}

\index{if-else}

\section{\texttt{if}-\texttt{else} Statements}
\label{ifelse:index-0}\label{ifelse:if-else-statements}\label{ifelse::doc}\label{ifelse:id1}
Run the example program, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/clothes/clothes.cs}{clothes/clothes.cs}. Try it at least twice, with
inputs 50 and then 80. As you can see, you get different results,
depending on the input. The main code of \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/clothes/clothes.cs}{clothes/clothes.cs} is:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
         \PYG{k+kt}{double} \PYG{n}{temperature} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptDouble}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}What is the temperature? \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{temperature} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Wear shorts.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{else} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Wear long pants.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Get some exercise outside.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

The lines labeled 2-7 are an \code{if}-\code{else} statement. Again it is
close to English, though you might say ``otherwise'' instead of
``else'' (but else is shorter!). There are two indented statements
in braces:
One, like in the simple \code{if} statement, comes right after the
\code{if} condition and is executed when the condition  is true.
In the \code{if}-\code{else} form this is followed by an
\code{else} (lined up under the \code{if} by convention),
followed by another indented statement enclosed in braces that is only
executed when the original condition is \emph{false}. In an \code{if}-\code{else}
statement exactly one of two possible parts in braces is executed.

A final line is also shown that is not indented, about getting exercise.
The \code{if} and \code{else} clauses each
only embed a \emph{single} (possibly compound) statement
as option, so the last statement is not part of the \code{if}-\code{else}
statement.  It is beyond the \code{if}-\code{else} statement; it is
just a part of the normal sequential
flow of statements.  We repeat:

\begin{notice}{note}{Note:}
Inside an \code{if}-\code{else} there is a
choice made of which clause to execute and which clause to skip,
but the whole \code{if}-\code{else} construction is a \emph{single}
larger statement, which exists in the normal \emph{sequential} flow
of execution.
\end{notice}

The compiler does not require the indentation of the if-true-statement
and the if-false-statement, but it is a standard style convention.

The general C\# \code{if}-\code{else} syntax is
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{if (} \emph{condition} \code{) \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement(s) for if-true
\end{DUlineblock}
\item[] \code{\}}
\item[] \code{else \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement(s) for if-false
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

The statements chosen based on the condition
can be any kind of statement.  This is the suggested form, but
as with the plain \code{if} statement, the if-true compound statement or
the if-false compound statement can be replace by a single statement
without braces, except in one otherwise ambiguous situation later,
{\hyperref[ifpitfalls:match-wrong-if]{\emph{Match Wrong if With else}}}.
\phantomsection\label{ifelse:compound-statement-scope}
\index{scope!compound statement}\index{compound statement!scope}\index{\{ \}!scope}

\subsection{Scope With Compound Statements}
\label{ifelse:scope-with-compound-statements}\label{ifelse:index-1}
The section {\hyperref[localscope:local-scope]{\emph{Local Scope}}} referred to function  bodies,
which happen to be enclosed in braces, making the function body a \emph{compound statement}.
In fact variables declared inside \emph{any} compound statement have their scope restricted
to \emph{inside} that compound statement.

As a result the following code makes no sense:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{BadBlockScope}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k}{if} \PYG{p}{(} \PYG{n}{x} \PYG{p}{\PYGZlt{}} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{int} \PYG{n}{val} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{l+m}{2}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{else} \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{int} \PYG{n}{val} \PYG{p}{=} \PYG{n}{x} \PYG{p}{\PYGZhy{}} \PYG{l+m}{2}\PYG{p}{:}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{return} \PYG{n}{val}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The \code{if}-\code{else} statement is legal, but useless,
because whichever compound statement gets executed,
\code{val} ceases being defined after the
closing brace of its compound statement,
so the \code{val} in the return statement has
not been declared or given a value.  The code
would generate a compiler error.

If we want \code{val} be used inside the braces and
to make sense past the end of the compound statement,
it cannot be declared inside the braces. Instead it must be
declared before the compound statements that are parts of the
\code{if}-\code{else} statement.   A local variable in a function declared before a nested compound
statement is still visible (in scope) \emph{inside}  that compound statement.
The following would work:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{OkScope}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{val}\PYG{p}{;}  
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZlt{}} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{val} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{l+m}{2}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{else} \PYG{p}{\PYGZob{}}
            \PYG{n}{val} \PYG{p}{=} \PYG{n}{x} \PYG{p}{\PYGZhy{}} \PYG{l+m}{2}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{val}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

There is even more subtlety here than meets the eye:
An \code{if}-\code{else} statement can generally be rewritten as two simple
if statements (though it is less efficient and less clear).
The two \code{if} statements would use opposite conditions, as in this variation:

\index{compiler error!uninitialized local variable}
\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{OkScope2}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{c+c1}{// without the = 0: Unassigned local variable error}
         \PYG{k+kt}{int} \PYG{n}{val} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}  
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZlt{}} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{val} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{l+m}{2}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{val} \PYG{p}{=} \PYG{n}{x} \PYG{p}{\PYGZhy{}} \PYG{l+m}{2}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{val}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Note that in this variation we added an
initialization for \code{val} to be 0, though the
value of the initialization is never used:  \code{val} is
guaranteed to be assigned a value in one of the \code{if} statements
before its value is used in the return statement.

Open Xamarin Studio with the examples solution, and open
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/ok\_if\_scope/ok\_if\_scope.cs}{ok\_if\_scope/ok\_if\_scope.cs} in the edit window.
The last function, \code{OkScope2},
is the one shown above.  Now \emph{remove} the logically
unnecessary \code{= 0} initialization for \code{val} so the line is just \code{int val;}.
As the comment says, an error should
appear (at least after you try to compile the program).
The error will say that there is an uninitialized local variable!  Why?

For safety
the C\# compiler has some basic analysis to check that every local
variable gets given a value before its value is used.  In the \code{OkScope} function
there is no \emph{one}
place where \code{val} gets an initial value, but the compiler is smart enough to see
that one of the branches of any if-else statement is always taken,
and \code{val} gets a value in each, so there is
no problem.

The compiler analysis is not complete:  It does not actually evaluate any
expressions.  This is good enough to catch many initialization errors that coders make,
but it
is not sufficient in general: We can see this from the altered \code{OkScope2}.

The original code shows the fix:  Give a dummy initialization that is never used
in execution, but keeps the compiler happy.

Although this extra initialization is annoying, the extra step is rarely needed.
Meanwhile it is very easy to forget to give a value to a local variable before use!
Having
the error caught quickly by the compiler is very handy, offsetting the extra work
when the compiler gives this error unnecessarily.


\subsection{If-else Exercise}
\label{ifelse:if-else-exercise}
Think of two different inputs you could give that would make the
execution of the code fragment proceed differently.  What would happen in
each case?  (Assume we have access to the class UIF.)
\begin{enumerate}
\item {} 
Consider:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{v} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter a word: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{v}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{3}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{v} \PYG{p}{=} \PYG{n}{v} \PYG{p}{+} \PYG{n}{v}\PYG{p}{;}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Now we have \PYGZdq{}} \PYG{p}{+} \PYG{n}{v}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}We still have \PYGZdq{}} \PYG{p}{+} \PYG{n}{v}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
Consider:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter a integer: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}The magnitude of \PYGZdq{}} \PYG{p}{+} \PYG{n}{x} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} is \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{\PYGZhy{}}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\end{enumerate}

\index{boolean expression}\index{comparison \textless{} \textgreater{} \textless{}= \textgreater{}= == !=}\index{\textless{} less than}\index{\textless{}= less than or equal}\index{\textgreater{} greater than}\index{\textgreater{}= greater than or equal}\index{== equality test}\index{!= inequality test}

\section{More Conditional Expressions}
\label{comparisonops:index-0}\label{comparisonops:more-conditional-expressions}\label{comparisonops::doc}\label{comparisonops:id1}
All the usual arithmetic comparisons may be made in C\#, but many do not
use standard mathematical symbolism, mostly for lack of proper keys
on a standard keyboard.
(If you are looking at the following table in the html version,
you need to be online and may need an up-to-date browser
to see these mathematical symbols be displayed correctly,
as well as the mathematical expressions later in the text.  The pdf version
of the book automatically shows all the right math symbolism online or offline.

\begin{tabulary}{\linewidth}{|L|L|L|}
\hline
\textsf{\relax 
Meaning
} & \textsf{\relax 
Math Symbol
} & \textsf{\relax 
C\# Symbols
}\\
\hline
Less than
 & 
\(<\)
 & 
\code{\textless{}}
\\
\hline
Greater than
 & 
\(>\)
 & 
\code{\textgreater{}}
\\
\hline
Less than or equal
 & 
\(\leq\)
 & 
\code{\textless{}=}
\\
\hline
Greater than or equal
 & 
\(\geq\)
 & 
\code{\textgreater{}=}
\\
\hline
Equals
 & 
\(=\)
 & 
\code{==}
\\
\hline
Not equal
 & 
\(\neq\)
 & 
\code{!=}
\\
\hline\end{tabulary}


There should not be space between the two-symbol C\#
substitutes.

Notice that the obvious choice for \emph{equals}, a single equal sign,
is \emph{not} used to check for equality. An annoying second equal sign
is required. This is because the single equal sign is already used
for \emph{assignment} in C\#, so it is not available for tests.

\begin{notice}{warning}{Warning:}
It is a common error to use only one equal sign when you mean to \emph{test}
for equality, and not make an assignment!
\end{notice}

Tests for equality do not make an assignment. Tests for equality can have an
arbitrary expression on the left, not just a variable.

All these tests work for numbers,
and characters.  Strings can also be compared, most often for
equality (==) or inequality (!=), though they also have a defined order,
so you can use \code{\textless{}}, for instance.

Predict the results and try each line in csharp:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{n}{x}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{6}\PYG{p}{;}
\PYG{n}{x}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{!}\PYG{p}{=} \PYG{l+m}{6}\PYG{p}{;}
\PYG{n}{x} \PYG{p}{=} \PYG{l+m}{6}\PYG{p}{;}
\PYG{l+m}{6} \PYG{p}{=}\PYG{p}{=} \PYG{n}{x}\PYG{p}{;}
\PYG{l+m}{6} \PYG{p}{!}\PYG{p}{=} \PYG{n}{x}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}hi\PYGZdq{}} \PYG{p}{=}\PYG{p}{=} \PYG{l+s}{\PYGZdq{}h\PYGZdq{}} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}i\PYGZdq{}}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}HI\PYGZdq{}} \PYG{p}{!}\PYG{p}{=} \PYG{l+s}{\PYGZdq{}hi\PYGZdq{}}\PYG{p}{;}
\PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Hello\PYGZdq{}}\PYG{p}{;}
\PYG{k+kt}{string} \PYG{n}{t} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}HELLO\PYGZdq{}}\PYG{p}{;}
\PYG{n}{s} \PYG{p}{=}\PYG{p}{=} \PYG{n}{t}\PYG{p}{;}
\PYG{n}{s}\PYG{p}{.}\PYG{n}{ToUpper}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{n}{t}\PYG{p}{;}
\end{Verbatim}

An equality check does not make an assignment. Strings equality tests are case
sensitive.

\textbf{Try this}: Following up on the discussion of the \emph{inexactness} of float
arithmetic, confirm that C\#
does not consider .1 + .2 to be equal to .3: Write a simple
condition into csharp to test.
\paragraph{Pay with Overtime Example}

Given a person's work
hours for the week and regular hourly wage, calculate the total pay
for the week, taking into account overtime. Hours worked over 40
are overtime, paid at 1.5 times the normal rate. This is a natural
place for a function enclosing the calculation.

\emph{Read} the setup for the function:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return the total weekly wages for a worker working }
      \PYG{c+c1}{/// totalHours with a given regular hourlyWage.  }
      \PYG{c+c1}{/// Include overtime for hours over 40.}
      \PYG{k}{static} \PYG{k+kt}{double} \PYG{n+nf}{CalcWeeklyWages}\PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{totalHours}\PYG{p}{,} \PYG{k+kt}{double} \PYG{n}{hourlyWage}\PYG{p}{)}
\end{Verbatim}

The problem clearly indicates two cases: when no more than 40
hours are worked or when more than 40 hours are worked. In case
more than 40 hours are worked, it is convenient to introduce a
variable overtimeHours. You are encouraged to think about a
solution before going on and examining mine.

You can try running my complete example program, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/wages1/wages1.cs}{wages1/wages1.cs},
also shown below.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{k}{class} \PYG{n+nc}{Wages}
   \PYG{p}{\PYGZob{}}                                                   \PYG{c+c1}{//heading chunk}
      \PYG{c+c1}{/// Return the total weekly wages for a worker working }
      \PYG{c+c1}{/// totalHours with a given regular hourlyWage.  }
      \PYG{c+c1}{/// Include overtime for hours over 40.}
      \PYG{k}{static} \PYG{k+kt}{double} \PYG{n+nf}{CalcWeeklyWages}\PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{totalHours}\PYG{p}{,} \PYG{k+kt}{double} \PYG{n}{hourlyWage}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}                                                
         \PYG{k+kt}{double} \PYG{n}{totalWages}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{totalHours} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{4}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{totalWages} \PYG{p}{=} \PYG{n}{hourlyWage}\PYG{p}{*}\PYG{n}{totalHours}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{else} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{double} \PYG{n}{overtime} \PYG{p}{=} \PYG{n}{totalHours} \PYG{p}{\PYGZhy{}} \PYG{l+m}{4}\PYG{l+m}{0}\PYG{p}{;}
            \PYG{n}{totalWages} \PYG{p}{=} \PYG{n}{hourlyWage}\PYG{p}{*}\PYG{l+m}{4}\PYG{l+m}{0} \PYG{p}{+} \PYG{p}{(}\PYG{l+m}{1.5}\PYG{p}{*}\PYG{n}{hourlyWage}\PYG{p}{)}\PYG{p}{*}\PYG{n}{overtime}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{totalWages}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{double} \PYG{n}{hours} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptDouble}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter hours worked: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{double} \PYG{n}{wage} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptDouble}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter dollars paid per hour: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{double} \PYG{n}{total} \PYG{p}{=} \PYG{n}{CalcWeeklyWages}\PYG{p}{(}\PYG{n}{hours}\PYG{p}{,} \PYG{n}{wage}\PYG{p}{)}\PYG{p}{;}  \PYG{c+c1}{//before chunk2}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}
            \PYG{l+s}{\PYGZdq{}Wages for \PYGZob{}0\PYGZcb{} hours at \PYGZdl{}\PYGZob{}1:F2\PYGZcb{} per hour are \PYGZdl{}\PYGZob{}2:F2\PYGZcb{}.\PYGZdq{}}\PYG{p}{,}
            \PYG{n}{hours}\PYG{p}{,} \PYG{n}{wage}\PYG{p}{,} \PYG{n}{total}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}                                                \PYG{c+c1}{//after chunk2}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{format!digits shown in string}\index{precision!format with \{:F\#\}}\index{digits formatted in string}\index{:!string precision formatting}
This program also introduces new notation for
displaying decimal numbers:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}
            \PYG{l+s}{\PYGZdq{}Wages for \PYGZob{}0\PYGZcb{} hours at \PYGZdl{}\PYGZob{}1:F2\PYGZcb{} per hour are \PYGZdl{}\PYGZob{}2:F2\PYGZcb{}.\PYGZdq{}}\PYG{p}{,}
            \PYG{n}{hours}\PYG{p}{,} \PYG{n}{wage}\PYG{p}{,} \PYG{n}{total}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

In the format string are \code{\{1:F2\}} and \code{\{2:F2\}}:  Inside
the braces, after the parameter index, you see a new part,
\code{:F2}.
The part after the colon gives additional formatting information.
In this case: Display with the decimal point
fixed (hence the \textbf{F}) so  \textbf{2} places beyond the decimal
point are shown.  Also the result is \emph{rounded}.
This is appropriate for money with dollars and cents.
You can replace the 2 to display
a different number of digits after the decimal point.
More formatting syntax is introduced in {\hyperref[forexamples:tables]{\emph{Tables}}}.

Because \code{if}-\code{else} statements alter the flow or execution, and altering this flow
causes lots of problems for many students, this is a good place to
play computer to illustrate clearly what is happening.  We will just
concentrate on a call to \code{CalcWeeklyWages}, where the \code{if}-\code{else}
statement is.

Recall that to play computer,
we keep track of the state of variables while following execution carefully,
statement by statement.
The big point here is that this order of execution is \emph{not} textual order!
If we are just following a call to \code{CalcWeeklyWages}, we start at
line 9, and we will assume for example that it is called with
\code{totalHour} as 50 and \code{hourlyWage} as 14.00:

\begin{tabulary}{\linewidth}{|L|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
totalWages
} & \textsf{\relax 
overtime
} & \textsf{\relax 
Comment
}\\
\hline
9
 & 
-
 & 
-
 & 
Assume passed totalHours=50; hourlyWage=14
\\
\hline
12
 &  &  & 
50 \textless{}= 40: false; SKIP if clause
\\
\hline
16
 &  & 
10
 & 
50-40=10 at start of else clause
\\
\hline
17
 & 
770
 &  & 
14*40 + (1.5*14)*10 = 770
\\
\hline
19
 &  &  & 
return 770 to caller
\\
\hline\end{tabulary}


We \emph{skipped} the executable line 13 in the if-true clause.

Instead suppose the function is called with
\code{totalHour} as 30 and \code{hourlyWage} as 14.00:

\begin{tabulary}{\linewidth}{|L|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
totalWages
} & \textsf{\relax 
overtime
} & \textsf{\relax 
Comment
}\\
\hline
9
 & 
-
 & 
-
 & 
Assume passed totalHours=30; hourlyWage=14
\\
\hline
12
 &  &  & 
30 \textless{}= 40: true; continue straight
\\
\hline
13
 & 
420
 &  & 
14*30 = 420; SKIP else clause
\\
\hline
19
 &  &  & 
return 420 to caller
\\
\hline\end{tabulary}


We skipped the executable lines 16-17
in the if-false clause after \code{else}.

Below is an equivalent alternative version of
\code{CalcWeeklyWages}, used in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/wages2/wages2.cs}{wages2/wages2.cs}. It uses just one
general calculation formula and sets the parameters for the formula
in the \code{if} statement. There are generally a number of ways you might
solve the same problem!

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{static} \PYG{k+kt}{double} \PYG{n+nf}{CalcWeeklyWages}\PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{totalHours}\PYG{p}{,} \PYG{k+kt}{double} \PYG{n}{hourlyWage}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}                       
         \PYG{k+kt}{double} \PYG{n}{regularHours}\PYG{p}{,} \PYG{n}{overtime}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{totalHours} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{4}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{regularHours} \PYG{p}{=} \PYG{n}{totalHours}\PYG{p}{;}
            \PYG{n}{overtime} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{else} \PYG{p}{\PYGZob{}}
            \PYG{n}{regularHours} \PYG{p}{=} \PYG{l+m}{4}\PYG{l+m}{0}\PYG{p}{;}
            \PYG{n}{overtime} \PYG{p}{=} \PYG{n}{totalHours} \PYG{p}{\PYGZhy{}} \PYG{l+m}{4}\PYG{l+m}{0}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{hourlyWage}\PYG{p}{*}\PYG{n}{regularHours} \PYG{p}{+} \PYG{p}{(}\PYG{l+m}{1.5}\PYG{p}{*}\PYG{n}{hourlyWage}\PYG{p}{)}\PYG{p}{*}\PYG{n}{overtime}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}


\subsection{Wages Play Computer Exercise}
\label{comparisonops:wages-play-computer-exercise}
We played computer on the original version of \code{CalcWeeklyWages}.  Now
follow the second version above, from \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/wages2/wages2.cs}{wages2/wages2.cs}.  Try it
with the same two sets of formal parameter values.

\begin{tabulary}{\linewidth}{|L|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
regularHours
} & \textsf{\relax 
overtime
} & \textsf{\relax 
Comment
}\\
\hline
1
 & 
-
 & 
-
 & 
Assume passed totalHours=50; hourlyWage=14
\\
\hline

 &  &  & \\
\hline

 &  &  & \\
\hline

 &  &  & \\
\hline

 &  &  & \\
\hline\end{tabulary}


\begin{tabulary}{\linewidth}{|L|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
regularHours
} & \textsf{\relax 
overtime
} & \textsf{\relax 
Comment
}\\
\hline
1
 & 
-
 & 
-
 & 
Assume passed totalHours=30; hourlyWage=14
\\
\hline

 &  &  & \\
\hline

 &  &  & \\
\hline

 &  &  & \\
\hline

 &  &  & \\
\hline\end{tabulary}



\subsection{Graduate Exercise}
\label{comparisonops:graduateex}\label{comparisonops:graduate-exercise}
Write a program, \code{graduate.cs}, that prompts students for how
many credits they have. Print whether of not they have enough
credits for graduation. (At Loyola University Chicago 120 credits
are needed for graduation.)


\subsection{Roundoff Exercise}
\label{comparisonops:roundoff-exercise}
In csharp declare and initialize  non-zero \code{double} variables
\code{x} and \code{y}.  Experiment so, according to C\# (and csharp):  \code{x+y == x}.
In other words, while \code{y} is not 0, adding it to  \code{x} does not
change \code{x}.  (Hints:  Note the approximate number of digits of accuracy
of a \code{double}, and remember the power of 10 notation with \code{E}
for \code{double} literals. See {\hyperref[data_types-and-conversions:type-double]{\emph{Type double}}} and the section on limits
after it.)

\index{if-else-if}

\section{Multiple Tests and \texttt{if}-\texttt{else} Statements}
\label{ifelsechained:multiple-tests-and-if-else-statements}\label{ifelsechained:multiple-tests}\label{ifelsechained:index-0}\label{ifelsechained::doc}
Often you want to distinguish between more than two distinct cases,
but conditions only have two possible results, \code{true} or \code{false},
so the only direct choice is between two options. As anyone who has
played ``20 Questions'' knows, you can distinguish more cases with
further questions. If there are more than two choices, a single
test may only reduce the possibilities, but further tests can
reduce the possibilities further and further. Since most any kind
of statement can be placed in the sub-statements in
an \code{if}-\code{else} statement, one
choice is a further \code{if} or \code{if}-\code{else} statement.
For instance consider a
function to convert a numerical grade to a letter grade, `A', `B',
`C', `D' or `F', where the cutoffs for `A', `B', `C', and `D' are
90, 80, 70, and 60 respectively. One way to write the function
would be to test for one grade at a time, and resolve all the
remaining possibilities inside the next \code{else} clause.
If we do this consistent with our indentation conventions so far:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k+kt}{char} \PYG{n+nf}{letterGrade}\PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{score}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k+kt}{char} \PYG{n}{letter}\PYG{p}{;}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{score} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{9}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{n}{letter} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}A\PYGZsq{}}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{else} \PYG{p}{\PYGZob{}}   \PYG{c+c1}{// grade must be B, C, D or F}
      \PYG{k}{if} \PYG{p}{(}\PYG{n}{score} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{8}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{letter} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}B\PYGZsq{}}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
      \PYG{k}{else} \PYG{p}{\PYGZob{}} \PYG{c+c1}{// grade must be C, D or F}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{score} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{7}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{letter} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}C\PYGZsq{}}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{else} \PYG{p}{\PYGZob{}}   \PYG{c+c1}{// grade must D or F}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{score} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{6}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{letter} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}D\PYGZsq{}}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
            \PYG{k}{else} \PYG{p}{\PYGZob{}}
               \PYG{n}{letter} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}F\PYGZsq{}}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}   \PYG{c+c1}{//end else D or F}
      \PYG{p}{\PYGZcb{}}      \PYG{c+c1}{// end of else C, D, or F}
   \PYG{p}{\PYGZcb{}}         \PYG{c+c1}{// end of else B, C, D or F}
   \PYG{k}{return} \PYG{n}{letter}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This repeatedly increasing indentation with an \code{if} statement in
the \code{else} clause can be annoying and distracting. Here is a preferred
alternative in this situation, that avoids all this further
indentation:
Combine each \code{else} and following \code{if} onto the same line,
and note that the \code{if} part after each else is just a \emph{single}
(possibly very complicated) statement.  This allows the elimination of
some of the braces:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return letter grade for score. }
      \PYG{k}{static} \PYG{k+kt}{char} \PYG{n+nf}{letterGrade}\PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{score}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{char} \PYG{n}{letter}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{score} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{9}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{letter} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}A\PYGZsq{}}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{else} \PYG{n+nf}{if} \PYG{p}{(}\PYG{n}{score} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{8}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{c+c1}{// grade must be B, C, D or F}
           \PYG{n}{letter} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}B\PYGZsq{}}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{else} \PYG{n+nf}{if} \PYG{p}{(}\PYG{n}{score} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{7}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{c+c1}{// grade must be C, D or F}
            \PYG{n}{letter} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}C\PYGZsq{}}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{else} \PYG{n+nf}{if} \PYG{p}{(}\PYG{n}{score} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{6}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{c+c1}{// grade must D or F}
            \PYG{n}{letter} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}D\PYGZsq{}}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{else} \PYG{p}{\PYGZob{}}
            \PYG{n}{letter} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}F\PYGZsq{}}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{letter}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

A program testing the letterGrade function is in
example program \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/grade1/grade1.cs}{grade1/grade1.cs}.

See {\hyperref[ifelsechained:gradeex]{\emph{Grade Exercise}}}.

As in a basic \code{if}-\code{else} statement, in the general format,
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{if (} \emph{condition1} \code{) \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement-block-run-if-condition1-is-true;
\end{DUlineblock}
\item[] \code{\}}
\item[] \code{else if (} \emph{condition2} \code{) \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement-block-run-if-condition2-is-the-first-true;
\end{DUlineblock}
\item[] \code{\}}
\item[] \code{else if (} \emph{condition3} \code{) \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement-block-run-if-condition3-is-the-first-true;
\end{DUlineblock}
\item[] \code{\}}
\item[] // ...
\item[] \code{else \{    //} \emph{no condition!}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement-block-run-if-no condition-is-true;
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

\emph{exactly one} of the statement blocks gets executed:
If some condition is true,
the first block following a true condition is executed.
If no condition is true,
the \code{else} block is executed.

Here is a variation. Consider this
fragment \emph{without} a final \code{else}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{weight} \PYG{p}{\PYGZgt{}} \PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Sorry, we can not take a suitcase that heavy.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{n+nf}{if} \PYG{p}{(}\PYG{n}{weight} \PYG{p}{\PYGZgt{}} \PYG{l+m}{5}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}There is a \PYGZdl{}25 charge for luggage that heavy.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This statement only prints one of two lines if there is a
problem with the weight of the suitcase.  Nothing is printed if
there is not a problem.

If the final \code{else} clause is omitted from the general \code{if} ... \code{else if} ...
pattern above, at most one block after a condition
is executed:  That is the block after the first true condition.
If all the conditions are false, none of the statement blocks
will be executed.

It is also possible to embed \code{if}-\code{else} statements inside other \code{if} or
\code{if}-\code{else} statements in more complicated patterns.


\subsection{Sign Exercise}
\label{ifelsechained:sign-exercise}
Write a program \code{sign.cs} to ask the user for a number. Print out
which category the number is in: \code{"positive"}, \code{"negative"}, or
\code{"zero"}.


\subsection{Grade Exercise}
\label{ifelsechained:gradeex}\label{ifelsechained:grade-exercise}
Copy \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/grade1/grade1.cs}{grade1/grade1.cs} to \code{grade2.cs} in your own project.
Modify
\code{grade2.cs} so it has an equivalent version of the letterGrade
function that tests in the opposite order, first for F, then D, C,
.... Hint: How many tests do you need to do? \footnote{
4 tests to distinguish the 5 cases, as in the previous version
}

Be sure to run your new version and test with different
inputs that test all the different paths through the program.

Be careful for edge cases:  Test the grades on the ``edge'' of a
change in the result.


\subsection{Wages Exercise}
\label{ifelsechained:wages-exercise}
Modify the \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/wages1/wages1.cs}{wages1/wages1.cs} or the \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/wages2/wages2.cs}{wages2/wages2.cs}
example to create a
program \code{wages3.cs} that assumes people are paid double time for
hours over 60. Hence they get paid for at most 20 hours overtime at
1.5 times the normal rate. For example, a person working 65 hours
with a regular wage of \$10 per hour would work at \$10 per hour for
40 hours, at 1.5 * \$10 for 20 hours of overtime, and 2 * \$10 for
5 hours of double time, for a total of
\begin{quote}

10*40 + 1.5*10*20 + 2*10*5 = \$800.
\end{quote}

You may find \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/wages2/wages2.cs}{wages2/wages2.cs} easier to adapt than
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/wages1/wages1.cs}{wages1/wages1.cs}.

Caution:  Be sure to thoroughly test your \emph{final} program version.  It is
easy to add new features that work by themselves, but break a part
that worked before! In particular in a program with decisions, make sure you
test with enough different data to check all lines of your program.


\section{If-statement Pitfalls}
\label{ifpitfalls:if-statement-pitfalls}\label{ifpitfalls::doc}
\index{semicolon after condition pitfall}\index{pitfall!if}\index{if!pitfall}

\subsection{Dangerous Semicolon}
\label{ifpitfalls:dangerous-semicolon}\label{ifpitfalls:index-0}\label{ifpitfalls:id1}
Regular statements must end with a semicolon.
It turns out that the semicolon is all you need to have a legal statement:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{p}{;}
\end{Verbatim}

We will see places that it is useful, but
meanwhile it can cause errors: You may be hard pressed to
remember to put semicolons at the end of all your statements, and in response you may
get compulsive about adding them at the end of statement
lines.  Be careful NOT to put one at the end of a method heading or
an \code{if} condition:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(} \PYG{n}{x} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// WRONG PROBABLY!}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

This code is deadly, since it compiles and is almost surely
\emph{not} what you mean.

Remember indentation and newlines are only significant for humans. The
two lines above are equivalent to:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(} \PYG{n}{x} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)}
   \PYG{p}{;}  \PYG{c+c1}{// Do nothing as statement when the condition is true}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// past if statement \PYGZhy{} do it always}
\end{Verbatim}

(Whenever you do need an empty statement, you are encouraged to put the
semicolon all by itself on a line, as above.)

If you always put an open brace \emph{directly} after the condition in an \code{if} statement,
you will not make this error:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(} \PYG{n}{x} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Then even if you were to add a semicolon:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(} \PYG{n}{x} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{p}{;}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

it would be a waste of a keystroke, but it would just be the first (empty) statement
inside the block, and the writing would still follow:
The extra semicolon would have no effect.

The corresponding error at the end of a method heading will at least
generate a compiler error, though it may appear cryptic:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{badSemicolon}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZob{}}
    \PYG{n}{x} \PYG{p}{=} \PYG{n}{x} \PYG{p}{+} \PYG{l+m}{2}\PYG{p}{;}
    \PYG{c+c1}{// ...}
\end{Verbatim}

This is another easy one to make and \emph{miss} - just one innocent semicolon.

\index{pitfall!dangling else!}\index{dangling else pitfall}\index{if-else!pitfall}

\subsection{Match Wrong \texttt{if} With \texttt{else}}
\label{ifpitfalls:match-wrong-if-with-else}\label{ifpitfalls:index-1}\label{ifpitfalls:match-wrong-if}
If you do not consistently put the substatements for the true
and false choices inside braces, you can run into problems from
the fact that the else part of an if statement is \emph{optional}.
Even if you use braces consistently,
you may well need to read code that does not place
braces around single statements. If C\# understood indentation as
in the recommended formatting style (or as required in Python),
the following would be OK:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{y} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}positive x and y\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{else}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}x not positive, untested y\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

Unfortunately placing the \code{else} under the first \code{if} is not enough to make
them go together (remember the C\# compiler ignores extra whitespace). The
following is equivalent to the compiler, with the else apparently going
with the second if:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{y} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}positive x and y\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{k}{else}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}x not positive, untested y\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

The compiler is consistent with the latter visual pattern: an \code{else} goes
with the most \emph{recent} \code{if} that could still take an \code{else}.
Hence if \code{x} is 3
and \code{y} is -2, the \code{else} part is executed and the statement printed is
incorrect: in this code
the else clause is only executed when \code{x} is positive and
\code{y} (\emph{is}
tested and) is not positive.

If you put braces everywhere to reinforce
your indentation, as we suggest, or if you only add the following
one set of braces around the inner if statement:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{y} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}positive x and y\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}x not positive, untested y\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

then the braces enclosing the inner \code{if} statement make it impossible for
the inner  \code{if} to continue on to an optional \code{else} part.
The \code{else} must go
with the first \code{if}. Now when the \code{else} part is reached, the statement
printed will be true: \code{x} is not positive, and the test of \code{y} was skipped.

\index{pitfall!need braces for if}\index{if!need braces}\index{braces needed with if}

\subsection{Missing Braces}
\label{ifpitfalls:id2}\label{ifpitfalls:index-2}\label{ifpitfalls:missing-braces}
Another place you can fool yourself with nice indenting style is
something like this.  Suppose we start with a perfectly reasonable

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}x is: positive\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

We may decide to avoid the braces, since there \emph{is} just one statement
that we want as the if-true part, but if we later decide
that we want this on two lines
and change it to

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}x is:\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}  positive\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

We are not going to get the behavior we want.
The word ``positive'' will \emph{always} be printed.

If we had first taken a bit more effort originally to write

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}x is: positive\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

then we could have split successfully into

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}x is:\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}  positive\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This way we do not have to keep worrying about this question when we revise:
``Have I switched to multiple lines after the \code{if}
and need to introduce braces?''

The last two of the pitfalls mentioned in this section are fixed by consistent
use of braces in the sub-statements of \code{if} statements.  They fix the \code{;}
after if-condition problem only if the open brace comes right after
the condition, but you still get a nasty error if you put in a semicolon
between the condition and opening brace.

\index{\&\&!boolean operation AND}\index{and \&\&}\index{boolean operation!\&\& AND}

\section{Compound Boolean Expressions}
\label{compoundconditions:index-0}\label{compoundconditions:compound-boolean-expressions}\label{compoundconditions::doc}\label{compoundconditions:id1}
To be eligible to graduate from Loyola University Chicago, you must
have 120 credits \emph{and} a GPA of at least 2.0. C\# does not use the
word \emph{and}.  Instead it uses \code{\&\&} (inherited from the C language).
Then the requirement
translates directly into C\# as a \emph{compound condition}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{credits} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{0} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{GPA} \PYG{p}{\PYGZgt{}}\PYG{p}{=}\PYG{l+m}{2.0}
\end{Verbatim}

This is true if both \code{credits \textgreater{}= 120} is true and
\code{GPA \textgreater{}= 2.0} is
true. A short example function using this would be:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{checkGraduation}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{credits}\PYG{p}{,} \PYG{k+kt}{double} \PYG{n}{GPA}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
    \PYG{k}{if} \PYG{p}{(}\PYG{n}{credits} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{0} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{GPA} \PYG{p}{\PYGZgt{}}\PYG{p}{=}\PYG{l+m}{2.0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}You are eligible to graduate!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
    \PYG{k}{else} \PYG{p}{\PYGZob{}}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}You are not eligible to graduate.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The new C\# syntax for the operator \code{\&\&}:
\begin{quote}

\emph{condition1} \code{\&\&} \emph{condition2}
\end{quote}

The compound condition is true if both of the component conditions
are true. It is false if at least one of the conditions is false.

Suppose we want a C\# condition that is true in the same situations as the mathematical
expression: low \textless{} val \textless{} high.  Unfortunately the math is not a
C\# expression.  The C\# operator \code{\textless{}} is binary.  In C\# the statement above is
equivalent to
\begin{quote}

(low \textless{} val) \textless{} high
\end{quote}

comparing a Boolean result to high, and causing a compiler error.
There is a C\# version.  Be sure to use this pattern:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{low} \PYG{p}{\PYGZlt{}} \PYG{n}{val} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{val} \PYG{p}{\PYGZlt{}} \PYG{n}{high}
\end{Verbatim}

\index{\textbar{}\textbar{}!boolean operation OR}\index{or \textbar{}\textbar{}}\index{boolean operation!\textbar{}\textbar{} OR}
Now suppose we want the opposite condition:  that val is \emph{not}
strictly between low and high.
There are several approaches.
One is that \code{val} would be less than or equal to low
\emph{or} greater than or equal to \code{high}.  C\# translate \emph{or} into \code{\textbar{}\textbar{}},
so a C\# expression would be:
\begin{quote}

val \textless{}= low \textbar{}\textbar{} val \textgreater{}= high
\end{quote}

The new C\# syntax for the operator \code{\textbar{}\textbar{}}:
\begin{quote}

\emph{condition1} \code{\textbar{}\textbar{}} \emph{condition2}
\end{quote}

The compound condition is true if at least one of the component conditions
are true. It is false if both conditions are false.

\index{! boolean operation NOT}\index{not !}\index{boolean operation!! NOT}
Another logical way to express the opposite of the condition low \textless{} val \textless{} high
is that it is \emph{not} the case
that low \textless{} val \&\& val \textless{}\textless{} high.  C\# translates \emph{not} as \code{!}.  Another way
to state the condition would be

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{p}{!}\PYG{p}{(}\PYG{n}{low} \PYG{p}{\PYGZlt{}} \PYG{n}{val} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{val} \PYG{p}{\PYGZlt{}} \PYG{n}{high}\PYG{p}{)}
\end{Verbatim}

The parentheses are needed because the \code{!}
operator has higher precedence than
\code{\textless{}}.

A way to remember this strange \emph{not} operator is to think of the use of \code{!}
in the not-equal operator: \code{!=}

The new C\# syntax for the operator \code{!}:
\begin{quote}

\code{!} \emph{condition}
\end{quote}

This whole expression is true when \emph{condition} is false,
and false when \emph{condition} is true.

Because of the precedence of \code{!}, you are often going to write:
\begin{quote}

\code{!(} \emph{condition} \code{)}
\end{quote}

Remember when such a condition is used in an \code{if} statement, \emph{outer}
parentheses are also needed:
\begin{quote}

\code{if (!(} \emph{condition} \code{)) \{}
\end{quote}

We now have a lot of operators!  Most of those in appendix {\hyperref[precedence:precedence]{\emph{Precedence of Operators}}}
have now been considered. There
you can see that \code{!} has the high precedence of unary arithmetic operators.
The operators \code{\&\&} and \code{\textbar{}\textbar{}} are almost at the bottom of the operators
considered in this book, just above the assignment operators, and below the
relational operators, with \code{\&\&} above \code{\textbar{}\textbar{}}.
You are encourages to use parentheses to make sure.

\textbf{Compound Overkill}:  Look back to the code converting a score to a letter grade
in {\hyperref[ifelsechained:multiple-tests]{\emph{Multiple Tests and if-else Statements}}}.
The condition before assigning the B grade could have been:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{p}{(}\PYG{n}{score} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{8}\PYG{l+m}{0} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{score} \PYG{p}{\PYGZlt{}} \PYG{l+m}{9}\PYG{l+m}{0}\PYG{p}{)}
\end{Verbatim}

That would have totally nailed the condition, but it is overly verbose in the
\code{if} .. \code{else if} ... code where it appeared:
Since you only get to consider a B as a grade if the grade was \emph{not} already
set to A, the second part of the compound condition above is redundant.

There are a couple more wrinkles with compound Boolean expressions introduced
later in {\hyperref[condition-short-circuit:short-circuit]{\emph{Short-Circuiting \&\& and \textbar{}\textbar{}}}}.


\subsection{Congress Exercise}
\label{compoundconditions:congress-exercise}\label{compoundconditions:congressex}
A person is eligible to be a US Senator who is at least 30 years
old and has been a US citizen for at least 9 years. Write a version
of a program \code{congress.cs} to obtain age and length of
citizenship from the user and print out if a person is eligible to
be a Senator or not. A person is eligible to be a US Representative
who is at least 25 years old and has been a US citizen for at least
7 years. Elaborate your program \code{congress.cs} so it obtains age
and length of citizenship and prints whether a person is eligible
to be a US Representative only, or is eligible for both offices, or
is eligible for neither.

This exercise could be done by making an exhaustive treatment of all
possible combinations of age and citizenship.  Try to avoid that.
(Note the paragraph just before this exercise.)

Caution:  be sure to do exhaustive testing.  It is easy to write code
that is correct for \emph{some} inputs, but not all.

\index{implication operator}

\subsection{Implication Exercise}
\label{compoundconditions:implication-exercise}\label{compoundconditions:index-3}
We have introduced C\# Boolean operators for AND, OR, and NOT.
There are other Boolean operators important in logic,
that are not directly given as a C\# operator.
One example is ``implies'', also expressed
in a logical if-then statement:  If I am expecting rain, then I am carrying an
umbrella.  Otherwise put:  ``I am expecting rain'' \emph{implies}
``I am carrying an umbrella''. The first part is a Boolean expression called the
\emph{hypothesis}, and the second part is called the \emph{conclusion}.  In general, when
A and B are Boolean expressions, ``A implies B'' is also a Boolean expression.

Just as the truth of a compound Boolean expression like ``A and B'' depends on the
truth value of the two parts, so with \emph{implies}:
If you are using good logic, and you start with a true assertion,
you should only be able to conclude something else true, so it is true that
``true implies true''.  If you start with garbage you can use that false statement
in a logical argument and end up with something either false or true:
``false implies false'' and ``false implies true'' are both true. The only thing
that should not work is to start with something true and conclude
something false.  If that were the case, logical arguments would be useless,
so ``true implies false'' is false.  There is no C\# operator for ``implies'', but
you can check all four cases of Boolean values for A and B to see that
``A implies B'' is true exactly when ``not A or B'' is true.  We can
express this in C\# as \code{!A \textbar{}\textbar{} B}.

So here is a silly little exercise illustrating both implication and using
the C\# Boolean operators:  Ask the user whether ``I am expecting rain'' is true.
(We have the UI function Agree.)  Then check with the user whether
``I am carrying an umbrella.''  Then conclude and print out
whether the implication ``If I am expecting rain, then I am carrying an
umbrella.'' is true or not in this situation.

\index{if!statements nested}\index{statement!if nested}

\section{Nested \texttt{if} Statements}
\label{ifnested:index-0}\label{ifnested:if-nested}\label{ifnested::doc}\label{ifnested:nested-if-statements}
In \code{if}-\code{else} statements the substatements (the if-true and if-false clauses)
are quite arbitrary statements.  They can be more \code{if} or
\code{if}-\code{else} statements.
In {\hyperref[ifelsechained:multiple-tests]{\emph{Multiple Tests and if-else Statements}}}
we have just illustrated placing an \code{if}-\code{else} statement as the \code{else}
clause, and repeating this pattern, to repeatedly test for one more case,
stopping when the first true condition if reached.
To choose one case from multiple cases,
each condition separates one case terminal case from all the remaining
untested cases.

Consider a different situation:  Steven Covey suggested that people classify
possible actions on two axes: urgent vs. not urgent and important vs. not
important, leading to four possible combinations.
We could ask a person to classify an activity this way, and them give a
process comment, something like from Covey's book:
\begin{itemize}
\item {} 
Important and urgent:  Be sure to schedule this promptly!

\item {} 
Important and not urgent:  Make sure that this is included regularly in your
plans!  Do not let urgent but unimportant things interfere!

\item {} 
Not important and urgent:  Can you skip this, or is it really worth
letting this displace important things you need to do?

\item {} 
Not important and not urgent:  Is there anything more worthwhile
for you to do now?

\end{itemize}

Assume we have Boolean variables \code{important} and \code{urgent}.
There are four separate combinations, and we could handle this with a
chain of compound conditions checking for one at a time:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{important} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{urgent}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Be sure ...\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{n+nf}{if} \PYG{p}{(}\PYG{n}{important} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{p}{!}\PYG{n}{urgent}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Make sure ...\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{n+nf}{if} \PYG{p}{(}\PYG{p}{!}\PYG{n}{important} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{urgent}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Can you...\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Is there ...\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Compound test conditions
are not necessary if we keep track of partial answers,
nesting \code{if} statements, thinking about the two aspects separately:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{important}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{urgent}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Be sure ...\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{else} \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Make sure ...\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{urgent}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Can you...\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{else} \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Is there ...\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The outer \code{if}-\code{else} determines whether the action is important, so the inner
conditions only need to deal with urgency.  Also note that in executing
this version there are never more than two short conditions evaluated.
In the first version,
you may have to go through all three conditions.  Both approaches work.
Which is clearer to you?


\subsection{Cartesian Plane Location Exercise/Example}
\label{ifnested:cartesian-plane-location-exercise-example}
Points in the Cartesian plane are given by an x and a y coordinate.  Seven
parts of the Cartesian plane are labeled in the figure below.

{\hfill\includegraphics[width=135.15pt]{cartesian.png}\hfill}

So we match each point with only one name, refer to the point where
both x and y are 0 as the origin, and only use the terms x axis or y axis when
the point is \emph{not} the origin.

Write a program prompting the user for integer x and y values, and print
out the part of the plane as named in the figure.
Separate the input and output from the naming logic:
Have a function with x and y coordinates as parameters that returns the
name of the part of the Cartesian plane.

There are several possible approaches to this function:
\begin{itemize}
\item {} 
Since each part is associated with a condition on both x and y,
you could write a 7 clause chain of if else if else .... with each condition
being a \emph{compound} Boolean expression checking for another specific case.
This gives some more practice with compound boolean expressions.

\item {} 
The previous version is conceptually straightforward,
but you end up checking the sign of x and y
many more times than you need to.  Alternately you can make each condition
check only the sign of \emph{one} coordinate, and \emph{nest} \code{if}-\code{else} statements
checking one coordinate inside an \code{if}-\code{else} statement checking the other
coordinate.  This is more complicated than the Covey importance and
urgency example, since each sign has three possibilities (+, 0, -)
rather than two. \emph{Our} solutions to this approach are in example
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/cartesian/cartesian.cs}{cartesian/cartesian.cs}.  There are actually two alternative
solutions functions there.
The first version uses many \code{if}-\code{else} statements, but since each clause
executes a \code{return} statement that stops any further execution,
no \code{else} clauses are actually needed, as shown in \code{PartOfPlane2}.

\end{itemize}


\section{Chapter Review Questions}
\label{reviewdecisions:chapter-review-questions}\label{reviewdecisions::doc}\begin{enumerate}
\item {} 
Which of these are Boolean expressions?  Assume the variables are of
type \code{int}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{true}
\PYG{l+s}{\PYGZdq{}false\PYGZdq{}}
\PYG{n}{x} \PYG{p}{=} \PYG{l+m}{3}
\PYG{n}{n} \PYG{p}{\PYGZlt{}} \PYG{l+m}{1}\PYG{l+m}{0}
\PYG{n}{count} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{2}\PYG{l+m}{2}
\PYG{n}{x} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{2} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{1}\PYG{l+m}{0}
\PYG{n}{x} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{2} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{l+m}{3}
\PYG{l+m}{1} \PYG{p}{\PYGZlt{}} \PYG{n}{y} \PYG{p}{\PYGZlt{}} \PYG{l+m}{1}\PYG{l+m}{0}
\end{Verbatim}

\item {} 
What are the values of these expressions?  Be able to explain:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+m}{2} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{l+m}{4} \PYG{p}{\PYGZlt{}} \PYG{l+m}{5}
\PYG{l+m}{2} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{l+m}{4} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3}
\PYG{l+m}{2} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{l+m}{4} \PYG{p}{\PYGZlt{}} \PYG{l+m}{5}
\PYG{l+m}{2} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{l+m}{4} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3}
\PYG{l+m}{3} \PYG{p}{\PYGZlt{}} \PYG{l+m}{2} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{l+m}{4} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3}
\PYG{l+m}{2} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{l+m}{4} \PYG{p}{\PYGZlt{}} \PYG{l+m}{5} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{l+m}{4} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3}
\end{Verbatim}

\item {} 
Correct the last two entries in the first problem, supposing the user
meant ``x could be either 2 or 3'' and then
``y is strictly between 1 and 10''.

\item {} 
Add parentheses in \code{2 \textless{} 3 \textbar{}\textbar{} 4 \textless{} 5 \&\& 4 \textless{} 3} to get a different result.

\item {} 
Suppose you have four possible distinct situations in your algorithm,
each requiring a totally
different response in your code,
and exactly one of the situations is sure to occur.
Have many times must you have \code{if} followed by
a condition?

\item {} 
Suppose you have four possible distinct situations in your algorithm,
each requiring a totally
different response in your code,
and at most one of the situations will occur, so
possibly nothing will happen that needs a response at all.
Have many times must you have \code{if} followed by
a condition?

\item {} 
Assume  \code{IsBig(x)} returns a Boolean value.
Remove the redundant part of this statement:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{IsBig}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{k}{true}\PYG{p}{)}
   \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}
\end{Verbatim}

\item {} 
Write an equivalent (and much shorter!) statement with no \code{if}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)}
   \PYG{k}{return} \PYG{k}{true}\PYG{p}{;}
\PYG{k}{else}
   \PYG{k}{return} \PYG{k}{false}\PYG{p}{;}
\end{Verbatim}

\item {} 
Write an equivalent (and much shorter!) statement with no \code{if}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)}
   \PYG{n}{isSmall} \PYG{p}{=} \PYG{k}{false}\PYG{p}{;}
\PYG{k}{else}
   \PYG{n}{isSmall} \PYG{p}{=} \PYG{k}{true}\PYG{p}{;}
\end{Verbatim}

\item {} 
Assume \code{x} and \code{y} are local \code{int} variables.
Code fragments are separated by a blank line below.
Pairs of the fragments are logically equivalent, but not necessarily with
a directly adjacent fragment. Match the pairs.  Be sure you understand
when different pairs would behave differently.  Caution:
there is some pretty awful code here, that we would \emph{hope} you would never
write, but you might need to correct/read!  Think of pitfalls.
In each equivalent pair, which code fragment is more professional?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}    \PYG{c+c1}{//a}
   \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}    \PYG{c+c1}{//b}
   \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)}      \PYG{c+c1}{//c}
   \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}    \PYG{c+c1}{//d}
   \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)}      \PYG{c+c1}{//e}
   \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{k}{else} \PYG{n+nf}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}    \PYG{c+c1}{//f}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
Same situation as the last problem, and same caution,
except this time assume the fragments
appear in a function that returns an \code{int}.
In each pair of equivalent fragments, which is your preference?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}         \PYG{c+c1}{//a}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}   \PYG{c+c1}{//b}
   \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}   \PYG{c+c1}{//c}
   \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}   \PYG{c+c1}{//d}
   \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}   \PYG{c+c1}{//e}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
   \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}   \PYG{c+c1}{//f}
   \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)}\PYG{p}{;}    \PYG{c+c1}{//g}
   \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}

\PYG{k}{return} \PYG{n}{x}\PYG{p}{;}      \PYG{c+c1}{//h}
\end{Verbatim}

\item {} 
Same situation as the last problem, and same caution:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{5}\PYG{p}{)}        \PYG{c+c1}{//a}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)}
       \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}
\PYG{k}{else}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{5}\PYG{p}{)}  \PYG{p}{\PYGZob{}}     \PYG{c+c1}{//b}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)}
       \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)}        \PYG{c+c1}{//c}
   \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{5}\PYG{p}{)}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}

\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{7}\PYG{p}{)}        \PYG{c+c1}{//d}
   \PYG{k}{return} \PYG{n}{x}\PYG{p}{;}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{l+m}{5}\PYG{p}{)}
   \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
\end{Verbatim}

\end{enumerate}

\index{loop!while}\index{while}

\chapter{While Loops}
\label{while:index-0}\label{while::doc}\label{while:while-loops}\label{while:id1}
\index{while!statement}\index{statement!while}

\section{While-Statements}
\label{whilestatements:index-0}\label{whilestatements::doc}\label{whilestatements:while-statements}\label{whilestatements:id1}
We have seen that the sequential flow of a program
can be altered with function calls
and decisions.  The last important pattern is \emph{repetition} or \emph{loops}.
There are several varieties.  The simplest place to start is with
\code{while} loops.

A C\#
\code{while} loop behaves quite similarly to common English usage. If
you hear
\begin{quote}

While your tea is too hot, add a chip of ice.
\end{quote}

Presumably you would test your tea. If it were too hot, you would
add a little ice. If you test again and it is still too hot, you
would add ice again. \emph{As long as} you tested and found it was true
that your tea was too hot, you would go back and add more ice.
C\# has a similar syntax:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{while (} \emph{condition} \code{)}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement
\end{DUlineblock}
\end{DUlineblock}
\end{quote}

As with an \code{if} statement we will generally assume a compound statement,
after the condition, so the syntax will actually be:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{while (} \emph{condition} \code{) \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement(s)
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

Setting up the English example as pseudocode in a similar format would be:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] while ( \emph{your tea is too hot} ) \{
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] add a chip of ice
\end{DUlineblock}
\item[] \}
\end{DUlineblock}
\end{quote}

\index{playing computer!loop}
To make things concrete and numerical, suppose the following: The
tea starts at 115 degrees Fahrenheit. You want it at 112 degrees. A
chip of ice turns out to lower the temperature one degree each
time. You test the temperature each time, and also print out the
temperature before reducing the temperature. In C\# you could
write and run the code below, saved in example program
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/cool/cool.cs}{cool/cool.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k+kt}{int} \PYG{n}{temperature} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{1}\PYG{l+m}{5}\PYG{p}{;}
      \PYG{k}{while} \PYG{p}{(}\PYG{n}{temperature} \PYG{p}{\PYGZgt{}} \PYG{l+m}{1}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{c+c1}{// first while loop code}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{temperature}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{temperature} \PYG{p}{=} \PYG{n}{temperature} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}The tea is cool enough.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

We added a final line after the \code{while} loop to remind you that
execution follows sequentially after a loop completes.

It is extremely important to totally understand how the flow of
execution works with loops.  One way to follow it
closely is to make a table with a line for each instruction
executed, keeping track of all the variables, playing computer.
as with \code{if} statements, the executed lines that you show in your table
will not be in textual order, as in
{\hyperref[data_programstructure:sequential-execution]{\emph{Sequential Execution}}}.
While \code{if} statements merely altered execution order
by skipping some lines, loops allow the same line in the text of your program
to be executed repeatedly, and show up in multiple places in your table.

\index{while!execution sequence}\index{execution sequence!while}
If you play computer and follow the path of execution, you could
generate the following table. Remember, that each time you reach
the end of the block after the \code{while} heading,
execution returns to the \code{while} heading for another test:

\begin{tabulary}{\linewidth}{|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
temperature
} & \textsf{\relax 
Comment
}\\
\hline
1
 & 
115
 & \\
\hline
2
 &  & 
115 \textgreater{} 112 is true, do loop
\\
\hline
3
 &  & 
prints 115
\\
\hline
4
 & 
114
 & 
115 - 1 is 114, loop back
\\
\hline
2
 &  & 
114 \textgreater{} 112 is true, do loop
\\
\hline
3
 &  & 
prints 114
\\
\hline
4
 & 
113
 & 
114 - 1 is 113, loop back
\\
\hline
2
 &  & 
113 \textgreater{} 112 is true, do loop
\\
\hline
3
 &  & 
prints 113
\\
\hline
4
 & 
112
 & 
113 - 1 is 112, loop back
\\
\hline
2
 &  & 
112 \textgreater{} 112 is false, skip loop
\\
\hline
6
 &  & 
prints that the tea is cool
\\
\hline\end{tabulary}


Each time the end of the loop body block is reached, execution
\emph{goes back} to the \code{while} loop heading for another test. When the
test is finally false, execution jumps past the indented body of
the \code{while} loop to the next sequential statement.

\begin{notice}{note}{Note:}
Unless a program is purely sequential,
the numbers under the \textbf{Line} column are \emph{not} just in textual, sequential
order.  The order of the numbers is the order of \emph{execution}.
Each line number in the ``playing computer'' table is the
line \emph{number label} for the next particular line \emph{getting executed}.
Since in decisions, loops, and function calls, lines may be reordered
or repeated, the corresponding line numbers may be skipped, repeated,
or otherwise out of numerical order.
\end{notice}

\index{while!rubric}\index{pattern for a while loop}
The biggest trick with a loop is to make the same code do the next
thing you want each time through.  That generally involves
the use of variables that are modified for each successive time through
the loop.  Here is a general pattern:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] initialization
\item[] \code{while (} \emph{continuationCondition} \code{) \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] do main action to be repeated
\item[] prepare variables for the next time through the loop
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

The simple first example follows this pattern directly.  Note
that the variables needed for the test of the condition must be
set up \emph{both} in the initialization \emph{and} inside the loop
(often at the very end).  Without a change inside the loop, the loop would
run forever!

How to manage all of this in general is a big deal for beginning students.
We will see a number of common patterns in lots of practice.  We will use
the term \emph{successive modification loop} for loops following the pattern
above.

Test yourself: Follow the code.  Figure out what is printed.
If it helps, get detailed and play computer:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{4}\PYG{p}{;}
      \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{l+m}{9}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{i}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{i} \PYG{p}{=} \PYG{n}{i} \PYG{p}{+} \PYG{l+m}{2}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Check yourself by running the example program \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/test\_while1/test\_while1.cs}{test\_while1/test\_while1.cs}.

\begin{notice}{note}{Note:}
In C\#, \code{while} is not used \emph{quite} like in English. In
English you could mean to stop \emph{as soon as} the condition you want
to test becomes false. In C\# the test is \emph{only} made when
execution for the loop starts (or starts again),
\emph{not} in the middle of the loop.
\end{notice}

\emph{Predict} what will happen with this slight variation on the
previous example, switching the order in the loop body. Follow it
carefully, one step at a time.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{4}\PYG{p}{;} \PYG{c+c1}{//variation on TestWhile1.cs}
      \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{l+m}{9}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{i} \PYG{p}{=} \PYG{n}{i} \PYG{p}{+} \PYG{l+m}{2}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{i}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Check yourself by running the example program
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/test\_while2/test\_while2.cs}{test\_while2/test\_while2.cs}.

The line sequence is important. The variable \code{i} is increased before
it is printed, so the first number printed is 6. Another common
error is to assume that 10 will \emph{not} be printed, since 10 is
\emph{past} 9, but the test that may stop the loop is \emph{not} made in the
middle of the loop. Once the body of the loop is started, it
continues to the end, even when \code{i} becomes 10.

\begin{tabulary}{\linewidth}{|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
i
} & \textsf{\relax 
Comment
}\\
\hline
1
 & 
4
 & \\
\hline
2
 &  & 
4 \textless{} 9 is true, do loop
\\
\hline
3
 & 
6
 & 
4+2=6
\\
\hline
4
 &  & 
print 6
\\
\hline
2
 &  & 
6 \textless{} 9 is true, do loop
\\
\hline
3
 & 
8
 & 
6+2= 8
\\
\hline
4
 &  & 
print 8
\\
\hline
2
 &  & 
8 \textless{} 9 is true, do loop
\\
\hline
3
 & 
10
 & 
8+2=10  \emph{No test here}
\\
\hline
4
 &  & 
print 10
\\
\hline
2
 &  & 
10 \textless{} 9 is false, skip loop
\\
\hline\end{tabulary}


You should be able to generate a table like the one above, following
the execution of one statement at a time.  You are playing through the role
of the computer in detail.
As code gets more complicated, particularly with loops, this ``playing computer''
is an important skill.

\textbf{Problem}:  Write a program with a \code{while} loop to print:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
10
9
8
7
6
5
4
3
2
1
Blastoff!
\end{Verbatim}

\textbf{Analysis}:
We have seen that we can produce a regular sequence of numbers in a loop.
The ``Blastoff!'' part does not fit the pattern, so it is logically a \emph{separate}
part after the loop.  We need a name for the number that decreases.  It can
be \code{time}.  Remember the general rubric for a \code{while} loop:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] initialization
\item[] \code{while (} \emph{continuationCondition} \code{) \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] do main action to be repeated
\item[] prepare variables for the next time through the loop
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

You can consider each part separately.  Where to start is partly a
matter of taste.

The main thing to do is print the time over and over.
The initial value of the time is 10.  We are going to want to keep printing
until the time is down to 1, so we \emph{continue} while the time is at least 1,
meaning the continuationCondition can be \code{time \textgreater{}= 1},
or we could use \code{time \textgreater{} 0}, since \code{time} is an integer here.

Finally we need to get ready to print a different time in
the next pass through the loop.
Since each successive time is one less than the previous one, the
preparation for the next value of time is:  \code{time = time - 1}.

Putting that all together, and remembering the one thing we noted
to do after the loop,
we get \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/blastoff/blastoff.cs}{blastoff/blastoff.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{Blastoff}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{int} \PYG{n}{time} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{;}
      \PYG{k}{while} \PYG{p}{(}\PYG{n}{time} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{time}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{time} \PYG{p}{=} \PYG{n}{time} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Blastoff!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Look back and see how we fit the general rubric.
There are a bunch of things to think about with a while loop, so
it helps to go one step at a time, thinking of the rubric and the specific
needs of the current problem.

There are many different (and more exciting) patterns of change coming
for loops,
but the simple examples so far get us started.

\index{while!rubric for planning}\index{loop!rubric for planning}\phantomsection\label{whilestatements:loop-rubric}\paragraph{Loop Planning Rubric}

Looking ahead to more complicated and interesting problems,
here is a more complete list of questions to ask yourself when
designing a function with a \code{while} loop:
\begin{itemize}
\item {} 
What data is involved? Make sure you give good variable names.

\item {} 
What needs to be initialized and how? This certainly includes any
variable tested in the condition.

\item {} 
What is the condition that will allow the loop to \emph{continue}?  It
may be easier to think of the condition that will \emph{stop} the loop.
That is fine - but remember to \emph{negate} it (with \code{!}) to turn it
into a proper \emph{continuation} condition.

\item {} 
Distinguish: What is the code that should only be executed once?
What action do I want to repeat?

\item {} 
How do I write the repeating action so I can modify it for the next time
through the loop to work with new data?

\item {} 
What code is needed to do modifications to make the same code work
the next time through the loop?

\item {} 
Have I thought of variables needed in the middle and declared them;
do other things need initialization?

\item {} 
Will the continuation condition eventually fail?
\emph{Be sure to think about this!}

\item {} 
Separate the actions to be done once before the repetition (code before the
loop) from repetitive actions (in the loop) from actions not repeated, but
done after the loop (code after the loop). Missing this distinction
is a \emph{common error}!

\end{itemize}


\subsection{Sum To \texttt{n}}
\label{whilestatements:sum-to-n}\label{whilestatements:sumton}
Let us write a function to sum the numbers from 1 to \code{n}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return the sum of the numbers from 1 through n.}
\PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{SumToN}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

For instance SumToN(5) calculates 1 + 2 + 3 + 4 + 5 and returns 15.
We know how to generate a sequence of integers, but this is a place
that a programmer gets tripped up by the speed of the human mind.
You are likely
so quick at this that you just see it all at once, with the answer.

\index{concrete example}
In fact, you and the computer need to do this in steps.  To help see, let
us take a concrete example like the one above for SumToN(5), and write out a
detailed sequence of steps like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
3 = 1 + 2
6 = 3 + 3
10 = 6 + 4
15 = 10 + 5
\end{Verbatim}

You could put this in code directly for a specific sum, but if \code{n} is general,
we need a loop, and hence we must see a \emph{pattern} in code that we can repeat.

In each calculation the second term in the additions is a successive integer,
that we can generate.  Starting in the second line, the first number
in each addition
is the sum from the previous line.  Of course the next integer and the next
partial sum change from step to step, so in order to use the same code over and
over we will need changeable variables, with names.  We can make the partial
sum be \code{sum} and we can call the next integer \code{i}.  Each addition can be
in the form:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}
\end{Verbatim}

We need to remember that result, the new sum.  You might first think to introduce
such a name:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{newSum} \PYG{p}{=} \PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}\PYG{p}{;}
\end{Verbatim}

This will work.  We can go through the \code{while} loop rubric:

The variables are \code{sum}, \code{newSum} and \code{i}.

To evaluate

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{newSum} \PYG{p}{=} \PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}\PYG{p}{;}
\end{Verbatim}

the first time in the loop, we need \emph{initial} values for sum and i.
Our concrete example leads the way:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{,} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}
\end{Verbatim}

We need a \code{while} loop heading with a continuation condition.  How
long do we want to add the next \code{i}?  That is for all the value up to and
including n:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{)} \PYG{p}{\PYGZob{}}
\end{Verbatim}

There is one more important piece - making sure the same code
\begin{quote}

newSum = sum + i;
\end{quote}

works for the \emph{next} time through the loop.  We have dealt before with
the idea of the next number in sequence:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{i} \PYG{p}{=} \PYG{n}{i} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}
\end{Verbatim}

What about \code{sum}?  What was the \code{newSum}
on \emph{one} time through the loop becomes the old or
just plain \code{sum} the \emph{next} time through, so we can make an assignment:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{sum} \PYG{p}{=} \PYG{n}{newSum}\PYG{p}{:}
\end{Verbatim}

All together we calculate the sum with:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{,} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}
\PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k+kt}{int} \PYG{n}{newSum} \PYG{p}{=} \PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}\PYG{p}{;}
   \PYG{n}{sum} \PYG{p}{=} \PYG{n}{newSum}\PYG{p}{:}
   \PYG{n}{i} \PYG{p}{=} \PYG{n}{i} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This exactly follows our general rubric, with preparation for the next time
through the loop at the end of the loop.
We can condense it in this case: Since \code{newSum} is only used
once, we can do away with this extra variable name,
and directly change the value of sum:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{,} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}
\PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{sum} \PYG{p}{=} \PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}\PYG{p}{;}
   \PYG{n}{i} \PYG{p}{=} \PYG{n}{i} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Finally this was supposed to fit in a function.  The ultimate purpose
was to \emph{return} the sum, which is the final value of the
variable \code{sum}, so the whole function is:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return the sum of the numbers from 1 through n.}
\PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{SumToN}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}     \PYG{c+c1}{// line 1}
\PYG{p}{\PYGZob{}}
   \PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{,} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}       \PYG{c+c1}{// 2}
   \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{)} \PYG{p}{\PYGZob{}}          \PYG{c+c1}{// 3}
      \PYG{n}{sum} \PYG{p}{=} \PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}\PYG{p}{;}         \PYG{c+c1}{// 4}
      \PYG{n}{i} \PYG{p}{=} \PYG{n}{i} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}             \PYG{c+c1}{// 5}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{return} \PYG{n}{sum}\PYG{p}{;}               \PYG{c+c1}{// 6}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{testing!edge case}\index{range testing}\index{edge case}
The comment before the function definition does not give a clear idea of the
range of possible values for \code{n}.  How small makes sense for the comment?
What actually works in the function?  The smallest expression
starting with 1 would just be 1: (\code{n} is 1).  Does that work in the function?
You were probably not thinking of that when developing the function!
Now look back now at this \emph{edge case}.  You can play computer on the code
or directly test it.  In this case the initialization of \code{sum} is 1,
and the body of the loop \emph{never} runs (2 \textless{}= 1 is false).  The function
execution jumps right to the return statement, and
does return 1, and everything is fine.

Also you should check the program in a more general situation, say with \code{n}
being 4.  You should be able to play computer and generate this table,
using the line numbers shown in comments at the end of lines,
and following one statement of execution at a time.  We only
make entries where variables change value.

\begin{tabulary}{\linewidth}{|L|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
i
} & \textsf{\relax 
sum
} & \textsf{\relax 
Comment
}\\
\hline
1
 &  &  & 
assume 4 is passed for n
\\
\hline
2
 & 
2
 & 
1
 & \\
\hline
3
 &  &  & 
2\textless{}=4: true, enter loop
\\
\hline
4
 &  & 
3
 & 
1+2=3
\\
\hline
5
 & 
3
 &  & 
2+1=3, bottom of loop
\\
\hline
3
 &  &  & 
3\textless{}=4: true
\\
\hline
4
 &  & 
6
 & 
3+3=6
\\
\hline
5
 & 
4
 &  & 
3+1=4, bottom of loop
\\
\hline
3
 &  &  & 
4\textless{}=4: true
\\
\hline
4
 &  & 
10
 & 
6+4=10
\\
\hline
5
 & 
5
 &  & 
4+1=5, bottom of loop
\\
\hline
3
 &  &  & 
5\textless{}=4: false, skip loop
\\
\hline
6
 &  &  & 
return 10
\\
\hline\end{tabulary}


The return only happens once, so it is not in the loop.  You get \emph{a} value
for a sum each time through, but not the final one.  A common beginner
error is to put the return statement inside the loop, like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{SumToN}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}  \PYG{c+c1}{// 1   BAD VERSION!!!}
\PYG{p}{\PYGZob{}}
   \PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{,} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}    \PYG{c+c1}{// 2}
   \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{)} \PYG{p}{\PYGZob{}}       \PYG{c+c1}{// 3}
      \PYG{n}{sum} \PYG{p}{=} \PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}\PYG{p}{;}      \PYG{c+c1}{// 4}
      \PYG{n}{i} \PYG{p}{=} \PYG{n}{i} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}          \PYG{c+c1}{// 5}
      \PYG{k}{return} \PYG{n}{sum}\PYG{p}{;}         \PYG{c+c1}{// 6  WRONG!}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Recall that \emph{when a return statement is reached, function execution ends},
\emph{no matter what comes next in the code}.
(This is a way to break out of a \code{while} loop that we will find useful
later.)  In this case however, it is not what we want at all.  The first sum
is calculated in line 4, so \code{sum} becomes 2 + 1, but when you get to line
6, the function terminates and never loops back, returning 3.

Now about large n....

\index{big oh!order of n}\index{order of n}
With loops we can make programs run for a long time.
The time taken becomes an issue.  In this case we go though the loop
n-1 times, so the total time is approximately proportional to n.
We write that the time is O(n), spoken ``oh of n'', or ``big oh of n'' or
``order of n''.

\index{pitfall!limit on number size}\index{overflow}
Computers are pretty fast, so you can try the testing program
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sum\_to\_n\_test/sum\_to\_n\_test.cs}{sum\_to\_n\_test/sum\_to\_n\_test.cs}
and it will go by so fast, that you will hardly notice.  Try these specific
numbers in tests: 5, 6, 1000, 10000, 98765.  All look OK?  Now try 66000.
On many systems you will get quite a surprise!
This is the first place we have to deal with the limited
size of the \code{int} type.
On many systems the limit is a bit over 2 billion.
You can check out the size of \code{int.MaxValue} in csharp.
The answer for 66000,
and \emph{also} 98765, is bigger than the upper limit.
Luckily the obviously wrong negative answer
for 66000 pops out at you.  Did you guess before you saw the answer for
66000, that there was an issue for
98765?  It is a good thing that no safety component in a big bridge was being
calculated!  It is a big deal that the system fails \emph{silently}
in such situations.  \emph{Think} how large the data may be that you deal with!

Now look at and run \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sum\_to\_n\_long/sum\_to\_n\_long.cs}{sum\_to\_n\_long/sum\_to\_n\_long.cs}.  The sum is
a \code{long} integer here. Check out in csharp how big
a \code{long} can be (\code{long.MaxValue}).  This version of the program
works for 100000 and for 98765.  We can get correct
answers for things that will take perceptible time.  Try working up to
1 billion (1000000000, nine 0's).  It takes a while: O(n) can be slow!

By hand it is a lot slower, unless you totally change the algorithm:
There is a classic story about how a calculation like this
was done in grade school (n=100) by the famous
mathematician Gauss. His teacher was trying to keep him busy.
Gauss discovered the general, exact, mathematical formula:
\begin{quote}

1 + 2 + 3 + ... + n = n(n+1)/2.
\end{quote}

That is the number of terms (n), times the average term (n+1)/2.

\index{big oh!constant order}\index{constant order}
Our loop was instructive, but not the fastest approach.  The simple exact
formula takes about the same time for any n.
(That is as long as the result fits in
a standard type of computer integer!)
This is basically constant time.  In discussing
how the speed relates to the size of n, we say it is O(1).
The point is here that 1 is a constant.  The time is of \emph{constant order}.

\index{pitfall!division}\index{division!pitfall}
We can write a ridiculously short
function following Gauss's model.  Here we introduce the variable average,
as in the motivation for Gauss's answer:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return the sum of the numbers from 1 through n.}
      \PYG{k}{static} \PYG{k+kt}{long} \PYG{n+nf}{SumToN}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}  \PYG{c+c1}{//CHANGED:  quick and WRONG}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{average} \PYG{p}{=} \PYG{p}{(}\PYG{n}{n}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{/}\PYG{l+m}{2}\PYG{p}{;}    \PYG{c+c1}{//from Gausse\PYGZsq{}s motivation}
         \PYG{k}{return} \PYG{n}{n}\PYG{p}{*}\PYG{n}{average}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Run the example program containing it: \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sum\_to\_n\_long\_bad/sum\_to\_n\_long\_bad.cs}{sum\_to\_n\_long\_bad/sum\_to\_n\_long\_bad.cs}.

Test it with 5, and then try 6. ???

``Ridiculously short'' does not imply correct!  The problem goes back
to the fact that Gauss was in \emph{math class} and you are doing
Computer Science.  Think of a subtle difference that might come in here:
Though (n+1)/2 is fine as math, recall the division operator does not
always give correct answers in C\#.  You get an integer answer from the
integer (or long) operands.  Of course the exact mathematical final answer
is an integer when \emph{adding} integers, but splitting it according to
Gauss's motivation can put a mathematical non-integer in the middle.

The C\# fix: The final answer is clearly an integer, so if we do the division
last, when we know the answer will be an integer (assuming a \code{long} integer),
things should be better:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{long} \PYG{n}{sum} \PYG{p}{=} \PYG{n}{n}\PYG{p}{*}\PYG{p}{(}\PYG{n}{n}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{/}\PYG{l+m}{2}\PYG{p}{;}
\PYG{k}{return} \PYG{n}{sum}\PYG{p}{;}
\end{Verbatim}

\index{cast}
Here is a shot at the whole function:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return the sum of the numbers from 1 through n.}
      \PYG{k}{static} \PYG{k+kt}{long} \PYG{n+nf}{SumToN}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}  \PYG{c+c1}{//CHANGED:  quick and still WRONG}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{long} \PYG{n}{sum} \PYG{p}{=} \PYG{n}{n}\PYG{p}{*}\PYG{p}{(}\PYG{n}{n}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{/}\PYG{l+m}{2}\PYG{p}{;}  \PYG{c+c1}{// final division will produce an integer}
         \PYG{k}{return} \PYG{n}{sum}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Run the example program containing it: \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sum\_to\_n\_long\_bad2/sum\_to\_n\_long\_bad2.cs}{sum\_to\_n\_long\_bad2/sum\_to\_n\_long\_bad2.cs}.

Test it with 5, and then try 6. Ok so far, but go on to long integer range:
try 66000 that messed us up before.  ??? You get an answer that is not
a multiple of 1000: not what we got before!  What other issues do we have
between math and C\#?

Further analysis:  To make sure the function always worked, it made sense
to leave the parameter \code{n} an \code{int}.  The function would not work
with \code{n} as the largest \code{long}.  The result can still be big enough
to only fit in a \code{long}, so the return value is a \code{long}.  All
this is reasonable but the C\# result is still wrong!  Look deeper.
While the result of \code{n*(n+1)/2} is \emph{assigned} to a \code{long} variable,
the \emph{calculation} \code{n*(n+1)/2} is done with \code{int}s not mathematical
integers.  By the same general type rule that led to the (n+1)/2 error
earlier, these operations on \code{int}s produce an \code{int} result, even
when wrong.

We need to force the \emph{calculation} to produce a \code{long}.
In the correct looping version \code{sum} was a \code{long}, and that
forced all the later arithmetic to be with longs.  Here are two variations
that work:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{long} \PYG{n}{nLong} \PYG{p}{=} \PYG{n}{n}\PYG{p}{;}
\PYG{k}{return} \PYG{n}{nLong}\PYG{p}{*}\PYG{p}{(}\PYG{n}{nLong}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{/}\PYG{l+m}{2}\PYG{p}{;}
\end{Verbatim}

or we can avoid a new variable name by {\hyperref[data_types-and-conversions:cast]{\emph{Casting}}} to \code{long}, converting
the first (left) operand to \code{long}, so all the later left-to-right
operations are forced to be \code{long}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{return} \PYG{p}{(}\PYG{k+kt}{long}\PYG{p}{)}\PYG{n}{n}\PYG{p}{*}\PYG{p}{(}\PYG{n}{n}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{/}\PYG{l+m}{2}\PYG{p}{;}
\end{Verbatim}

You can try example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sum\_to\_n\_long\_quick/sum\_to\_n\_long\_quick.cs}{sum\_to\_n\_long\_quick/sum\_to\_n\_long\_quick.cs}
to finally get a result that is dependably fast and correct.

Important lessons from this humble summation problem:
\begin{itemize}
\item {} 
\emph{Working} and being \emph{efficient} are two different things in general.

\item {} 
\emph{Math} operations and C\# operations are not always the same.
Knowing this in theory is not the same as remembering it in practice!

\end{itemize}

Further special syntax that only makes sense in any kind of loop is discussed in
{\hyperref[forstatements:break-continue]{\emph{Break and Continue}}}, after we introduce the last kind of loop.

\index{while!index for sequence}\index{sequence with while}

\section{While-Statements with Sequences}
\label{while-with-sequence:while-sequence}\label{while-with-sequence:index-0}\label{while-with-sequence::doc}\label{while-with-sequence:while-statements-with-sequences}

\subsection{One Character Per Line}
\label{while-with-sequence:one-character-per-line}
We will process many sequences or collections.  At this point
the only collection we have discussed is a string - a sequence of
characters that we can index.
\phantomsection\label{while-with-sequence:onecharperline}
\index{example!OneCharPerLine}\index{OneCharPerLine example}
Consider the following silly function description and heading as a start:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{// Print the characters of s, one per line.}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{OneCharPerLine}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\end{Verbatim}

\code{OneCharPerLine("bug")} would print:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
b
u
g
\end{Verbatim}

We are accessing one character at a time.  We can do that with
the indexing notation.  Thinking concretely about the example above,
we are looking to print, \code{s{[}0{]}}, \code{s{[}1{]}}, \code{s{[}2{]}}.  If
we knew we would always have three characters, we could do this
with three explicit print statements, but we are looking to write a general
definition for an arbitrary length string:
This requires a loop.
For now our only option is a \code{while} loop.  We can follow our basic
{\hyperref[whilestatements:loop-rubric]{\emph{loop planning rubric}}},
one step at a time:
The index is changing in a simple repetitive sequence.
We can call the
index \code{i}.  Its initial value is clearly 0.
That is our initialization.  We need a \code{while} loop continuation
condition.
For the 3-character string example, the last index above is 2.
In general we want \emph{all} the characters.  Recall the index of the last
character is the length - 1, or with our parameter \code{s}, \code{s.Length - 1}
The \code{while} loop condition needs to allow indices through
\code{s.Length - 1}.  We could write a condition with \code{\textless{}=} or more
concisely:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)} \PYG{p}{\PYGZob{}}
\end{Verbatim}

In the body of the loop, the main thing is to print the next character,
and the next character is \code{s{[}i{]}}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\index{++ increment}\index{-- decrement}\index{operator!++ increment}\index{operator!-- decrement}
We also need to remember the part to get ready for the next time
through the loop.  We have dealt with regular sequence of values
before.  We change \code{i} with:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{i} \PYG{p}{=} \PYG{n}{i}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{;}
\end{Verbatim}

This change is so common, there is a simpler syntax:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
\end{Verbatim}

This increases the value of the numeric variable i by 1.
(The reverse is \code{i-{-};}) \footnote{
To be complete, the statements \code{c = c + 1;} and \code{c++;} are not always
equivalent.

In \code{c++} the type of \code{c} must be numeric, but not necessarily \code{int}.
It could be a \emph{smaller} type, like \code{char}.

With a  \code{c} of type \code{char} the \code{c++} could
not be replaced by \code{c = c + 1}, but you could use \code{c = (char)(c + 1)}:
The \code{int} literal 1 forces
the sum expression to be an \code{int}, which must be cast back to a \code{char} to be
assigned to \code{c}.  Similarly with the \code{-{-}} operator.
}

So all together:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{// Print the characters of s, one per line.}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{OneCharPerLine}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

You can test this with example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/char\_loop1/char\_loop1.cs}{char\_loop1/char\_loop1.cs}.

This is a very common pattern.
We could do anything we want with each individual character,
not just print it.

\index{ReversedPrint example}

\subsubsection{String Backwards Exercise/Example}
\label{while-with-sequence:index-3}\label{while-with-sequence:string-backwards-exercise-example}\label{while-with-sequence:reversed-print-example}
Here is a variation:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Print s in reverse order; no extra newlines}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintReversed}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\end{Verbatim}

There are a few changes:
\begin{itemize}
\item {} 
You do not want to go on to the next line, so use \code{Write},
not \code{WriteLine}.

\item {} 
It is still a regular sequence of character indices, but
we are working backwards through the string.  We have created
a decreasing sequence before.  Where do
you start?  Where do you stop?  What is the condition? How do you
get ready for the next time through the loop? (Remember our newest
notation.)

\end{itemize}

Our code with driver is in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/reversed\_print/reversed\_print.cs}{reversed\_print/reversed\_print.cs}.

\index{string!PrintVowels}\index{PrintVowels example}

\subsection{Print Vowels Function}
\label{while-with-sequence:printvowels}\label{while-with-sequence:index-4}\label{while-with-sequence:print-vowels-function}
Let us get more complicated.  Consider the function described:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Print the vowels (aeiou) in s, one per line.}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintVowels}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\end{Verbatim}

For instance PrintVowels(``computer'') would print:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
o
u
e
\end{Verbatim}

We have seen that we can go through the whole string and do the same
thing each time through the loop, using \code{s{[}i{]}} in some specific way.

This new description seems problematic.  We do \emph{not} appear to want to do
the same thing each time:  We only want to print \emph{some} of the
characters.  Again your eyes and mind are so fast, you likely miss what you
need to do when you go through \code{PrintVowels} by hand.  Your
eyes let you just grab the vowels easily, but think, what is actually
happening?  You are checking each character to see \textbf{if} it is a vowel,
and printing it if it is:  You are doing the same thing each time -
\emph{testing} \textbf{if} the character is a vowel.  The pseudocode is

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{k}{is} \PYG{n}{a} \PYG{n}{vowel}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{print} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

We \emph{do} want to do this each time through the loop.  We \emph{can} use
a \code{while} statement.

Next task:  convert the pseudocode ``s{[}i{]} is a vowel'' to C\#.

There are multiple approaches.  The one you get by following your
nose is just to consider all the cases where it is true:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}a\PYGZsq{}}
\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}e\PYGZsq{}}
\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}i\PYGZsq{}}
\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}o\PYGZsq{}}
\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}u\PYGZsq{}}
\end{Verbatim}

How do you combine them into a condition?
The letter can be a \emph{or} e \emph{or} i \emph{or} o \emph{or} u.  We get the code:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Print the vowels (aeiou) in s, one per line.}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintVowels}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}a\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}e\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}i\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}}
                \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}o\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}u\PYGZsq{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
            \PYG{n}{i} \PYG{p}{=} \PYG{n}{i}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

That has a long condition!  Here is a nice trick to shorten that:
We want to check if a character is in a group of letters.  We have
already seen the string method IndexOf.  Recall we can use it to see if
a character is in or not in a string.  We can use \code{"aeiou".IndexOf(s{[}i{]})}.
We do not care \emph{where} \code{s{[}i{]}} comes in the string of vowels.
All we care is that \code{"aeiou".IndexOf(s{[}i{]}) \textgreater{}= 0}.

\index{string!Contains}\index{Contains for strings}
This is still a bit of a mouthful.  Often it is just important if a
character or string is \emph{contained} in another string, not where it appears,
so it is easier to
use the string method \code{Contains}.  Though IndexOf takes either a string
or a character as parameter, \code{Contains} only takes a string.  There is a
nice quick idiom to convert anything to a string:  use \code{""+}.
The condition could be \code{"aeiou".Contains(""+s{[}i{]})}.
The \code{"" + s{[}i{]}} adds
the string version of \code{s{[}i{]}} to the empty string.

The function is still not as general as it might be:
Only lowercase vowels are listed.  We could do something with
\code{ToLower}, or just use the condition: \code{"aeiouAEIOU".Contains(""+s{[}i{]})}

This variation is in example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/vowels2/vowels2.cs}{vowels2/vowels2.cs}.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Print the vowels (aeiou) in s, one per line.}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintVowels}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
         \PYG{k+kt}{string} \PYG{n}{vowels} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}aeiouAEIOU\PYGZdq{}}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{vowels}\PYG{p}{.}\PYG{n}{Contains}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{+}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
            \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{example!check\_digits}\index{IsDigits example function}

\subsection{IsDigits Function}
\label{while-with-sequence:isdigits-function}\label{while-with-sequence:index-6}\label{while-with-sequence:isdigits}
Consider a variation, determining if \emph{all} the characters
in a string are vowels.  We could work on that, but it is
not very useful.  Instead let us consider if all the
characters are digits.  This is a true-false question, so the function
to determine this would return a Boolean result:

There are several ways to check if a character is a digit.  We could use the
\code{Contains} idiom from above, but here is another option:
The integer codes for digits are sequential,
and since characters are technically a kind of integer, we can
compare:  The character \code{s{[}i{]}} is a digit if it is in the range from \code{'0'}
to \code{'9'}, so the condition can be written:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+s+sc}{\PYGZsq{}0\PYGZsq{}} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}9\PYGZsq{}}
\end{Verbatim}

Similarly  the condition \code{s{[}i{]}} is not a digit, can be written
negating the compound condition as in {\hyperref[compoundconditions:compound-boolean-expressions]{\emph{Compound Boolean Expressions}}}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZlt{}} \PYG{l+s+sc}{\PYGZsq{}0\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZgt{}} \PYG{l+s+sc}{\PYGZsq{}9\PYGZsq{}}
\end{Verbatim}

If you think of going through by hand and checking,
you would check through the
characters sequentially and if you find a non-digit,
you would want to \emph{remember} that the string is not only digits.

One way to do this is have a variable holding an answer so far:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{bool} \PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{k}{true}\PYG{p}{;}
\end{Verbatim}

Of course initially, you have not found any non-digits, so it starts off true.
As you go through
the string, you want to make sure that answer is changed to \code{false}
if a non-digit is encountered:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{l+s+sc}{\PYGZsq{}0\PYGZsq{}} \PYG{p}{\PYGZgt{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZgt{}} \PYG{l+s+sc}{\PYGZsq{}9\PYGZsq{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{k}{false}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

When we get all the way through the string, the answer so far is the
final answer to be returned:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return true if s contains one or more digits}
\PYG{c+c1}{/// and nothing else. Otherwise return false.}
\PYG{k}{static} \PYG{k+kt}{bool} \PYG{n+nf}{IsDigits}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k+kt}{bool} \PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{k}{true}\PYG{p}{;}
   \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
   \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{k}{if} \PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZlt{}} \PYG{l+s+sc}{\PYGZsq{}0\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZgt{}} \PYG{l+s+sc}{\PYGZsq{}9\PYGZsq{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{k}{false}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
      \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{return} \PYG{n}{allDigitsSoFar}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Remember something to always consider:  edge cases.
In the description it says it is true for a string of \emph{one or more} digits.

Check examples of length 1 and 0.
Length 1 is fine, but it fails for the empty string,
since the loop is skipped and the initial answer, \code{true} is returned.

There are many ways to fix this.  We will know right up front that the answer
is false if the length is 0, and we could immediately set
\code{allDigitsSoFar} to false.  We would need to change the initialization
so it checks the length and chooses the right value for \code{allDigitsSoFar},
true or false. Since we are selecting between two values,
an \code{if} statement should occur to you:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{bool} \PYG{n}{allDigitsSoFar}\PYG{p}{;}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{k}{true}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{k}{else} \PYG{p}{\PYGZob{}}
    \PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{k}{false}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

If we substitute this initialization for \code{allDigitsSoFar},
the code will satisfy the edge case, and the code will always
work.  Still, this code can be improved:

Examine the \code{if} statement more closely:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] if the condition is  \code{true}, \code{allDigitsSoFar} is \code{true};
\item[] if the condition is \code{false}, \code{allDigitsSoFar} is \code{false};
\end{DUlineblock}
\end{quote}

See the symmetry: the value assigned to \code{allDigitsSoFar} is always
the \emph{value of the condition}.

A \emph{much} more concise and still equivalent initialization is just:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{bool} \PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

In more generality this
conciseness comes from the fact that it is a \emph{Boolean} value that
you are trying to set each time, based on a \emph{Boolean} condition:  You do not
need to do that with an \code{if} statement!  You just need an
assignment statement.  If you use an \code{if} statement in such a situation,
you being verbose and marking yourself as a novice!

It could even be slightly more concise:  The precedence of assignment is
very low, lower than the comparison \code{\textgreater{}},
so the parentheses could be omitted.  We think the
code is easier to read with the parentheses left in, as written above.

The whole function would be:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return true if s contains one or more digits}
      \PYG{c+c1}{/// and nothing else. Otherwise return false.}
      \PYG{k}{static} \PYG{n}{Boolean} \PYG{n+nf}{IsDigits}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Boolean} \PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZlt{}} \PYG{l+s+sc}{\PYGZsq{}0\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZgt{}} \PYG{l+s+sc}{\PYGZsq{}9\PYGZsq{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{k}{false}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
            \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{allDigitsSoFar}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

You can try this code in example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/check\_digits1/check\_digits1.cs}{check\_digits1/check\_digits1.cs}.

\index{return!from inside loop}
Note that we earlier made an improvement by replacing an \code{if}-\code{else} statement
generating a Boolean value by a simple Boolean assignment.
In the most recent sample code, there is an \code{if} statement setting a Boolean
value:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZlt{}} \PYG{l+s+sc}{\PYGZsq{}0\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZgt{}} \PYG{l+s+sc}{\PYGZsq{}9\PYGZsq{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{k}{false}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

You might be tempted to replace this \code{if} statement by a simple Boolean
assignment:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{allDigitsSoFar} \PYG{p}{=} \PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZlt{}} \PYG{l+s+sc}{\PYGZsq{}0\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZgt{}} \PYG{l+s+sc}{\PYGZsq{}9\PYGZsq{}}\PYG{p}{)}\PYG{p}{;}  \PYG{c+c1}{// bad!}
\end{Verbatim}

Play computer with this change to see for yourself why it is bad, before
looking at our explanation below....

The place where we originally said to use a simple Boolean assignment was
replacing an \code{if}-\code{else} statement, that \emph{always} set a Boolean value.  In the more
recent correct code for digits, we had a simple \code{if} statement,
and were only setting the boolean variable
to \code{false} \emph{some} of the time: when we had \emph{not} found a digit.  The bad code
sets the variable for \emph{each} character in the string,
so it can change an earlier \code{false} value back to \code{true} for a later digit.
The final value
always comes from the the \emph{last} character in the string!  We want the
function to come up with an answer \code{false} if \emph{any} character is not a digit,
not just the last character.  The bad code would give the wrong answer
with the string ``R2D2''.  If you do not see that, play computer with this string
and the bad code variation
that sets \code{allDigitsSoFar} every time through the loop.

There is a less commonly useful way to make an assignment without \code{if}
work here \footnote{
The Boolean assignment did not work when \code{allDigitsSoFar} was already
\code{false}, and the next character was a digit.  This could be fixed with
a compound Boolean expression in the assignment:

\code{allDigitsSoFar = allDigitsSoFar  \&\& (s{[}i{]} \textless{} '0' \textbar{}\textbar{} s{[}i{]} \textgreater{} '9');}

This way, once \code{allDigitsSoFar} is \code{false}, it stays \code{false}.
}, but a much more important,
improved approach follows:

The last correct code is still inefficient.  If an early
character in a long string is not a digit, we already know the
final answer, but this code goes through and still checks all the
other characters in the string!  People checking by hand
would stop as soon as they found a
non-digit.  We can do that in several ways with C\#, too.
Since this is a function, and we would know the final answer
where we find a non-digit,
the simplest thing is to use the fact that a return statement
\emph{immediately terminates} the function (even if in a loop).

Instead of setting a variable to \code{false} to \emph{later} be returned,
we can return right away, using the loop:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZlt{}} \PYG{l+s+sc}{\PYGZsq{}0\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZgt{}} \PYG{l+s+sc}{\PYGZsq{}9\PYGZsq{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{k}{return} \PYG{k}{false}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

What if the loop terminates normally (no return from inside)?
That means no
non-digit was found, so if there are any characters at all,
they are all digits. There are
\emph{one or more} digits as long as the string length is \emph{positive}.
Again we do \emph{not} need an \code{if}-\code{else} statement to check the length and
set the Boolean result.
Look in the full
code for the function:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return true if s contains one or more digits}
      \PYG{c+c1}{/// and nothing else. Otherwise return false.}
      \PYG{k}{static} \PYG{n}{Boolean} \PYG{n+nf}{IsDigits}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZlt{}} \PYG{l+s+sc}{\PYGZsq{}0\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZgt{}} \PYG{l+s+sc}{\PYGZsq{}9\PYGZsq{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{k}{return} \PYG{k}{false}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
            \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

The full code with a \code{Main} testing program is in
example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/check\_digits2/check\_digits2.cs}{check\_digits2/check\_digits2.cs}.

Returning out of a loop
is a good pattern to remember when you are searching for something,
and you know the final answer for your function as soon as you find it.

\index{playing computer!loop}\index{loop!playing computer}

\subsection{Play Computer With a Loop}
\label{while-with-sequence:play-computer-with-a-loop}\label{while-with-sequence:index-8}
We have not given you a chance to play computer with a loop.  Here is
some simple silly code,
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/loop\_steps/loop\_steps.cs}{loop\_steps/loop\_steps.cs},
also using a sequence:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{class} \PYG{n+nc}{LoopSteps}
\PYG{p}{\PYGZob{}}
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}} \PYG{c+c1}{// play computer and predict what this loop does}
      \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}abcd\PYGZdq{}}\PYG{p}{;}
      \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
      \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{l+m}{4}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}/\PYGZdq{}} \PYG{p}{+} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{+} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Play computer, completing the table.  You fill in the line numbers,
carefully.  The sequence is \emph{not} 9, 10, 11, 12, 13!

\begin{tabulary}{\linewidth}{|L|L|L|}
\hline
\textsf{\relax 
Line
} & \textsf{\relax 
i
} & \textsf{\relax 
Comment
}\\
\hline
5
 & 
-
 & 
Start at beginning of Main
\\
\hline
7
 &  & 
set s = ``abcd'' (does not change)
\\
\hline
8
 & 
1
 & 
initialize i
\\
\hline
...
 &  & \\
\hline\end{tabulary}



\subsubsection{Duplicate Character Exercise}
\label{while-with-sequence:duplicate-character-exercise}
Create a file \code{double\_char\_test.cs},
and write and test a function with the documentation and heading below:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// If two consecutive characters in s are the same, return true.}
\PYG{c+c1}{/// Return false otherwise.  Examples:}
\PYG{c+c1}{/// HasDoubleChar(\PYGZdq{}bigfoot\PYGZdq{}) and HasDoubleChar(\PYGZdq{}aaah!\PYGZdq{}) are true;}
\PYG{c+c1}{/// HasDoubleChar(\PYGZdq{}treated\PYGZdq{}) and HasDoubleChar(\PYGZdq{}haha!\PYGZdq{}) are false.}
\PYG{k}{static} \PYG{k+kt}{bool} \PYG{n+nf}{HasDoubleChar}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\end{Verbatim}

You may want to play computer on a short example - there is an easy mistake
to make.

\index{interactive while loop}\index{loop!while}\index{while!interactive}

\section{Interactive \texttt{while} Loops}
\label{whileinteractive:index-0}\label{whileinteractive::doc}\label{whileinteractive:interactive-while-loops}\label{whileinteractive:id1}
Next we consider a particular form of \code{while} loops:  Interactive while loops
involve input from the user each time through the loop.
We consider them now for three reasons:
\begin{itemize}
\item {} 
Interactive \code{while} loops have one special `gotcha'
worth illustrating.

\item {} 
We will illustrate some general techniques for understanding and developing
\code{while} loops.

\item {} 
As a practical matter,
we can greatly improve the utility input functions we have been using, and
add some more.

\end{itemize}

We already have discussed the PromptInt function.  The user can choose
any int.  Sometimes we only want an integer in a certain range.
One approach is to not accept a bad value, but make the user repeat
trying until explicitly
entering a value in the right range.  In theory the user could make errors
for some time, so a loop makes sense.  For instance we might have a slow
user, and there could be an exchange like the following
when you want a number from 0 to 100.  For illustration, user input is shown
in boldface:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] Enter a score: (0 through 100) \textbf{233}
\item[] 233 is out of range!
\item[] Enter a score: (0 through 100) \textbf{101}
\item[] 101 is out of range!
\item[] Enter a score: (0 through 100) \textbf{-1}
\item[] -1 is out of range!
\item[] Enter a score: (0 through 100) \textbf{100}
\end{DUlineblock}
\end{quote}

and the value 100 would be accepted.

This is a well-defined idea.  A function makes sense.  Its heading
includes a prompt and low and high limits of the allowed range:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Prompt the user to obtain an int until the response is in the}
      \PYG{c+c1}{/// range [lowLim, highLim].  Then return the int in range.}
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{PromptIntInRange}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{prompt}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{lowLim}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{highLim}\PYG{p}{)}
\end{Verbatim}

For example to generate
sequence above, the call would be:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{PromptIntInRange}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter a score: (0 through 100) \PYGZdq{}}\PYG{p}{,} \PYG{l+m}{0}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{l+m}{0}\PYG{p}{)}
\end{Verbatim}

\index{concrete example!splitting a loop}\index{loop!splitting concrete example}\index{splitting a loop concrete example}
There is an issue with the common term ``loop'' in programming.
In normal English, a loop has no beginning and no end, like a circle.
C\# loops have a sequence of statements with a definite beginning and end.

Consider the sequence above in pseudocode.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Input a number with prompt (233)
Print error message
Input a number with prompt (101)
Print error message
Input a number (\PYGZhy{}1)
Print error message
Input a number with prompt (100)
Return 100
\end{Verbatim}

We can break this into a repeating
pattern in two ways.  The most obvious is the following,
with three repetitions of a basic pattern,
with the last two line not in the same pattern
(so they would go after the loop).  :

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Input a number with prompt (233)
Print error message

Input a number with prompt (101)
Print error message

Input a number (\PYGZhy{}1)
Print error message

Input a number with prompt (100)
Return 100
\end{Verbatim}

Another choice, since
you can split a loop at any point, would be the following, with the first and
last lines not in the  pattern that repeats three times in the middle:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Input a number with prompt (233)

Print error message
Input a number with prompt (101)

Print error message
Input a number (\PYGZhy{}1)

Print error message
Input a number with prompt (100)

Return 100
\end{Verbatim}

When you consider \code{while} loops, there is a problem with the first version:
Before the first pass through the loop and at the end of the block of code
in the body of the loop, you must be \emph{able} to run the test in the
while heading.  We will be testing the latest input from the user.

It is the second version that has us getting new input
\emph{before the first} loop \emph{and} at the \emph{end of each} loop!

Now we can think more of the basic process to turn this into a C\# solution:
What variables do we need?   We will call the user's response \code{number}.

What is the test in the while loop heading?
The easiest thing to think of is that we are done when
we get something correct.  That, however, is a \emph{termination} condition.
We need to reverse it to get the \emph{continuation condition}, that the answer is
out of range.  There are two ways to be out of range:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{number} \PYG{p}{\PYGZlt{}} \PYG{n}{lowLim}
\PYG{n}{number} \PYG{p}{\PYGZgt{}} \PYG{n}{highLim}
\end{Verbatim}

How do we combine them?  Either one rules out a correct answer,
so \code{number} is out of range
if too high OR too low.  Remember the C\# symbolism for ``or'': \code{\textbar{}\textbar{}}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{while} \PYG{p}{(}\PYG{n}{number} \PYG{p}{\PYGZlt{}} \PYG{n}{lowLim} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{number} \PYG{p}{\PYGZgt{}} \PYG{n}{highLim}\PYG{p}{)} \PYG{p}{\PYGZob{}}
\end{Verbatim}

Following the sequence in the concrete example we had above,
we can see how to put things
together.
We need to get input from the user \emph{before} first beginning
the \code{while} loop, so we immediately have something to test
in the \code{while} heading's condition.

Do not reinvent the wheel!
We can use our earlier general \code{PromptInt} function.  It needs a prompt.
As a first version, we can use the parameter \code{prompt}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{number} \PYG{p}{=} \PYG{n}{PromptInt}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

That is the initialization step before the loop.

\index{pitfall!repeat interactive input}\index{interactive while loop!repeat interactive input}
\emph{If} we get into the body of the loop, it means there is an error,
and the concrete example indicates we print a warning message.
The concrete example \emph{also} shows another step in the loop, asking
the user for input.  It is
easy to think
\begin{quote}

``I already have the code included to read a value from the user,
so there is nothing really to do.''
\end{quote}

WRONG!  The initialization code with
the input from the user is \emph{before} the loop.  C\# execution approaches the
test in the \code{while} headings from \emph{two} places at different times:
the initialization \emph{and} coming back
from the bottom of the loop.  To get a \emph{new} value to test, we must
\emph{repeat} getting input from the user at the \emph{bottom of the loop body}.

\index{compiler error!declaration repeat}\index{declaration repeat error}\index{type!declaration repeat error}
You might decide to be quick
and just copy the initialization line into the bottom of the
loop (and indent it):

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{number} \PYG{p}{=} \PYG{n}{PromptInt}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

Luckily you will get a compiler error in that situation, avoiding
more major troubleshooting:
The \emph{complete} copy of the line copies the \emph{declaration}
part as well as the assignment part, and the compiler sees the declaration of
\code{number} already there
from the scope outside the while block, and complains.

Hence copy the line, \emph{without} the \code{int} declaration:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{number} \PYG{p}{=} \PYG{n}{PromptInt}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

When the loop condition becomes false, and you get past the loop,
you have a correct value in \code{number}.  You have done all the hard work.
Do not forget to return it at the end.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Prompt the user to obtain an int until the response is in the}
      \PYG{c+c1}{/// range [lowLim, highLim].  Then return the int in range.}
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{PromptIntInRange}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{prompt}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{lowLim}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{highLim}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{number} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{number} \PYG{p}{\PYGZlt{}} \PYG{n}{lowLim} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{number} \PYG{p}{\PYGZgt{}} \PYG{n}{highLim}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} is out of range!\PYGZdq{}}\PYG{p}{,} \PYG{n}{number}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{number} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{number}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

You can try this full example, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/input\_in\_range1/input\_in\_range1.cs}{input\_in\_range1/input\_in\_range1.cs}.
Look at it and then try compiling and running.

Look at the Main code.
It is redundant - the limits are written both in the prompt and in the
parameters.  We can do better.  In general we endeavor to supply data only
once, and let the program use it in several places if it needs to.
Since the limits are given as parameters, anyway, we prefer
to have the program elaborate the prompt automatically.
If the limits are -10 and 10,
automatically add to the prompt something like (-10 through 10).

We could use

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{} (\PYGZob{}0\PYGZcb{} through \PYGZob{}1\PYGZcb{}) \PYGZdq{}}\PYG{p}{,} \PYG{n}{lowLim}\PYG{p}{,} \PYG{n}{highLim}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

but we need the code twice, producing the same string each time.
If you recall the
{\hyperref[funcreturn:string-format]{\emph{string.Format function}}}, then we can just create
the string once, and use it twice.
Here is a revised version, in example
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/input\_in\_range2/input\_in\_range2.cs}{input\_in\_range2/input\_in\_range2.cs},
without redundancy in the prompts in \code{Main}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)} \PYG{c+c1}{//testing routine}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{n} \PYG{p}{=} \PYG{n}{PromptIntInRange}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter a score: \PYGZdq{}}\PYG{p}{,} \PYG{l+m}{0}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Your score is \PYGZob{}0\PYGZcb{}.\PYGZdq{}}\PYG{p}{,} \PYG{n}{n}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Try another test.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{n} \PYG{p}{=} \PYG{n}{PromptIntInRange}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter a number: \PYGZdq{}}\PYG{p}{,} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Your number is \PYGZob{}0\PYGZcb{}.\PYGZdq{}}\PYG{p}{,} \PYG{n}{n}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}      
                                                 
      \PYG{c+c1}{/// Prompt the user to obtain an int until the response is in the}
      \PYG{c+c1}{/// range [lowLim, highLim].  Then return the int in range.}
      \PYG{c+c1}{/// Use the specified prompt, adding a reminder of the allowed range.}
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{PromptIntInRange}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{prompt}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{lowLim}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{highLim}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{string} \PYG{n}{longPrompt} \PYG{p}{=} \PYG{k+kt}{string}\PYG{p}{.}\PYG{n}{Format}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} (\PYGZob{}1\PYGZcb{} through \PYGZob{}2\PYGZcb{}) \PYGZdq{}}\PYG{p}{,}
                                           \PYG{n}{prompt}\PYG{p}{,} \PYG{n}{lowLim}\PYG{p}{,} \PYG{n}{highLim}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{number} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{n}{longPrompt}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{number} \PYG{p}{\PYGZlt{}} \PYG{n}{lowLim} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{number} \PYG{p}{\PYGZgt{}} \PYG{n}{highLim}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} is out of range!\PYGZdq{}}\PYG{p}{,} \PYG{n}{number}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{number} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{n}{longPrompt}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{number}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

This time around we did the user input correctly, with the
request for new input \emph{repeated} at the end of the loop.
That repetition \emph{is} easy to forget.  Before we see what happens
when you forget, note:

\index{pitfall!infinite loop}\index{infinite loop}
\begin{notice}{warning}{Warning:}
A \code{while} loop may be written so the continuation condition is
\emph{always} true, and the loop \emph{never} stops by itself.
This is an \emph{infinite loop}.
In practice, in many operating environments, particularly
where you are getting input from the user,
you can abort the execution of a program in
an infinite loop by entering
\code{Ctrl-C}.
\end{notice}

In particular you get an infinite loop
if you fail to get new input from the user at the
end of the loop.  The condition uses the bad
original choice forever.  Here is the loop in the mistaken version,
from example  \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/input\_in\_range2\_bad/input\_in\_range2\_bad.cs}{input\_in\_range2\_bad/input\_in\_range2\_bad.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
         \PYG{k+kt}{int} \PYG{n}{number} \PYG{p}{=} \PYG{n}{UIF}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{n}{longPrompt}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{number} \PYG{p}{\PYGZlt{}} \PYG{n}{lowLim} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{number} \PYG{p}{\PYGZgt{}} \PYG{n}{highLim}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{c+c1}{// infinte loop!}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} is out of range!\PYGZdq{}}\PYG{p}{,} \PYG{n}{number}\PYG{p}{)}\PYG{p}{;}
            \PYG{c+c1}{// number = UIF.PromptInt(longPrompt); //OMITS repeated prompt!}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{number}\PYG{p}{;}
\end{Verbatim}

You can run the program.  Remember \code{Ctrl-C} !
There are two tests in \code{Main}.
If you give a legal answer immediately in the first test,
it works fine (never getting into the loop body).  If you
give a bad input in the second test, you see that you can never fix it!
Remember \code{Ctrl-C} !

A more extreme abort is to close the entire console/terminal window
running the program.

\index{exercise!Agree}\index{Agree exercise}

\subsection{Agree Function Exercise}
\label{whileinteractive:index-5}\label{whileinteractive:agree-function-exercise}\label{whileinteractive:id2}
Save example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/test\_agree\_stub/test\_agree.cs}{test\_agree\_stub/test\_agree.cs}
in a project of your own.

Yes-no (true/false) questions are common.
How might you write an input utility function \code{Agree}?
You can speed things
up by considering only the first letter of responses.
Assume that it is important that the user makes a clear response:
Then you should
consider three categories of answer:  ones accepted as true,
ones accepted as false, and ambiguous ones.
You need to allow for
the possibility that the user keeps
giving ambiguous answers for some time....


\subsection{Interactive Sum Exercise}
\label{whileinteractive:interactive-sumex}\label{whileinteractive:interactive-sum-exercise}
Write a program \code{sum\_all.cs} that prompts the user to enter
numbers, one per line, ending with a line containing 0, and keep a
running sum of the numbers. Only print out the sum after all the
numbers are entered (at least in your \emph{final} version).

\index{exercise!InputWhole}\index{InputWhole exercise}

\subsection{Safe Whole Number Input Exercise}
\label{whileinteractive:safe-whole-number-input}\label{whileinteractive:index-6}\label{whileinteractive:safe-whole-number-input-exercise}
Save example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/test\_input\_whole\_stub/test\_input\_whole.cs}{test\_input\_whole\_stub/test\_input\_whole.cs} as
a project of your own.  The code should test
a function \code{PromptWhole}, as described below.

There is an issue with reading in numbers with the PromptInt function.
If you make a typo and enter something that cannot be converted from a
string to the right kind of number, a naive program will bomb.
This is avoidable if you test the string and repeat the input
if the string is illegal.
Places where more complicated tests for illegality are needed are
considered in {\hyperref[stringmethods2:safe-input-number]{\emph{Safer PromptInt and PromptDouble Exercise}}} and
{\hyperref[stringmethods2:safest-input-int]{\emph{Safest PromptInt Exercise}}}.  For now we just consider
reading in whole numbers (integers greater than or equal to 0).
Note that such
a number is written as just a sequence of digits.
Follow the interactive model of PromptIntInRange, looping until
the user enters something that is legal: in this case, all digits.

The stub code already includes the earlier function \code{IsDigits}.

\index{short-circuit \&\& and \textbar{}\textbar{}}\index{\textbar{}\textbar{}!short-circuit}\index{\&\&!short-circuit}

\section{Short-Circuiting \&\& and \textbar{}\textbar{}}
\label{condition-short-circuit:short-circuiting-and}\label{condition-short-circuit:short-circuit}\label{condition-short-circuit:index-0}\label{condition-short-circuit::doc}
Follow along with the following silly, but illustrative csharp sequence:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{int} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{,} \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{,} \PYG{n}{z} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{y}\PYG{p}{/}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{n}{z} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{x} \PYG{p}{!}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
\PYG{k}{false}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;} \PYG{n}{y} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{y}\PYG{p}{/}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{n}{z} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{x} \PYG{p}{!}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
\PYG{k}{true}
\end{Verbatim}

The compound condition includes \code{x != 0},
so what happens if we change x to 0 and
try the condition again.  Will you get \code{false}?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{x} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{y}\PYG{p}{/}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{n}{z} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{x} \PYG{p}{!}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
\PYG{n}{System}\PYG{p}{.}\PYG{n}{DivideByZeroException}\PYG{p}{:} \PYG{n}{Division} \PYG{n}{by} \PYG{n}{zero}
\PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
\end{Verbatim}

No, one of the parts involves dividing by zero, and you see the result.
What if we swap the two conditions to get the \emph{logically equivalent}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{x} \PYG{p}{!}\PYG{p}{=} \PYG{l+m}{0} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{y}\PYG{p}{/}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{n}{z}\PYG{p}{;}
\PYG{k}{false}
\end{Verbatim}

Something is going on here besides pure mathematical logic.
Remember the final version in {\hyperref[while-with-sequence:isdigits]{\emph{IsDigits}}}.  We did not
need to continue processing when we knew the final answer
already.  The \code{\&\&} and \code{\textbar{}\textbar{}} operators work the same way,
evaluating from left to right.  If \code{x != 0} is \code{false},
then \code{x != 0 \&\& y/x \textgreater{} z} starts off being evaluated like
\code{false \&\& ??}.  We do no need the second part evaluated to
know the overall result is \code{false}, so C\#
\emph{does not evaluate further}.  This behavior has
acquired the jargon \emph{short-circuiting}.  Many computer languages share
this feature.

It also applies to \code{\textbar{}\textbar{}}.  In what situation do you know
what the final result is after evaluating
the first condition?  In this case you know:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{true} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{p}{?}\PYG{p}{?}
\end{Verbatim}

evaluates to true.  Continuing with the same csharp sequence above
(where x is 0, y is 5, and z is 1):

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{x} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{y}\PYG{p}{/}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{n}{z}\PYG{p}{;}
\PYG{k}{true}
\end{Verbatim}

The division by 0 in the second condition \emph{never happens}.
It is short-circuited.

For completeness, try the other order:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{y}\PYG{p}{/}\PYG{n}{x} \PYG{p}{\PYGZgt{}} \PYG{n}{z} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{x} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
\PYG{n}{System}\PYG{p}{.}\PYG{n}{DivideByZeroException}\PYG{p}{:} \PYG{n}{Division} \PYG{n}{by} \PYG{n}{zero}
\PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
\end{Verbatim}

This idea is useful in the \code{Agree} function, where you
want to deal with the first character in the user's answer.

In situations where you want to
test conditionThatWillBombWithBadData, you want to avoid
causing an Exception.
When there is good data, you want the result to actually
come from conditionThatWillBombWithBadData.  There are two cases,
however, depending on what result
you want if the data for this condition \emph{is bad}, so you cannot evaluate it:
\begin{itemize}
\item {} 
If you want the result to be \code{false} with bad data for the dangerous
condition, use
\begin{quote}

falseConditionIfDataBad \code{\&\&} conditionThatWillBombWithBadData
\end{quote}

\item {} 
If you want the result to be \code{true} with bad data for
the dangerous condition, use
\begin{quote}

trueConditionIfDataBad \code{\textbar{}\textbar{}} conditionThatWillBombWithBadData
\end{quote}

\end{itemize}


\section{While Examples}
\label{whileexamples:while-examples}\label{whileexamples::doc}
\index{bisection method}

\subsection{Bisection Method}
\label{whileexamples:index-0}\label{whileexamples:bisection-method}\label{whileexamples:id1}
For a very different example we look to scientific computing.  In math
class you likely learned various ways to find roots of functions f(x) exactly.
In practice those methods almost never work beyond low order polynomials.
Hence the best we can do usually is to approximate solutions numerically.
One broadly useful approach is the \emph{bisection method}.  You just need a
continuous function (with an unbroken graph),
and you need to first find two places,
a and b, where f(a) and f(b) have opposite signs. If f is continuous and goes
between positive and negative values, then it must cross 0 somewhere in between,
and so there must be a real solution.  The question is how to get close
to a crossing point efficiently.

As an example we show \(f(x)=x^2 - 2\), in the range from x = 0 to x = 2.
As a first example we choose a simple function where the root can be figured symbolically,
in this case the square root of 2.  The figure below shows the graph,
with extra horizontal and vertical lines that will will be explained.

\includegraphics[width=233.25pt]{bisection.png}

In the figure a= 0, f(0) \textless{} 0, b = 2, f(2) \textgreater{} 0.

The basic idea is to bisect the interval between a and b, finding the midpoint,
c = (a+b)/2. If f(c) is 0, you are done.
Otherwise f(c) has a sign which must be opposite \emph{one} of f(a) and f(b).

In the figure the initial interval has the same x coordinates as for the top gray line.
Its midpoint is at 1, the x coordinate of the red vertical segment coming down from
the top gray line in the figure.  Note f(1) \textless{} 0, the opposite sign of f(2),
so we next consider the half of the original interval from the midpoint 1 to 2,
with the next gray line marking this interval.
The function still must cross 0 in the smaller interval because of the opposite
signs for f on the endpoints.  In
the iterative procedure, you  continue this process, halving the length of
the interval,
shifting one endpoint or the other to be the middle
of the most recent interval, so for each interval, the signs of f on
the two ends are opposite.
Repeating this procedure, you can home in on as small an interval around a
crossing point (root) as you like.
The figure show this process for the first 5 steps,
halving the interval length each time.  You need to look at the output of the code to
follow the results for even smaller intervals.

This approach always works, as long as the signs of f
at the initial endpoints are distinct.  Our \code{Bisection} functions check,
and if this initial requirement
is violated, the function returns the special double code value,
\code{double.NaN}, meaning \emph{not a number}.

There are other approaches to finding roots that may be faster when they work,
but many of these methods can also have some chance of completely failing,
so root finding algorithms generally have two
extra parameters:  a maximum number of iterations and a tolerance that
indicates how close to a root is close enough.

In the \code{Bisection} function we use \code{a} and \code{b}
as the endpoints of an interval and \code{c} as the
midpoint.  In each iteration the value of \code{a} or \code{b} is reset to be the
previous midpoint value \code{c}.
Of course a production version would not print out all the intermediate data,
as the interval shrinks, but we do for illustration:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{double} \PYG{n+nf}{Bisection}\PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{double} \PYG{n}{b}\PYG{p}{,} 
                                     \PYG{k+kt}{double} \PYG{n}{tolerance}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{iterations}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{c+c1}{// check the preconditions for the method to work}
         \PYG{c+c1}{// a must be less than b so we can do the interval search }
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{a} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{n}{b}\PYG{p}{)}
            \PYG{k}{return} \PYG{k+kt}{double}\PYG{p}{.}\PYG{n}{NaN}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}a \PYGZgt{}= b ok\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{bool} \PYG{n}{ok} \PYG{p}{=} \PYG{k}{false}\PYG{p}{;}

         \PYG{c+c1}{// The function must cross the x\PYGZhy{}axis between the endpoints, }
         \PYG{c+c1}{//   meaning its sign changes. }
         \PYG{k}{if} \PYG{p}{(}\PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{a}\PYG{p}{)} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{f}\PYG{p}{(}\PYG{n}{b}\PYG{p}{)} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Test 1 passed\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{ok} \PYG{p}{=} \PYG{k}{true}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{if} \PYG{p}{(}\PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{a}\PYG{p}{)} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{f}\PYG{p}{(}\PYG{n}{b}\PYG{p}{)} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Test 2 passed\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{ok} \PYG{p}{=} \PYG{k}{true}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{if} \PYG{p}{(}\PYG{p}{!}\PYG{n}{ok}\PYG{p}{)}
            \PYG{k}{return} \PYG{k+kt}{double}\PYG{p}{.}\PYG{n}{NaN}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{n} \PYG{p}{\PYGZlt{}} \PYG{n}{iterations}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{double} \PYG{n}{c} \PYG{p}{=} \PYG{p}{(}\PYG{n}{a} \PYG{p}{+} \PYG{n}{b}\PYG{p}{)} \PYG{p}{/} \PYG{l+m}{2}\PYG{p}{;}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}a = \PYGZob{}0\PYGZcb{}  b=\PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{)}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{c}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{p}{(}\PYG{n}{b} \PYG{p}{\PYGZhy{}} \PYG{n}{a}\PYG{p}{)}\PYG{p}{/}\PYG{l+m}{2} \PYG{p}{\PYGZlt{}} \PYG{n}{tolerance}\PYG{p}{)}
               \PYG{k}{return} \PYG{n}{c}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{Math}\PYG{p}{.}\PYG{n}{Sign}\PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{c}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Sign}\PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{a}\PYG{p}{)}\PYG{p}{)}\PYG{p}{)}
               \PYG{n}{a} \PYG{p}{=} \PYG{n}{c}\PYG{p}{;}
            \PYG{k}{else}
               \PYG{n}{b} \PYG{p}{=} \PYG{n}{c}\PYG{p}{;}
            \PYG{n}{n}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{k+kt}{double}\PYG{p}{.}\PYG{n}{NaN}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Since the bisection method always homes in on a real root rapidly,
an alternate version specifically for the bisection method
finds the \emph{best} approximation possible with \code{double}
arithmetic.  While you can always halve an interval mathematically, you
eventually run out of distinct \code{double} values! We can stop when
the midpoint (calculated with limited \code{double} precision)
is \emph{exactly} the same as \code{a} or \code{b}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// This bisection method returns the best double approximation}
      \PYG{c+c1}{/// to a root of f.  Returns double.NaN if the f(a)*f(b) \PYGZgt{} 0.}
      \PYG{c+c1}{/// Does not require a \PYGZlt{} b.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{double} \PYG{n+nf}{Bisection}\PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{double} \PYG{n}{b}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{a}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} 
            \PYG{k}{return} \PYG{n}{a}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{b}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} 
            \PYG{k}{return} \PYG{n}{b}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{Math}\PYG{p}{.}\PYG{n}{Sign}\PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{b}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Sign} \PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{a}\PYG{p}{)}\PYG{p}{)}\PYG{p}{)}  \PYG{c+c1}{//or f(a)*f(b)\PYGZgt{}0}
            \PYG{k}{return} \PYG{k+kt}{double}\PYG{p}{.}\PYG{n}{NaN}\PYG{p}{;}
         \PYG{k+kt}{double} \PYG{n}{c} \PYG{p}{=} \PYG{p}{(}\PYG{n}{a} \PYG{p}{+} \PYG{n}{b}\PYG{p}{)} \PYG{p}{/} \PYG{l+m}{2}\PYG{p}{;}
         \PYG{c+c1}{// If no f(c) is exactly 0, iterate until the smallest possible }
         \PYG{c+c1}{// double interval, when there is no distinct double midpoint.}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{c} \PYG{p}{!}\PYG{p}{=} \PYG{n}{a} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{c} \PYG{p}{!}\PYG{p}{=} \PYG{n}{b}\PYG{p}{)} \PYG{p}{\PYGZob{}} 
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}a = \PYGZob{}0\PYGZcb{}  b= \PYGZob{}1\PYGZcb{}, diff = \PYGZob{}2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{,} \PYG{n}{b}\PYG{p}{\PYGZhy{}}\PYG{n}{a}\PYG{p}{)}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{c}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} 
               \PYG{k}{return} \PYG{n}{c}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{Math}\PYG{p}{.}\PYG{n}{Sign}\PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{c}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Sign}\PYG{p}{(}\PYG{n}{f}\PYG{p}{(}\PYG{n}{a}\PYG{p}{)}\PYG{p}{)}\PYG{p}{)}
               \PYG{n}{a} \PYG{p}{=} \PYG{n}{c}\PYG{p}{;}
            \PYG{k}{else}
               \PYG{n}{b} \PYG{p}{=} \PYG{n}{c}\PYG{p}{;}
            \PYG{n}{c} \PYG{p}{=} \PYG{p}{(}\PYG{n}{a} \PYG{p}{+} \PYG{n}{b}\PYG{p}{)} \PYG{p}{/} \PYG{l+m}{2}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{c}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

C\# remembers \code{double} values to more decimal places than it will actually
display, so the second illustration also shows the difference between \code{a} and \code{b},
indicating the double values are still not really equal even after their
displays match.

You can try this full example,
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/bisection\_method1/bisection\_method1.cs}{bisection\_method1/bisection\_method1.cs}.
Note the special function checking for \code{double.NaN} in \code{Main},
because \code{double.NaN} is not equal to itself!

The current versions have a major limitation:  They just work with the one
canned version of the function \code{f} in the class.
You need to edit
the source code to use the same process with a different function!
There are several ways around this using more advanced C\# features.
After the section {\hyperref[interfaces:interface]{\emph{Interfaces}}}, a more flexible version
should make sense, \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/bisection\_method/bisection\_method.cs}{bisection\_method/bisection\_method.cs},
explored further in {\hyperref[csproj-revisited:bisection-exercise]{\emph{Bisection With Function Interface Exercise}}}.  The more
advanced version illustrates with the function in the initial version and
several others, all using the same bisection function.

\index{exercise!savings}

\subsection{Savings Exercise}
\label{whileexamples:id2}\label{whileexamples:savings-exercise}\label{whileexamples:index-1}
The idea here is to see how many years it will take a bank account to grow
to at least a given value, assuming a fixed annual interest.
Write a program \code{savings.cs}.
Prompts the user for three numbers: an initial balance, the annual percentage
for interest as a decimal. like .04 for 4\%, and the final balance desired.
Print the initial balance, and the balance each year until
the desired amount is reached. Round displayed amounts
to two decimal places, as usual.

The math:  The amount next year is the amount now times
(1 + interest fraction),
so if I have \$500 now and the interest rate is .04,
I have \$500*(1.04) = \$520 after one year, and after two years I have,
\$520*(1.04) = \$540.80.
If I enter into the program a \$500 starting balance, .04 interest rate and
a target of \$550, the program prints:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+m}{5}\PYG{l+m}{0}\PYG{l+m}{0.00}
\PYG{l+m}{5}\PYG{l+m}{2}\PYG{l+m}{0.00}
\PYG{l+m}{5}\PYG{l+m}{4}\PYG{l+m}{0.80}
\PYG{l+m}{5}\PYG{l+m}{6}\PYG{l+m}{3.42}
\end{Verbatim}

\index{exercise!strange sequence}

\subsection{Strange Sequence Exercise}
\label{whileexamples:strange-sequence-exercise}\label{whileexamples:index-2}\label{whileexamples:strange-seq-ex}
Save the example program \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/strange\_seq\_stub/strange\_seq.cs}{strange\_seq\_stub/strange\_seq.cs}
in a project of your own.

There are three functions to complete.  Do one at a time and test.

\code{Jump}: First complete the definitions of function \code{Jump}.
For any integer \code{n}, \code{Jump(n)} is \code{n/2} if \code{n} is even,
and \code{3*n+1} if \code{n} is odd.
In the \code{Jump} function definition use an \code{if}-\code{else}
statement.  Hint \footnote{
If you divide an even number by 2, what is the remainder?  Use this idea
in your \code{if} condition.
}

\code{PrintStrangeSequence}:
You can start with one number, say n = 3, and \emph{keep} applying the
\code{Jump} function to the \emph{last} number given,
and see how the numbers jump around!

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Jump}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{)} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{*}\PYG{l+m}{3}\PYG{p}{+}\PYG{l+m}{1} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{Jump}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{)} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{/}\PYG{l+m}{2} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{n}{Jump}\PYG{p}{(}\PYG{l+m}{5}\PYG{p}{)} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{*}\PYG{l+m}{5}\PYG{p}{+}\PYG{l+m}{1} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{6}\PYG{p}{;} \PYG{n}{Jump}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{6}\PYG{p}{)} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{6}\PYG{p}{/}\PYG{l+m}{2} \PYG{p}{=} \PYG{l+m}{8}\PYG{p}{;}
\PYG{n}{Jump}\PYG{p}{(}\PYG{l+m}{8}\PYG{p}{)} \PYG{p}{=} \PYG{l+m}{8}\PYG{p}{/}\PYG{l+m}{2}  \PYG{p}{=}   \PYG{l+m}{4}\PYG{p}{;} \PYG{n}{Jump}\PYG{p}{(}\PYG{l+m}{4}\PYG{p}{)} \PYG{p}{=}   \PYG{l+m}{4}\PYG{p}{/}\PYG{l+m}{2} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}
\PYG{n}{Jump}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{)} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{/}\PYG{l+m}{2}  \PYG{p}{=}   \PYG{l+m}{1}
\end{Verbatim}

This process of repeatedly applying the same function to the most recent result
is called function \emph{iteration}.  In this case you see that iterating the
\code{Jump} function, starting from n=3, eventually reaches the value 1.

It is an \emph{open research question} whether iterating the Jump function
from an integer \code{n} will eventually reach 1,
for \emph{every} starting integer \code{n} greater than 1.
Researchers have only found examples of \code{n} where it is true.
Still, no general argument has been made to apply to the
\emph{infinite} number of possible starting integers.

In the PrintStrangeSequence you iterate the \code{Jump} function
starting from parameter value \code{n}, as long as the current number is not 1.
If you start with 1, stop immediately.

\code{CountStrangeSequence}:  Iterate the \code{Jump} function as in
\code{PrintStrangeSequence}.  Instead of printing each number in the sequence,
just count them, and return the count.

\index{exercise!roundoff II}

\subsection{Roundoff Exercise II}
\label{whileexamples:roundoff-exercise-ii}\label{whileexamples:roundoff2}\label{whileexamples:index-3}
Write a program to complete and test the function with this heading
and documentation:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return the largest possible number y, so in C\PYGZsh{}: x+y = x}
\PYG{c+c1}{/// If x is Infinity return Infinity.}
\PYG{c+c1}{/// If x is \PYGZhy{}Infinity, return double.MaxValue.}
\PYG{c+c1}{/// Assume x is not NaN (which is equal to nothing).}
\PYG{k}{static} \PYG{k+kt}{double} \PYG{n+nf}{Epsilon}\PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{x}\PYG{p}{)}
\end{Verbatim}

Hint:  The non-exceptional case can have some similarity
to the bisection in the best root approximation example:
start with two endpoints, \code{a} and \code{b}, where \code{x+a = x} and
\code{x+b \textgreater{} x}, and reduce the interval size by half....

\index{string!method}

\section{More String Methods}
\label{stringmethods2:more-string-methods}\label{stringmethods2:index-0}\label{stringmethods2::doc}\label{stringmethods2:id1}
Before we do more elaborate things with strings, some more string methods
will be helpful.  Be sure you are familiar with the earlier discussion of
strings in
{\hyperref[basicstringops:basic-string-ops]{\emph{Basic String Operations}}}.

Play with the new string methods in csharp!

This variation of \code{IndexOf} has a second parameter:

\index{string!IndexOf}\index{IndexOf string method}\begin{description}
\item[{\code{int IndexOf(string target, int start)}}] \leavevmode
Returns the index of the beginning of the first occurrence of the string
\code{target}
in \textbf{this} string object, starting at index \code{start} or after.
Returns -1 if \code{target} is not found. Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{state} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Mississippi\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{print}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}01234567890\PYGZbs{}n\PYGZdq{}}\PYG{p}{+}\PYG{n}{state}\PYG{p}{)} \PYG{c+c1}{// to see indices}
\PYG{l+m}{0}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{3}\PYG{l+m}{4}\PYG{l+m}{5}\PYG{l+m}{6}\PYG{l+m}{7}\PYG{l+m}{8}\PYG{l+m}{9}\PYG{l+m}{0}
\PYG{n}{Mississippi}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{state}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}is\PYGZdq{}}\PYG{p}{,} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// same as state.IndexOf(\PYGZdq{}is\PYGZdq{});}
\PYG{l+m}{1}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{state}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}is\PYGZdq{}}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{4}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{state}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}is\PYGZdq{}}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{state}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}i\PYGZdq{}}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{7}
\end{Verbatim}

\end{description}

\index{string!Trim}\index{Trim string method}\begin{description}
\item[{\code{string Trim()}}] \leavevmode
Returns a string formed from \textbf{this} string object, but
with leading and trailing whitespace removed. Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} string s = \PYGZdq{}\PYGZbs{}n  123    \PYGZdq{};
csharp\PYGZgt{} \PYGZdq{}\PYGZsh{}\PYGZdq{} + s + \PYGZdq{}\PYGZsh{}\PYGZdq{};
\PYGZsh{}
  123   \PYGZsh{}
csharp\PYGZgt{} \PYGZdq{}\PYGZsh{}\PYGZdq{} + s.Trim() + \PYGZdq{}\PYGZsh{}\PYGZdq{};
\PYGZsh{}123\PYGZsh{}
\end{Verbatim}

\end{description}

\index{string!Replace}\index{Replace string method}\begin{description}
\item[{\code{string Replace(string target, string replacement)}}] \leavevmode
Returns a string formed from \textbf{this} string by replacing
all occurrences of the substring \code{target} by \code{replacement}.
Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}This is it!\PYGZdq{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Replace}\PYG{p}{(}\PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}/\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}This/is/it!\PYGZdq{}}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Replace}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}is\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}at\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}That at it!\PYGZdq{}}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{l+s}{\PYGZdq{}oooooh\PYGZdq{}}\PYG{p}{.}\PYG{n}{Replace}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}oo\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}ah\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{l+s}{\PYGZdq{}ahahoh\PYGZdq{}}
\end{Verbatim}

\end{description}

\index{string!StartsWith}\index{StartsWith string method}\begin{description}
\item[{\code{bool StartsWith(string prefix)}}] \leavevmode
Returns \code{true} if  \textbf{this} string object starts
with string \code{prefix}, and \code{false} otherwise.
Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{l+s}{\PYGZdq{}\PYGZhy{}123\PYGZdq{}}\PYG{p}{.}\PYG{n}{StartsWith}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZhy{}\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{true}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{l+s}{\PYGZdq{}downstairs\PYGZdq{}}\PYG{p}{.}\PYG{n}{StartsWith}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}down\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{true}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{l+s}{\PYGZdq{}1 \PYGZhy{} 2 \PYGZhy{} 3\PYGZdq{}}\PYG{p}{.}\PYG{n}{StartsWith}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZhy{}\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{false}
\end{Verbatim}

\end{description}

\index{string!EndsWith}\index{EndsWith string method}\begin{description}
\item[{\code{bool EndsWith(string suffix)}}] \leavevmode
Returns \code{true} if  \textbf{this} string object ends
with string \code{suffix}, and \code{false} otherwise.
Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{l+s}{\PYGZdq{}\PYGZhy{}123\PYGZdq{}}\PYG{p}{.}\PYG{n}{EndsWith}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZhy{}\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{false}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{l+s}{\PYGZdq{}downstairs\PYGZdq{}}\PYG{p}{.}\PYG{n}{EndsWith}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}airs\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{true}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{l+s}{\PYGZdq{}downstairs\PYGZdq{}}\PYG{p}{.}\PYG{n}{EndsWith}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}air\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{false}
\end{Verbatim}

\end{description}

\index{exercise!CountRep}\index{CountRep exercise}

\subsection{Count Repetitions in a String Exercise}
\label{stringmethods2:index-6}\label{stringmethods2:countrep}\label{stringmethods2:count-repetitions-in-a-string-exercise}
Write a program \code{test\_count\_rep.cs}, with a Main testing method,
that tests a function with the following heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// Return the number of separate repetitions of target in s.}
\PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{CountRep}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{target}\PYG{p}{)}
\end{Verbatim}

For example here is what \code{CountRep( "Mississippi", target)}
would return with various values for \code{target}:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{"i"}: 4
\item[] \code{"is"}: 2
\item[] \code{"sss"}: 0
\end{DUlineblock}
\end{quote}

Assume each repetition is completely separate, so
\code{CountRep("Wheee!", "ee")} returns 1.  The last
two e's do not count, since the middle e is already
used in the match of the first two e's.

\index{exercise!safe PromptInt and PromptDouble}\index{safe PromptInt and PromptDouble exercises}

\subsection{Safer PromptInt and PromptDouble Exercise}
\label{stringmethods2:safer-promptint-and-promptdouble-exercise}\label{stringmethods2:index-7}\label{stringmethods2:safe-input-number}
Save the example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/safe\_number\_input\_stub/safe\_number\_input.cs}{safe\_number\_input\_stub/safe\_number\_input.cs}
in a project of your own.

The idea is to write safe versions of the utility functions
PromptInt and PromptDouble (which can then be used in further
places like PromptIntInRange).

Be sure you are familiar with {\hyperref[whileinteractive:safe-whole-number-input]{\emph{Safe Whole Number Input Exercise}}},
and the development of its \code{InputWhole} function.

A legal whole number string consists entirely of digits.  We have
already written example \code{IsDigits} to identify a string for a
whole number.

The  improvements to PromptInt and PromptDouble are
very similar and straightforward \emph{if} you have developed the two main
Boolean support functions,
\code{IsIntString} and \code{IsDecimalString} respectively.

A complicating issue with integer and decimal strings
is that they may include parts other than
digits.  An integer may start with a minus sign.  A
decimal number can also contain a decimal point in an appropriate
place.  The suggestion is to confirm that these other characters appear in
legal places, remove them, and see that what is left is digits.
The recently introduced string methods should help....

Using the ideas above,
develop the functions in order and test after each one:
write \code{IsIntString}, revise \code{PromptInt},
write \code{IsDecimalString}, and revise \code{PromptDouble}.

Be sure to test carefully.  Not only confirm that all
appropriate strings return \code{true}:
Also be sure to test that you return \code{false"}
for \emph{all} sorts of bad strings.

There is still one issue with \code{IsIntString} not considered yet:  see
the next exercise for the final improvement.

Hopefully
you learned something from writing the earlier PromptWhole.
Probably it is not worth keeping in our utility library
any longer, since we have
the more general and safe PromptInt, and we can
restrict to many ranges with PromptIntInRange.

We will arrange for these functions to be a library class later.
For now just develop and test them in this one class.


\subsection{Safest PromptInt Exercise}
\label{stringmethods2:safest-input-int}\label{stringmethods2:safest-promptint-exercise}
With the suggestions so far the in the previous exercise,
\code{IsIntString} will catch a strange stray character, and be
sure that the string for an \emph{integer} is entered, but an \code{int} is
not an arbitrary integer:  it has limited range, between
\code{int.MinValue} =  -2147483648 and \code{int.MaxValue} = 2147483647.

Revise the \code{IsIntString} function of the previous
exercise so that it checks that the result is in range, too, allowing
the PromptInt function to be totally reliable.

There is a problem:  your current version of IsIntString is likely
to accept a string like \code{"9876543210"}, and you cannot convert it to an
\code{int} to do the comparison to see that it is in fact
too large for an \code{int}!  Catch 22?

There is an alternate approach involving comparing strings, not numbers.

There is a string instance method:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k+kt}{int} \PYG{n+nf}{CompareTo}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{t}\PYG{p}{)}
\end{Verbatim}

It does roughly lexicographical string comparisons, so

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{s}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{n}{t}\PYG{p}{)} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{0}
\end{Verbatim}

is true when s ``comes before'' t or is equal to t.  This works with
alphabetizing letter strings:  ``at'' comes before ``ate'' which comes before
``attention'' which comes before ``eat''.  It also works with digit strings
\emph{of the same length}
to give the same relationship as the corresponding numbers:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+s}{\PYGZdq{}123456890\PYGZdq{}}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}2147483647\PYGZdq{}}\PYG{p}{)} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{0}
\end{Verbatim}

is true, and

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+s}{\PYGZdq{}9876543210\PYGZdq{}}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}2147483647\PYGZdq{}}\PYG{p}{)} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{0}
\end{Verbatim}

is false.

This idea can be leveraged into a completely reliable version of IsIntString.
(With this approach you could also create an IsLongString very similarly,
but we skip it since it teaches you nothing new.)

The idea of a \code{CompareTo} method is much more general
and is used much later in {\hyperref[fractions-revisited:rationals-revisited]{\emph{Rationals Revisited}}}.

\index{library!UI}\index{UI library class}

\section{User Input: UI}
\label{userinput:user-input-ui}\label{userinput:ui}\label{userinput:index-0}\label{userinput::doc}
With the exercises in the last section, we have all we need for a much improved
User Input library class.  This will be the class \code{UI}.
We have the original \code{PromptLine}, improved \code{PromptInt},
\code{PromptDouble}, \code{PromptIntInRange}, \code{PromptDoubleInRange}, \code{Agree},
and assorted supporting functions.
The only changes to individual methods were to make
sure that the static methods are public.

Henceforth we will be using \code{UI} in place of \code{UIF}.  In fact all the places \code{UIF}
was used before could be replaced by \code{UI}:
It includes all the functionality of \code{UIF}.

You can look at the code all together in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/ui/ui.cs}{ui/ui.cs}.

There are even fancier ways of arranging for legal numeric input.
We have only been reading whole lines, but it is possible to read
individual characters with \code{Console.ReadKey},
without a newline being entered yet.  A much more extensive advanced
subject is the special regular expression language for
describing arbitrary patterns in strings using the \code{Regex} class.
Though we will not discuss the details, another slick replacement for UI
using these features is in the example class \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/uifnt/UIFNT.cs}{uifnt/UIFNT.cs}.

\index{algorithms!greatest common divisor}\index{Euclid's algorithm}\index{greatest common divisor algorithm}

\section{Greatest Common Divisor}
\label{gcdexamples:index-0}\label{gcdexamples::doc}\label{gcdexamples:gcd}\label{gcdexamples:greatest-common-divisor}

\subsection{Euclid's Algorithm}
\label{gcdexamples:euclid-s-algorithm}
The greatest common divisor of two non-zero integers is a great
example to illustrate the power of loops. Everyone learns about the
\emph{concept} of a greatest common divisor when faced with a fraction that
is not in \emph{reduced} form.

Consider the fraction \(\frac{2}{4}\), which is the same as
\(\frac{1}{2}\). The fraction \(\frac{2}{4}\)
can be reduced, because the
numerator and denominator both have greatest common factor of 2. That
is, \(\frac{2}{4} = \frac{1 \cdot 2}{2 \cdot 2}\). So the factor of 2 can
be canceled from both the numerator and the denominator.

Euclid (the mathematician from classic times and author of \emph{Elements})
is credited with having come up with a clever algorithm for how to
compute the greatest common divisor efficiently. It is written as
follows, where \(a \bmod b\) means \code{a \% b} in C\#.
\begin{gather}
\begin{split}gcd(a, b) = gcd(b, a \bmod b)\end{split}\notag\\\begin{split}gcd(a, 0) = a\end{split}\notag
\end{gather}
It is common in mathematics to list functions as one or more
\emph{cases}. The way you read this is as follows:
\begin{itemize}
\item {} 
In general, the greatest common divisor of \code{a} and \code{b} is the
same as computing the greatest common divisor of \code{b} and the
remainder of \code{a} divided by \code{b}.

\item {} 
In the case where \code{b} is zero, the result is \code{a}. This makes
sense because \code{a} divides itself and 0.

\end{itemize}

To gain some appreciation of how the definition \emph{always} allows you to
compute the greatest common divisor, it is worthwhile to try it out
for a couple of numbers where you \emph{know} the greatest common
divisor. For example, we already know that the greatest common divisor
of 10 and 15 is 5. Let's use Euclid's method to verify this:
\begin{itemize}
\item {} 
\(gcd(10, 15) = gcd(15, 10 \bmod 15) = gcd(15, 10)\)

\item {} 
\(gcd(15, 10) = gcd(10, 15 \bmod 10) = gcd(10, 5)\)

\item {} 
\(gcd(10, 5) = gcd(5, 10 \bmod 5) = gcd(5, 0)\)

\item {} 
\(gcd(5, 0) = 5\)

\end{itemize}

Notice that in the example above, the first number (10) was smaller than
the second (15), and the first transformation just swapped the numbers,
so the larger number was first.  Thereafter the first number is always
larger.


\subsection{GCD ``Brute Force'' Method}
\label{gcdexamples:gcd-brute-force-method}
Now that we've gotten the preliminaries out of the way and have a basic
mathematical explanation for how
to calculate the greatest common divisor,
we'll take a look at how to translate this into code using the
machinery of while loops that you've recently learned.

The way GCD is formulated above is, indeed, the most clever way to
calculate the greatest common divisor.
Yet the way we learn about the greatest common divisor in elementary
school (at least at first) is to
learn how to factor the numbers a and b, often in a brute force way.
So for example, when calculating the
greatest common divisor of 10 and 15, we can immediately see it,
because we know that both of these
numbers are divisible by 5 (e.g. 5 * 2 = 10 and 5 * 3 = 15).
So the greatest common divisor is 5.

But if we had something more tricky to do like 810 and 729,
we might have to think a bit more.

Before we learn to find the factors of numbers,
we will often just ``try'' numbers until we get the
greatest common divisor. This sort of trial process can take place in a loop,
where we start at 1 and end at min(a, b). Why the minimum?
We know that none of the values after the minimum can divide both a and b
(in integer division),
because no larger number can divide a smaller positive number. The smaller
number would be the (non-zero) remainder.

Now take a look at a basic version of GCD:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Return the greatest common divisor of positive numbers.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{GreatestCommonDivisor} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{b}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{n} \PYG{p}{=} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Min} \PYG{p}{(}\PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{gcd} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{,} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}

         \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{a} \PYG{p}{\PYGZpc{}} \PYG{n}{i} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{b} \PYG{p}{\PYGZpc{}} \PYG{n}{i} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{gcd} \PYG{p}{=} \PYG{n}{i}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
            \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{gcd}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

This code works as follows:
\begin{itemize}
\item {} 
We begin by finding \code{Math.Min(a, b)}.
This is how to compute the minimum of any two
values in C\#. Technically, we don't need to use the minimum of a and b,
but there is no
point in doing any more work than necessary.

\item {} 
We'll use the variable \code{i} as the loop index, starting at 1.

\item {} 
The variable \code{gcd} will hold the largest currently known common divisor.
We start with 1, which divides any integer, and we will
look for a higher value that also divides a and b.

\item {} 
The line \code{while (i \textless{}= n)} is used to indicate that we are
iterating the values of
\code{i} until the minimum of \code{a} and \code{b} (computed earlier) is reached.

\item {} 
The line \code{if (a \% i == 0 \&\& b \% i == 0)}
is used to check whether we have found a
new value that replaces our previous \emph{candidate} for the GCD.
A value can only be
a candidate for the GCD if it divides a and b without a remainder.
The modulus
operator \code{\%} is our way of determining whether there is a
remainder from the
division operation \code{a / i} or \code{b / i}.

\item {} 
The line \code{i++} is our way of going to the next value of \code{i}
to be tested as the new GCD.

\item {} 
When this loop terminates, the greatest common divisor has been found.

\end{itemize}

So this gives you a relatively straightforward way of calculating the
greatest common divisor. While simple, it is not necessarily the most
efficient way of determining the GCD. If you think about what is going on,
this loop could run a significant number of times.
For example, if you were calculating the GCD two very large numbers, say,
one billion (1,000,000,000) and two billion (2,000,000,000)
it is painfully evident that you would consider a large number of values
(a billion, in fact) before obtaining
the candidate GCD, which we know is 1,000,000,000.


\subsubsection{Brute-Force GCD Exercise}
\label{gcdexamples:brute-force-gcd-exercise}
The code above goes though all integers 2 through \code{min(a, b)}.  That is
not generally necessary when the GCD is greater than 1,
even with a brute-force mindset.   Write a
\code{g\_c\_d\_basic\_faster.cs} to do this with a slightly different
\code{GreatestCommonDivisor} function. \footnote{
The original brute-force gcd approach always goes through all the integers
between 1 and \code{min(a, b)}.  There is a way to stop the first time
the real gcd is reached.  How can you arrange that?
}


\subsection{GCD Subtraction Method}
\label{gcdexamples:gcd-subtraction-method}
The subtraction method (also attributable to Euclid) to compute the
Greatest Common Divisor works as follows:
\begin{itemize}
\item {} 
Based on the \emph{mathematical} definition in the previous section, the
greatest common divisor algorithm saves a step when we already have
\code{a} and \code{b} in the \emph{right order}.

\item {} 
The \emph{right order} means that \(a > b\). As we noted earlier, the
cleverness of the \emph{mathematical} definition is that \code{a} and \code{b}
are swapped as the first step to ensure that \(a > b\), after
which we can repeatedly divide to get the GCD.

\item {} 
Division, of course, is a form of repetitive subtraction, so the way
to divide by \code{b} is to repeatedly subtract it (from a) until \code{a}
is no longer greater than \code{b}.

\item {} 
The subtraction method basically makes no attempt to put \code{a} and
\code{b} in the right order. Instead, we just write similar loops to
allow for the possibility of either order.

\item {} 
A simple check must be performed to ensure that the approach of
repeated subtraction actually resulted in the GCD. This will happen
if \code{a} and \code{b} bump into one another, thereby meaning that we
have computed the GCD.

\end{itemize}

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{GreatestCommonDivisor} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{b}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{c}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{a} \PYG{p}{!}\PYG{p}{=} \PYG{n}{b}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{while} \PYG{p}{(}\PYG{n}{a} \PYG{p}{\PYGZgt{}} \PYG{n}{b}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{c} \PYG{p}{=} \PYG{n}{a} \PYG{p}{\PYGZhy{}} \PYG{n}{b}\PYG{p}{;}
               \PYG{n}{a} \PYG{p}{=} \PYG{n}{c}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
            \PYG{k}{while} \PYG{p}{(}\PYG{n}{b} \PYG{p}{\PYGZgt{}} \PYG{n}{a}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{c} \PYG{p}{=} \PYG{n}{b} \PYG{p}{\PYGZhy{}} \PYG{n}{a}\PYG{p}{;}
               \PYG{n}{b} \PYG{p}{=} \PYG{n}{c}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{a}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

A look at the source code more or less follows the above explanation.

Let's start by looking at the inner loop at line 5, \code{while (a \textgreater{}
b)}. In this loop, we are repeatedly subtracting \code{b} from \code{a},
which we know we can do, because \code{a} started out as being larger
than \code{b}.  At the end of loop \code{a} is reduced to either
\begin{enumerate}
\item {} 
\code{b}, in which case \code{b} exactly divided the earlier \code{a},
and \code{b} is the GCD, or

\item {} 
a number less than \code{b}, namely
\(a \bmod b\) (or in C\# terms \code{a \% b}), and the process continues....

\end{enumerate}

The loop on line 9 is similar to the loop in line 5. For the same
reasons as we already explained, \code{b} ends up equal to \code{a},
which is the GCD, or \code{b} ends up as
\(b \bmod a\).

As discussed above, if \code{a} and \code{b} end up as the same number,
that is the GCD.  On the other hand,
the first GCD algorithm example showed how remainders may need to be to
be calculated over and over.  The outer loop in this version keeps this up
until \code{a} and \code{b} are reduced to equal
values.  At this point the inner loops would make no further changes,
and the common value is the GCD.

As an exercise to the reader, you may want to consider adding some
\code{Console.WriteLine()} statements to print the values of \code{a} and
\code{b} within each loop, and after both loops have executed. It will
allow you to see in visual terms how this method does its work.

\index{greatest common divisor!iterative}

\subsection{GCD Remainder Loop}
\label{gcdexamples:id2}\label{gcdexamples:gcd-remainder-loop}\label{gcdexamples:index-1}
There are several ways to code the shorter Euclidean algorithm at the beginning of this
GCD section.  It is a repetitive pattern,
and a loop can be used.  There are two parameters, \code{a} and \code{b}, to the gcd,
and they can be successively changed, suggesting a loop.  What is the continuation
condition?  You stop when \code{b} is 0, so you continue while \code{b != 0}.
The parameters \code{a} and \code{b} need to be replaced by \code{b} and \code{a \% b}.
One extra variable needs to be introduced to make this double change work.  The simplest
is to introduce a variable \code{r} for the remainder.  Check and see for yourself that you
need an extra variable like \code{r}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return the greatest comon divisor of nonnegative numbers,}
\PYG{c+c1}{/// not both 0.}
\PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{GreatestCommonDivisor} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{b}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k}{while} \PYG{p}{(}\PYG{n}{b} \PYG{p}{!}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{n}{a} \PYG{p}{\PYGZpc{}} \PYG{n}{b}\PYG{p}{;}
      \PYG{n}{a} \PYG{p}{=} \PYG{n}{b}\PYG{p}{;}
      \PYG{n}{b} \PYG{p}{=} \PYG{n}{r}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{return} \PYG{n}{a}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

More verbose demonstration code,
that prints the progress each time through
loop is in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/g\_c\_d\_remainder\_loop/g\_c\_d\_remainder\_loop.cs}{g\_c\_d\_remainder\_loop/g\_c\_d\_remainder\_loop.cs}.

\index{recursion!greatest common divisor}\index{greatest common divisor!recursion}

\subsection{Preview: Recursive GCD}
\label{gcdexamples:gcd-recursive}\label{gcdexamples:preview-recursive-gcd}\label{gcdexamples:index-2}
The first statement of Euclid's algorithm said (in C\#) when

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{gcd}\PYG{p}{(}\PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{)} \PYG{p}{=} \PYG{n}{gcd}\PYG{p}{(}\PYG{n}{b}\PYG{p}{,} \PYG{n}{a} \PYG{p}{\PYGZpc{}} \PYG{n}{b}\PYG{p}{)}
\end{Verbatim}

It is saying the result of the function with one set of parameters is equal to
calling the function with another set of parameters.  If we put this into a
C\# function definition, it would mean the instructions for the function say
to \emph{call itself}.  This is a broadly useful technique called \emph{recursion},
where a function calls \emph{itself} inside its definition.
We don't expect you to master this
technique immediately but do feel that it is important you at least
\emph{hear} about it and see its tremendous power:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return the greatest comon divisor of nonnegative numbers,}
\PYG{c+c1}{/// not both 0.}
\PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{GreatestCommonDivisor} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{b}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{b} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}                               \PYG{c+c1}{// base}
      \PYG{k}{return} \PYG{n}{a}\PYG{p}{;}                                \PYG{c+c1}{//   case}
   \PYG{p}{\PYGZcb{}} \PYG{k}{else} \PYG{p}{\PYGZob{}}
      \PYG{k}{return} \PYG{n+nf}{GreatestCommonDivisor} \PYG{p}{(}\PYG{n}{b}\PYG{p}{,} \PYG{n}{a} \PYG{p}{\PYGZpc{}} \PYG{n}{b}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// recursion}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}
\begin{itemize}
\item {} 
Recalling our earlier definition, the case \(gcd(a, 0) = a\) is
handled directly by lines commented as ``base case''.

\item {} 
And the case \(gcd(a, b) = gcd(b, a \bmod b)\) is handled by
line with comment ``recursion'', with the function calling itself.

\end{itemize}

In \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/g\_c\_d\_euclid\_recursive/g\_c\_d\_euclid\_recursive.cs}{g\_c\_d\_euclid\_recursive/g\_c\_d\_euclid\_recursive.cs}
is a wordier demonstration version that prints to the screen
the progress at each recursive call.

The recursive version of the \code{gcd} function \emph{refers to itself}
by \emph{calling} itself.  Though this seems circular, you can see
from the examples that it works very well.  The important point is that
the calls to the same function are not completely the same:
\emph{Successive} calls have \emph{smaller} second numbers, and the second
number eventually reaches 0, and in that case
there is a direct final answer.  Hence the function is not really circular.

This recursive version is a much more direct translation of the original
mathematical algorithm than the looping version!

The general idea of recursion is for a
function to call itself with \emph{simpler} parameters, until a simple enough place
is reached, where the answer can be directly calculated.

\index{statement!do while}\index{do while}\index{while vs. do while}

\section{Do-While Loops}
\label{do-while:index-0}\label{do-while:do-while}\label{do-while::doc}\label{do-while:do-while-loops}
Suppose you want the user to enter three integers for sides of a
right triangle.  If they do not make a right triangle, say so
and make the user try again.

One way to look at the while statement rubric is:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
set data for condition
while (condition) \PYGZob{}
   accomplish something
   set data for condition
\PYGZcb{}
\end{Verbatim}

As we have pointed out before this involves setting data in two places.
With the triangle problem, three pieces for data need to be entered,
and the condition to test is fairly simple.   (In any case the condition
could be calculated in a function.)

A \code{do}-\code{while} loop will help here.  It tests the condition at the end of the
loop, so there is no need to gather data before the loop:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{,} \PYG{n}{c}\PYG{p}{;}
\PYG{k}{do} \PYG{p}{\PYGZob{}}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Think of integer sides for a right triangle.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{n}{a} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter integer leg: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{n}{b} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter another integer leg: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{n}{c} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter integer hypotenuse: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{k}{if} \PYG{p}{(}\PYG{n}{a}\PYG{p}{*}\PYG{n}{a} \PYG{p}{+} \PYG{n}{b}\PYG{p}{*}\PYG{n}{b} \PYG{p}{!}\PYG{p}{=} \PYG{n}{c}\PYG{p}{*}\PYG{n}{c}\PYG{p}{)} \PYG{p}{\PYGZob{}}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Not a right triangle: Try again!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}} \PYG{k}{while} \PYG{p}{(}\PYG{n}{a}\PYG{p}{*}\PYG{n}{a} \PYG{p}{+} \PYG{n}{b}\PYG{p}{*}\PYG{n}{b} \PYG{p}{!}\PYG{p}{=} \PYG{n}{c}\PYG{p}{*}\PYG{n}{c}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

The general form of a \code{do}-\code{while} statement is
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{do \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement(s)
\end{DUlineblock}
\item[] \code{\} while (} \emph{continuationCondition} \code{);}
\end{DUlineblock}
\end{quote}

Here the block of statement(s) is \emph{always} executed at least once, but it continues
to be executed in a loop only so long as the condition tested
after the loop body is true.

\begin{notice}{note}{Note:}
A \code{do}-\code{while} loop is the \emph{one} place where you \emph{do} want a semicolon
right after a condition, unlike the places mentioned in
{\hyperref[ifpitfalls:dangerous-semicolon]{\emph{Dangerous Semicolon}}}.  At least if you omit it here you
are likely to get a compiler error rather than a difficult logical
bug.
\end{notice}

A \code{do}-\code{while} loop, like the example above,
can accomplish exactly the same thing as the \code{while}
loop rubric at the beginning of this section.  It has the general form:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
do \PYGZob{}
   set data for condition
   if (condition) \PYGZob{}
       accomplish something
   \PYGZcb{}
\PYGZcb{} while (condition);
\end{Verbatim}

It only sets the data to be tested \emph{once}.
(The trade-off is that the condition is tested \emph{twice}.)

\index{exercise!loan table}\index{decimal!loan table exercise}

\subsection{Loan Table Exercise}
\label{do-while:id1}\label{do-while:index-1}\label{do-while:loan-table-exercise}
Loans are common with a specified interest rate and with a fixed periodic
payment.  Interest is charged at a fixed rate on the amount left in the loan
after the last periodic payment (or start of the loan for the first payment).

For example, if an initial \$100 loan is made with 10\% interest per pay
period, and a regular \$20 payment each pay period:
At the time of the first payment interest of \$100*.10 = \$10 is accrued,
so the total owed is \$110.  Right after the payment of \$20,
\$110 - \$20 = \$90 remains.  That \$90 gains interest of \$90*.10 = \$9 up to the
next payment, when \$90 + \$9 = \$99 is owed.  After the regular payment of
\$20, \$99 - \$20 = \$79 is left, and so on.  When a payment of at most \$20 brings
the amount owed to 0, the loan is done.

We can make a table showing
\begin{itemize}
\item {} 
Payment number (starting from 1)

\item {} 
The principal amount after the previous payment (or the beginning of the loan
for the first payment)

\item {} 
The interest on that principal up until the next periodic payment

\item {} 
The payment made as a result.

\end{itemize}

Continuing the example above, the whole table
would look like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Number Principal   Interest    Payment
     1    100.00      10.00      20.00
     2     90.00       9.00      20.00
     3     79.00       7.90      20.00
     4     66.90       6.69      20.00
     5     53.59       5.36      20.00
     6     38.95       3.90      20.00
     7     22.85       2.29      20.00
     8      5.14       0.51       5.65
\end{Verbatim}

In the final line, the principal plus interest equal the payment, finishing
off the loan.

Similarly, with a \$1000.00 starting loan, 5\% interest per pay period, and
\$196 payments due, we would get

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Number Principal   Interest    Payment
     1   1000.00      50.00     196.00
     2    854.00      42.70     196.00
     3    700.70      35.04     196.00
     4    539.74      26.99     196.00
     5    370.73      18.54     196.00
     6    193.27       9.66     196.00
     7      6.93       0.35       7.28
\end{Verbatim}

If a \$46 payment were specified, the principal would not decrease from the
initial amount, and the loan would never be paid off.

There are a couple of wrinkles here:  \code{double} values do not hold decimal
values exactly.  The \code{decimal} type does hold decimal numbers exactly
(and in an enormous range, see {\hyperref[data_types-and-conversions:numeric-type-limits]{\emph{Numeric Types and  Limits}}}) and
hence are beter for monetary calculations.  Decimal literals end with m, like
\code{34.56m} for \emph{exactly} 34.56.

Though decimals are exact, money only has two decimal places.  We make the
assumption that interest will always be calculated as current
principal*rate, rounded
to two decimal places:  \code{Math.Round(principal*rate, 2)}.

Write \code{loan\_calc.cs{}`}, completing \code{LoanTable} and write a
\code{Main} testing program:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Print a loan table, showing payment number, principal at the}
\PYG{c+c1}{/// beginning of the payment period, interest over the period, and}
\PYG{c+c1}{/// payment at the end of the period.}
\PYG{c+c1}{/// The principal is the initial amount of the loan.}
\PYG{c+c1}{/// The rate is fraction representing the rate of interest per PAYMENT.}
\PYG{c+c1}{/// The periodic regular payment is also specified.}
\PYG{c+c1}{/// If the payment is insufficient, merely print \PYGZdq{}payment too low\PYGZdq{}.}
\PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{LoanTable}\PYG{p}{(}\PYG{k+kt}{decimal} \PYG{n}{principal}\PYG{p}{,} \PYG{k+kt}{decimal} \PYG{n}{rate}\PYG{p}{,}
                             \PYG{k+kt}{decimal} \PYG{n}{payment}\PYG{p}{)}
\end{Verbatim}

Note that the \code{rate}, too, is a \code{decimal},
even though it does not represent money.
That is important, because arithmetic with a \code{decimal} and a \code{double} is
forbidden:  A \code{double} would have to be explicitly cast to a \code{decimal}.
Insisting on \code{decimal} parameter simplifies the function code.

This exercise is much more sophisticated than the {\hyperref[whileexamples:savings-exercise]{\emph{Savings Exercise}}},
so it is placed in this section, much later in the chapter.  Use what
ever form of loop makes the most sense to you.

\index{labs!string manipulations}

\section{Number Guessing Game Lab}
\label{lab-number-game:index-0}\label{lab-number-game::doc}\label{lab-number-game:number-guessing-game-lab}\label{lab-number-game:lab-number-game}
\textbf{Objectives}:
\begin{itemize}
\item {} 
Work with functions

\item {} 
Work with interactive while loops

\item {} 
Use decisions

\item {} 
Introduce random values

\end{itemize}

This lab is inspired by a famous children's game
known as the number-guessing game. We suppose two people are playing.

The rules are:
\begin{itemize}
\item {} 
Person A chooses a positive integer less than N and keeps it in his or
her head.

\item {} 
Person B makes repeated guesses to determine the number. Person A
must indicate whether the guess is higher or lower.

\item {} 
Person A must tell the truth.

\end{itemize}

So as an example:
\begin{itemize}
\item {} 
George and Andy play the game.

\item {} 
George chooses a positive number less than 100 (29) and puts it in his
head.

\item {} 
Andy guesses 50. George says ``Lower''. Andy now knows that
\(1 \leq number < 50\).

\item {} 
Andy guesses 25. George says ``Higher''. Andy now knows that
\(26 \leq number < 50\).

\item {} 
Andy guesses 30. George says ``Lower''. Andy now knows that the
\(26 \leq number < 30\).

\item {} 
Andy starts thinking that he is close to knowing the correct answer. He
decides to guess 29. Andy guesses the correct number. So George
says, ``Good job! You win.''

\end{itemize}

We are going to elaborate this game in small steps.  You might save
the intermediate versions under new names.

The computer code for the
game is going to be acting like Player A.


\subsection{Part 1: No Hints; Fixed Secret Number}
\label{lab-number-game:part-1-no-hints-fixed-secret-number}
You will want to use the UI class, so either copy ui.cs into your project, or
(for Xamarin Studio) create a new project in a solution
in which you already have added the ui library project, and add the ui project
as a \emph{reference} for the lab project.
Make sure your program has \code{namespace IntroCS;} to match the UI class.

You are going to play a game, and later may repeat it, so put the code
for playing the number game in a function called \code{Game}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Game}\PYG{p}{(}\PYG{p}{)}
\end{Verbatim}

For now your write a \code{Main} function to just call \code{Game()}.

In \code{Game}:
\begin{enumerate}
\item {} 
For the simplest versions, which help testing, have the
program assign a specific
secret number (like 29), and call it \code{secret}.
Admittedly, this is not much fun for the player the second time!

\item {} 
Prompt the player for a guess.
Use \code{UI.PromptInt}.
Every time the player guesses wrong,
print ``Wrong!''.  A later version will give clues.  Keep
prompting for another number until the player guesses correctly.
(Since you, the programmer, knows the secret number, this need not go
on forever.)

\item {} 
When the player guesses the right number, print ``Correct!  You win!''

\end{enumerate}

Sample play could look like:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] Guess the number: \textbf{55}
\item[] Wrong!
\item[] Guess the number: \textbf{12}
\item[] Wrong!
\item[] Guess the number:  \textbf{29}
\item[] Good job!  You win!
\end{DUlineblock}
\end{quote}

You could also make the game stop immediately,
(since you know the secret number):
\begin{quote}

\begin{DUlineblock}{0em}
\item[] Guess the number:  \textbf{29}
\item[] Good job!  You win!
\end{DUlineblock}
\end{quote}


\subsection{Part 2: Add Hints}
\label{lab-number-game:part-2-add-hints}
In \code{Game}:
Instead of just printing ``Wrong!'' when the player is incorrect,
print ``Lower!'' or ``Higher!''  as appropriate.  For example:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] Guess the number: \textbf{55}
\item[] Lower!
\item[] Guess the number: \textbf{12}
\item[] Higher!
\item[] Guess the number: \textbf{25}
\item[] Higher!
\item[] Guess the number:  \textbf{29}
\item[] Good job!  You win!
\end{DUlineblock}
\end{quote}


\subsection{Part 3:  Add a Random Secret Number}
\label{lab-number-game:part-3-add-a-random-secret-number}
In \code{Game}, make the following alterations and additions:
\begin{enumerate}
\item {} 
For now set an \code{int} variable \code{big} to 100.  We will make sure
the secret number is less than \code{big}.

\item {} 
Have the Game function print
``In this game you guess a positive number less than 100.''
For future use it is best if you have the printing statement
reference the variable \code{big}, rather than the literal \code{100}.

\end{enumerate}

\index{random number generator}\begin{enumerate}
\item {} 
Thus far the secret number was fixed in the program.  Now we are
going to let it vary, by having the game generate a \emph{random} number.
For your convenience, we are going to give you the C\#
code to compute the random number.  Assuming we want a secret number
so \(1 \leq secret < big\), we can use the code:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Random} \PYG{n}{r} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Random}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{k+kt}{int} \PYG{n}{secret} \PYG{p}{=} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{n}{big}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

In case you are wondering, we are creating a \emph{new object}
of the \emph{class} \code{Random} which serves as the
random number generator. We'll cover this in more detail when we
get to the {\hyperref[classes:classes]{\emph{Classes and Object-Oriented Programming}}} chapter. Here is some illustration using a \code{Random}
object in csharp.  Your answers will not be the same!

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{Random} \PYG{n}{r} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Random}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{5}\PYG{l+m}{5}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{3}\PYG{l+m}{1}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{7}\PYG{l+m}{9}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{2}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{4}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{3}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{3}
\end{Verbatim}

In general the minimum possible value of the number returned by \code{r.Next}
is the first parameter, and the value returned is always \emph{less} than
the second parameter, \emph{never equal}.

You can see that \code{r.Next()} is smart enough to give what appears to
be a randomly chosen number every time.

Example (where \code{secret} ended up as 68):
\begin{quote}

\begin{DUlineblock}{0em}
\item[] Guess a number less than 100!
\item[] Guess the number: \textbf{60}
\item[] Higher!
\item[] Guess the number: \textbf{72}
\item[] Lower!
\item[] Guess the number: \textbf{66}
\item[] Higher!
\item[] Guess the number: \textbf{68}
\item[] Good job!  You win!
\end{DUlineblock}
\end{quote}

For debugging purposes, you might want to have \code{secret}
be printed out right away.
(Eliminate that part when everything works!)

\end{enumerate}


\subsection{Part 4:  Let the Player Set the Range of Values}
\label{lab-number-game:part-4-let-the-player-set-the-range-of-values}
In \code{Game}:
Instead of declaring \code{big} and  automatically initializing it to 100,
make \code{big} be a parameter, so the heading looks like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Game}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{big}\PYG{p}{)}
\end{Verbatim}

In \code{Main}:
\begin{enumerate}
\item {} 
Prompt the player for the limit on the secret number.
An exchange might look like:
\begin{quote}

Enter a secret number bound: \textbf{10}
\end{quote}

\item {} 
Pass the value given by the player to the \code{Game} function
(so it will be \code{big} inside \code{Game}).

\end{enumerate}

Hence the program might start with:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] Enter a secret number bound: \textbf{10}
\item[] In this game you guess a number less than 10!
\item[] Guess the number: \textbf{5}
\item[] Higher!
\item[] Guess the number: \textbf{7}
\item[] Lower!
\item[] Guess the number: \textbf{6}
\item[] Good job!  You win!
\end{DUlineblock}
\end{quote}


\subsection{Part 5:  Count the Guesses}
\label{lab-number-game:part-5-count-the-guesses}
In \code{Game}: When the player finally wins, print the number of guesses
the player made.  For example, for the game sequence shown above,
the last line would become:
\begin{quote}

Good job!  You win on guess 3!
\end{quote}

You need to keep a count, adding 1 with each guess.


\subsection{Possible Extra Credit Improvements or Variations}
\label{lab-number-game:possible-extra-credit-improvements-or-variations}
Should you finish everything early, try the following:
\begin{enumerate}
\item {} 
\textbf{(20\% extra credit)}  In \code{Main}:

Use an outer \code{while} loop to allow the game to be played
repeatedly. Change the prompt for the bound in \code{Main} to:
\begin{quote}

Enter a secret number bound (or 0 to quit):
\end{quote}

Continue to play games until the player enters 0 for the bound.

\item {} 
\textbf{(40\% extra credit)}
In \code{Main} prompt users to see if they want to guess numbers or reverse roles and
choose
the secret number.  In the first case, just call the existing Game function.
In the second case you need a new function,
where the user is the one who knows the secret
number and the computer guesses numbers until the answer
is obtained. Write and use a new function

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{GameReversed}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{big}\PYG{p}{)}
\end{Verbatim}

Pass it the parameter \code{big}, still set in \code{Main}.
The new \code{GameReversed} will tell the user to put a number in
his/her head, and press return to continue.
(You can throw away the string entered - this is just to cause a pause.)
Then the computer guesses.
For simplicity let the human enter ``L'' for lower, ``H'' for higher, and
``E'' for equal (when the computer wins).
As you saw in the initial example with George and Andy,
each hint reduces the range of the possible secret numbers.
Have the computer guess a \emph{random} number in the \emph{exact} range that
remains possible.

To do this you must note the asymmetry of the parameters for the method
\code{Next}:  suppose \code{n = r.Next(low, higher)}, then
\begin{quote}

\(low \leq number < higher\)
\end{quote}

The first parameter \emph{may} be returned, but second
parameter is \emph{never} returned.

You will need two variables \code{low} and \code{higher} that keep
bracketing the allowed range.  The simplest thing is to set them so they
will be the parameters for the following call to \code{Next}.

That would mean initially \code{low}
is 1 and \code{higher} is equal to \code{big}.
With each hint you adjust one or the other of \code{low} and \code{higher} so they
get closer together.
The game ends after the human enters ``E''.

Have the computer complain that the human is cheating (and stop the game)
if the computer
guesses the only possible value, and the human does \emph{not} respond with ``E''.

\end{enumerate}


\section{Chapter Review Questions}
\label{reviewwhile:chapter-review-questions}\label{reviewwhile::doc}\begin{enumerate}
\item {} 
While loops are a very important part of your programming tools.
Put in your own words:  when should you think to use a while loop?

\item {} 
Loops are also among the hardest things for many students --
with lots of things to think about.
There is a sequence of general process questions that you can ask yourself
to help you organize your work.  What are they in your words?
Do you know them well, or have them written down in a place you
can easily jump to?

\item {} 
Compare do-while and while loops:
How do you think about which one to use?

\item {} 
In an interactive while loop you need to continuously get data
from the user.  Where do you generally put the code to get more data?

\item {} 
In general, what causes an infinite \code{while} loop?

\item {} 
What is wrong with this statement:  When the condition in a \code{while} loop
heading becomes false, the loop statement immediately terminates.

\item {} 
A \code{while} loop will terminate when the program evaluates the
condition in its heading and the value becomes false.
What is the important difference in this statement from the previous
incorrect statement?

\item {} 
When does a program evaluate the condition in a \code{while} loop heading?
(There are two situations.)

\item {} 
A \code{while} loop is generally terminated when the program evaluates the
condition in its heading and it becomes false.
How else can a program exit from a \code{while} loop?

\item {} 
We generally construct a loop so its body is a compound statement,
composed of a sequence of statements inside.  If this body is a sequence of
simple statements, does it make sense for
one of them to be a return statement?

\item {} 
When inside a loop,
a return statement should generally only appear as a \emph{sub-statement}
of what kind of statement?

\item {} 
Which of these conditions is safer in general, with \emph{arbitrary}
\code{string} \code{s} and
\code{int} \code{i}?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{!}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}\PYGZsh{}\PYGZsq{}} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{i} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{0} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}

\PYG{n}{i} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{0} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{!}\PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}\PYGZsh{}\PYGZsq{}}
\end{Verbatim}

\item {} 
What is printed?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{//          012345678901234567890}
\PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}Is coding cool?  Yes!\PYGZdq{}}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Trim}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{k+kt}{string} \PYG{n}{t} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Substring}\PYG{p}{(}\PYG{l+m}{9}\PYG{p}{,} \PYG{l+m}{8}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{t}\PYG{p}{.}\PYG{n}{Replace}\PYG{p}{(}\PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}/\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{t}\PYG{p}{.}\PYG{n}{Trim}\PYG{p}{(}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Replace}\PYG{p}{(}\PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}/\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{StartsWith}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}is\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{ToLower}\PYG{p}{(}\PYG{p}{)}\PYG{p}{.}\PYG{n}{StartsWith}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}is\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}co\PYGZdq{}}\PYG{p}{)}\PYG{p}{,} \PYG{n}{j} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}co\PYGZdq{}}\PYG{p}{,} \PYG{n}{i}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{,}
    \PYG{n}{k} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}co\PYGZdq{}}\PYG{p}{,} \PYG{n}{j}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{i} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}} \PYG{p}{+} \PYG{n}{j} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}} \PYG{p}{+} \PYG{n}{k}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\end{enumerate}

\index{loop!foreach}\index{foreach}

\chapter{Foreach Loops}
\label{foreach:foreach-loops}\label{foreach:index-0}\label{foreach::doc}\label{foreach:foreach}

\section{\texttt{foreach} Syntax}
\label{foreachintro:foreach-syntax}\label{foreachintro::doc}\label{foreachintro:id1}
\index{statement!foreach}\index{foreach!syntax}
These sections on \code{foreach} loops and the later {\hyperref[for:for-loops]{\emph{For Loops}}}
introduce new looping statements.
Neither is absolutely necessary:
You could do all the same things with \code{while} loops,
but there are many situations where \code{foreach} loops and \code{for} loops
are more convenient and easier to read.

A \code{foreach} statement
only works with an object that holds a sequence or collection.
We will see many more kinds of sequences later.  For now we can illustrate
with a string, which is a sequence of characters.

We have already processed strings a character at a time, with \code{while} loops.
We took advantage of the fact that strings could be indexed.  Our \code{while}
loops directly controlled the sequence of indices. Then we could
look up the character at each index of a given string \code{s}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
\PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{use} \PYG{k}{value} \PYG{n}{of} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
   \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Examples have been in {\hyperref[while-with-sequence:while-sequence]{\emph{While-Statements with Sequences}}}, like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{// Print the characters of s, one per line.}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{OneCharPerLine}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

In this example we really only care about the characters, not the indices.
Managing the indices is just a way to get at the
underlying sequence of characters.

A conceptually simpler view is just:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{n}{each} \PYG{n}{character} \PYG{k}{in} \PYG{n}{s}
    \PYG{n}{use} \PYG{n}{the} \PYG{k}{value} \PYG{n}{of} \PYG{n}{the} \PYG{n}{character}
\end{Verbatim}

To \emph{use} ``the character'' in C\#, we must be able to refer to it.
We might name the current character \code{ch}.
The following is a variant of \code{OneCharPerLine} with a \code{foreach}
loop:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{OneCharPerLine}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{char} \PYG{n}{ch} \PYG{k}{in} \PYG{n}{s}\PYG{p}{)} \PYG{p}{\PYGZob{}}
       \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{ch}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

That is all you need! The \code{foreach} heading feeds us one
character from \code{s} each time through, using the name \code{ch}
to refer to it.
Of course any new variable name must be declared in C\#, so \code{ch}
is preceded in the heading by its type, \code{char}.
Then we can use \code{ch} inside the body of the loop.
Advancing to the next element in the sequence is automatic in the next
time through the loop.  No \code{i++} to remember;
no possibility of an infinite loop!

The general syntax of a \code{foreach} loop is
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{foreach (} \textbf{type itemName} \code{in} \emph{sequence} \code{) \{}
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement(s) using \textbf{itemName}
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

Here is a version of IsDigits:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{n}{Boolean} \PYG{n+nf}{IsDigits}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{char} \PYG{n}{ch} \PYG{k}{in} \PYG{n}{s}\PYG{p}{)} \PYG{p}{\PYGZob{}}
       \PYG{k}{if} \PYG{p}{(}\PYG{n}{ch} \PYG{p}{\PYGZlt{}} \PYG{l+s+sc}{\PYGZsq{}0\PYGZsq{}} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{ch} \PYG{p}{\PYGZgt{}} \PYG{l+s+sc}{\PYGZsq{}9\PYGZsq{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
          \PYG{k}{return} \PYG{k}{false}\PYG{p}{;}
       \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{return} \PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

See the advantages of \code{foreach} in these examples:
\begin{itemize}
\item {} 
They are more concise than the indexing versions.

\item {} 
They keep the emphasis on the characters, not the secondary indices.

\item {} 
The \code{foreach} heading emphasizes that a particular sequence is being
processed.

\end{itemize}

\begin{notice}{warning}{Warning:}
\emph{If} you have explicit need to refer to the indices of the items in the sequence,
then a \code{foreach} statement does not work.
\end{notice}

Of course you can refer to the indices of items in  sequence with a flexible
\code{while} loop, or see {\hyperref[for:for-loops]{\emph{For Loops}}}, coming soon....


\section{\texttt{foreach} Examples}
\label{foreachexamples::doc}\label{foreachexamples:foreach-examples}
\index{char!underlying numeric code}\phantomsection\label{foreachexamples:codeofstringchar}
In {\hyperref[while-with-sequence:isdigits]{\emph{IsDigits}}} we use the underlying int Unicode value
of the characters in comparisons.
When printing, you cannot see this code directly,
since the \code{char} type prints as \emph{characters}!
To see the underlying code value for a character, ch,
it can be cast to an int:  \code{(int)ch}

We can easily write a loop to print the unicode value of each character in a
string, \code{s}.  We do not need indices here, so a \code{foreach} loop is
appropriate:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{char} \PYG{n}{ch} \PYG{k}{in} \PYG{n}{s}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Unicode for \PYGZob{}0\PYGZcb{} is \PYGZob{}1\PYGZcb{}.\PYGZdq{}}\PYG{p}{,} \PYG{n}{ch}\PYG{p}{,} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{)}\PYG{n}{ch}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Try this in csharp.

We will have many more examples after we introduce more kinds of sequences.


\section{Chapter Review Questions}
\label{reviewforeach:chapter-review-questions}\label{reviewforeach::doc}\begin{enumerate}
\item {} 
Describe in general when a \code{foreach} loop is going to be easier to use
than a \code{while} loop.

\item {} 
Even if you want to process every element of a sequence, what would keep
you from using a \code{foreach} loop?

\end{enumerate}

\index{loop!for}\index{for}

\chapter{For Loops}
\label{for:index-0}\label{for::doc}\label{for:for-loops}\label{for:id1}
\index{statement!for}

\section{For-Statement Syntax}
\label{forstatements:index-0}\label{forstatements::doc}\label{forstatements:for-statement-syntax}
We now introduce the last kind of loop syntax: \code{for} loops.

A \code{for} loop is an example of \emph{syntactic sugar}:  syntax that can simplify
things for the programmer, but can be immediately translated into an
equivalent syntax by the compiler.  For example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{n}{i} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{sum} \PYG{p}{=} \PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

is exactly equivalent to this code similar to part of
{\hyperref[whilestatements:sumton]{\emph{SumToN}}}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{i}\PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}
\PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{sum} \PYG{p}{=} \PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}\PYG{p}{;}
   \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

More generally:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{for (} \emph{initialization} \code{;} \emph{condition} ; \emph{update} \code{)} \{
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement(s)
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

translates to
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \emph{initialization} \code{;}
\item[] \code{while (} \emph{condition} \code{)} \{
\item[]
\begin{DUlineblock}{\DUlineblockindent}
\item[] statement(s)
\item[] \emph{update} \code{;}
\end{DUlineblock}
\item[] \code{\}}
\end{DUlineblock}
\end{quote}

In the example above, \emph{initialization} is \code{i=2}, \emph{condition} is \code{i \textless{}= n},
and \emph{update} is \code{i++}.

Why bother with this rearrangement?  It is a matter of taste,
but the heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{n}{i} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
\end{Verbatim}

puts all the information about the variable controlling the loop
into one place at the top, which may help quickly visualize the overall
sequence in the loop.  If you use this format, and get used to the
three parts you are less likely to forget the \code{i++}
than when it comes tacked on to the end of a while loop body, after all
the specific things you were trying to accomplish.

Although the \code{for} loop syntax is very general,
a strongly recommended convention
is to only use a \code{for} statement when all the control of variables
determining loop repetition are in the heading.

For example if a \code{for}
loop uses \code{i} in the heading, \code{i} can have a value assigned or
reassigned in the heading, but should \emph{not} have its value modified
anywhere inside the loop body.
If you want more complicated behavior, use a \code{while} loop.

A \code{for} loop can also include variable declaration in the initialization,
as in:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{sum} \PYG{p}{=} \PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This is close, but not quite equivalent to:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}
\PYG{k}{while} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{sum} \PYG{p}{=} \PYG{n}{sum} \PYG{p}{+} \PYG{n}{i}\PYG{p}{;}
   \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Variables declared in a \code{for} loop heading are local to the
\code{for} loop heading and body.  The variable \code{i} declared before
the \code{while} statement above is still defined after the \code{while} loop.

The two semicolons are always needed in the \code{for} heading, but any of the
parts they normally separate may be omitted.
If the condition part is omitted, the condition is
interpreted as always true, leading to an infinite loop, that can only
terminate due to a \code{return} or {\hyperref[forstatements:break-continue]{\emph{break statement}}} in the body.

\index{execution sequence!for loop}
Note the different parts of the heading used at different times (consistent
with the positions in the corresponding while loop):
\begin{itemize}
\item {} 
When starting the whole statement, the initialization is done, and then
the test.

\item {} 
After finishing the body and returning to the heading, the update operations
are done, followed by the test.

\end{itemize}

\textbf{Other variations}

As in a regular local variable declaration,
there may be several variables of the
same type initialized at the beginning of a \code{for} loop heading,
separated by commas.  Also, at the end of the \code{for} loop heading, the
update portion may include more than one expression, separated by commas.
For example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{,} \PYG{n}{j} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{j}\PYG{p}{;} \PYG{n}{i} \PYG{p}{=} \PYG{n}{i}\PYG{p}{+}\PYG{l+m}{2}\PYG{p}{,} \PYG{n}{j}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{i}\PYG{p}{,} \PYG{n}{j}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Guess what this does, and then paste it into csharp to check.

The comma separated lists in a \code{for} statement heading
are mentioned here for completeness.  Later we will find a situation
where this is actually useful.

\index{statement!break}\index{statement!continue}\index{break statement}\index{continue statement}

\subsection{Break and Continue}
\label{forstatements:break-continue}\label{forstatements:index-2}\label{forstatements:break-and-continue}
This section concerns special \emph{break} and \emph{continue} statements
that can \emph{only} occur inside a loop (any kind:
\code{while}, \code{for} or \code{foreach}).
The syntax is convenient in various circumstances, but not necessary.  You are free
to use it, but for this course it is an \emph{optional extra}:

You can already stop a loop in the middle with an \code{if} statement
that leads to a choice with a \code{return} statement.
Of course that forces you to completely leave the current function.  If you only want to
break out of the \emph{innermost current loop}, but \emph{not} out of the whole function, use
a break statement:
\begin{quote}

\code{break;}
\end{quote}

in place of return.  Execution continues after the end of the whole innermost
currently running loop statement.
The \code{break} and \code{continue} statements only
make practical sense inside of an \code{if} statement that is inside the loop.

Examples, assuming  \code{target} already has a string value and \code{a} is an array of
strings:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{bool} \PYG{n}{found} \PYG{p}{=} \PYG{k}{false}\PYG{p}{;}
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{a}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{a}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{n}{target}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{n}{found} \PYG{p}{=} \PYG{k}{true}\PYG{p}{;}
      \PYG{k}{break}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{found}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Target found at index \PYGZdq{}} \PYG{p}{+} \PYG{n}{i}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}} \PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Target not found\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

When an element is reached that matches \code{target},
execution goes on \emph{past the loop} with \code{if (found)} ....

An alternate implementation with a compound condition in the heading and no \code{break} is:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{bool} \PYG{n}{found} \PYG{p}{=} \PYG{k}{false}\PYG{p}{;}
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{a}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{p}{!}\PYG{n}{found}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{a}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{n}{target}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{n}{found} \PYG{p}{=} \PYG{k}{true}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{found}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Target found at index \PYGZdq{}} \PYG{p}{+} \PYG{n}{i}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}} \PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Target not found\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

With a \code{foreach} loop, which has no explicit continuation condition,
the \code{break} would be more clearly useful.
Here is a variant if you do not care about the specific location of the target:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{bool} \PYG{n}{found} \PYG{p}{=} \PYG{k}{false}\PYG{p}{;}
\PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s} \PYG{k}{in} \PYG{n}{a}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{s} \PYG{p}{=}\PYG{p}{=} \PYG{n}{target}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{n}{found} \PYG{p}{=} \PYG{k}{true}\PYG{p}{;}
      \PYG{k}{break}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{found}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Target found\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}} \PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Target not found\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Using \code{break} statements is a matter of taste.  There is some advantage in reading
and following a loop that has only one exit criteria,
which is easily visible in the heading.  On the other hand, in many situations,
using a break statement makes the code much less verbose, and hence easier to follow.
If you \emph{are} reading through the loop, it may be clearer to have an immediate action
where it is certain that the loop should terminate.

All the modifiers about \emph{innermost} loop are important
in a situation like the following:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{p}{.}\PYG{p}{.}\PYG{p}{.}\PYG{p}{.}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{for} \PYG{p}{(}\PYG{p}{.}\PYG{p}{.}\PYG{p}{.}\PYG{p}{.}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
      \PYG{k}{if} \PYG{p}{(}\PYG{p}{.}\PYG{p}{.}\PYG{p}{.}\PYG{p}{)} \PYG{p}{\PYGZob{}}
        \PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
        \PYG{k}{break}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
      \PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The break statement is in the inner loop.  If it is reached, the inner loop ends,
but the inner loop is just a single statement inside the outer loop,
and the outer loop continues.
If the outer loop continuation condition remains true,
the inner loop will be executed again,
and the break may or may not be reached that time, so the inner loop may or may
not terminate normally....

For completeness we mention the much less used \code{continue} statement:
\begin{quote}

\code{continue;}
\end{quote}

It does not break out of the whole loop:
It just
skips the rest of the \emph{body} of the innermost current loop, \emph{this time} through the loop.
In the simplest situations a \code{continue} statement just avoids an extra \code{else} clause.
It can considerable shorten code if the test is inside of complicated, deeply nested
\code{if} statements.


\section{Examples With \texttt{for} Statements}
\label{forexamples:examples-with-for-statements}\label{forexamples::doc}
Thus far all of our \code{for} loops have used a sequence of successive integers.
Suppose you want to print the first \code{n} multiples of \code{k},
like the first 5 multiples
of 3:  3, 6, 9, 12, 15.  This could be handled by generating
a sequence \code{i} = 1 through \code{n}, and multiply each \code{i} by \code{k}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{i}\PYG{p}{*}\PYG{n}{k}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Another approach is to note that the numbers you want to print advance
in a regular fashion, too, but with an increment 3 in the example above,
or k in general:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{n}{k}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{n}\PYG{p}{*}\PYG{n}{k}\PYG{p}{;} \PYG{n}{i} \PYG{p}{=} \PYG{n}{i}\PYG{p}{+}\PYG{n}{k}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{i}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{i} \PYG{p}{=} \PYG{n}{i} \PYG{p}{+} \PYG{n}{k}\PYG{p}{;}
\end{Verbatim}

is a common pattern, less common than incrementing by one,
but still very common.  C\# and many other languages allow a shorter version:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{i} \PYG{p}{+}\PYG{p}{=} \PYG{n}{k}\PYG{p}{;}
\end{Verbatim}

This means to increment the variable i by k.

\begin{notice}{warning}{Warning:}
Be careful: the \code{+=} must be in
that order, with no space between.  Unfortunately the reverse order:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{i} \PYG{p}{=}\PYG{p}{+} \PYG{n}{k}\PYG{p}{;}
\end{Verbatim}

is also legal, and just assigns the value of k to i.
\end{notice}

\index{operator!+= -= *= /= \%=}\index{+= operator}\index{-= operator}\index{*= operator}\index{/= operator}\index{\%= operator}
Most C\# binary operations have a similar variation.  For instance
if \emph{op} is \code{+}, \code{-}, \code{*}, \code{/} or \code{\%},
\begin{quote}

\textbf{variable} \emph{op}= \emph{expression}
\end{quote}

means the same as
\begin{quote}

\textbf{variable} = \textbf{variable} op \emph{expression}
\end{quote}

For example

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{x} \PYG{p}{*}\PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\end{Verbatim}

is the same as

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{x} \PYG{p}{=} \PYG{n}{x} \PYG{p}{*} \PYG{l+m}{5}\PYG{p}{;}
\end{Verbatim}

\index{format!field width and precision}\index{field width formatting}\index{precision!format}\index{table formatting}\index{example!power\_table.cs}\index{power\_table.cs example}\index{right justification}\index{justification!right}\index{\{ \}!format field width and precision}

\subsection{Tables}
\label{forexamples:tables}\label{forexamples:index-1}\label{forexamples:id1}
Reports commonly include tables, often with successive lines generated by
a consistent formula.  As a simple first
table, we can show the square, cube, and square root of numbers 1 through 10.
The Math class has a function Sqrt, so we take the square root with Math.Sqrt
function.  The pattern is consistent, so we can loop easily:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(} \PYG{k+kt}{int} \PYG{n}{n} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;} \PYG{n}{n} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{n}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} \PYGZob{}1\PYGZcb{} \PYGZob{}2\PYGZcb{} \PYGZob{}3\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{n}\PYG{p}{,} \PYG{n}{n}\PYG{p}{*}\PYG{n}{n}\PYG{p}{,} \PYG{n}{n}\PYG{p}{*}\PYG{n}{n}\PYG{p}{*}\PYG{n}{n}\PYG{p}{,} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Sqrt}\PYG{p}{(}\PYG{n}{n}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The numbers will be there, but the output is not pretty:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
1 1 1 1
2 4 8 1.4142135623731
3 9 27 1.73205080756888
4 16 64 2
5 25 125 2.23606797749979
6 36 216 2.44948974278318
7 49 343 2.64575131106459
8 64 512 2.82842712474619
9 81 729 3
10 100 1000 3.16227766016838
\end{Verbatim}

First we might not need all those digits in the square root approximations.
We can replace \code{\{3\}} by \code{\{3:F4\}} to just show 4 decimal places.

We can adjust the spacing to make nice
columns by using a further formatting option.  The longest entries are all
in the last row, where they take up, 2, 3, 4, and 6 columns (for 3.1623).
Change the format string:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(} \PYG{k+kt}{int} \PYG{n}{n} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;} \PYG{n}{n} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{n}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0,2\PYGZcb{} \PYGZob{}1,3\PYGZcb{} \PYGZob{}2,4\PYGZcb{} \PYGZob{}3,6:F4\PYGZcb{}\PYGZdq{}}\PYG{p}{,}
                       \PYG{n}{n}\PYG{p}{,} \PYG{n}{n}\PYG{p}{*}\PYG{n}{n}\PYG{p}{,} \PYG{n}{n}\PYG{p}{*}\PYG{n}{n}\PYG{p}{*}\PYG{n}{n}\PYG{p}{,} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Sqrt}\PYG{p}{(}\PYG{n}{n}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

and we generate the neater output:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 1   1    1 1.0000
 2   4    8 1.4142
 3   9   27 1.7321
 4  16   64 2.0000
 5  25  125 2.2361
 6  36  216 2.4495
 7  49  343 2.6458
 8  64  512 2.8284
 9  81  729 3.0000
10 100 1000 3.1623
\end{Verbatim}

We are using two new formatting forms:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{\{}index\code{,}fieldWidth\code{\}}  and
\item[] \code{\{}index\code{,}fieldWidth\code{:F}\#\code{\}}
\end{DUlineblock}
\end{quote}

where index, fieldWidth, and \# are replaces by specific literal integers.
The new part with the comma (not colon) and fieldWidth, sets the \emph{minimum}
number of columns used for the substituted string, padding with blanks as needed.

\begin{notice}{warning}{Warning:}
There is a \emph{special} language for the
characters between the braces in a format string.
The rules are different than in regular C\# code, where
comma and colon are symbols,
and the parser allows \emph{optional whitespace} around them.
This is \emph{not} the case inside the braces of a format string:
There cannot be a space after the colon or before the comma.
Some blanks are legal; some blanks lead to exceptions being thrown,
and other positions for blanks
just silently give the wrong format.

The safest approach for a programmer is just to have
\emph{no} blanks between the braces in a format string.
\end{notice}

\emph{If the string to be inserted is wider than the fieldWidth,}
then the \emph{whole} string is inserted, \emph{ignoring} the fieldWidth.  Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}stuff\PYGZdq{}}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}123456789\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0,9\PYGZcb{}\PYGZbs{}n\PYGZob{}0,7\PYGZcb{}\PYGZbs{}n\PYGZob{}0,5\PYGZcb{}\PYGZbs{}n\PYGZob{}0,3\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{s}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

generates:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
123456789
    stuff
  stuff
stuff
stuff
\end{Verbatim}

filling 9, 7, and then 5 columns, by padding with 4, 2, and 0 blanks.
\emph{The last line sticks out past the proposed 3-column fieldWidth.}

One more thing to add to our power table is a heading.  We might want:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
n   square    cube    root
\end{Verbatim}

To make the data line up with the heading titles,
we can expand the columns, with code in example
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/power\_table/power\_table.cs}{power\_table/power\_table.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0,2\PYGZcb{}\PYGZob{}1,7\PYGZcb{}\PYGZob{}2,5\PYGZcb{}\PYGZob{}3,7\PYGZcb{}\PYGZdq{}}\PYG{p}{,}
                        \PYG{l+s}{\PYGZdq{}n\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}square\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}cube\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}root\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{k}{for} \PYG{p}{(} \PYG{k+kt}{int} \PYG{n}{n} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;} \PYG{n}{n} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{n}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0,2\PYGZcb{}\PYGZob{}1,7\PYGZcb{}\PYGZob{}2,5\PYGZcb{}\PYGZob{}3,7:F4\PYGZcb{}\PYGZdq{}}\PYG{p}{,}
                           \PYG{n}{n}\PYG{p}{,} \PYG{n}{n}\PYG{p}{*}\PYG{n}{n}\PYG{p}{,} \PYG{n}{n}\PYG{p}{*}\PYG{n}{n}\PYG{p}{*}\PYG{n}{n}\PYG{p}{,} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Sqrt}\PYG{p}{(}\PYG{n}{n}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

generating:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 n  square    cube    root
 1       1       1  1.0000
 2       4       8  1.4142
 3       9      27  1.7321
 4      16      64  2.0000
 5      25     125  2.2361
 6      36     216  2.4495
 7      49     343  2.6458
 8      64     512  2.8284
 9      81     729  3.0000
10     100    1000  3.1623
\end{Verbatim}

Note how we make sure the columns are consistent in the heading and further rows:
We used a format string for the headings with the same field widths as
in the body of the table. A separate variation: We also reduced the length
of the format string by putting all the substitution expressions in braces
right beside each other, and generate the space between columns with a
larger field width.

\index{left justification}\index{format!left justification}\index{justification!left}\phantomsection\label{forexamples:left-justification}
\textbf{Left Justification:}  Though our examples have always right justified in
a field (padding on the left), for completeness we note this alternative:
A minus sign in front of the fieldWidth
places the result left justified (padded on the right).
For example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}stuff\PYGZdq{}}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}1234567890\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0,\PYGZhy{}9\PYGZcb{}\textbar{}\PYGZbs{}n\PYGZob{}0,\PYGZhy{}7\PYGZcb{}\textbar{}\PYGZbs{}n\PYGZob{}0,\PYGZhy{}5\PYGZcb{}\textbar{}\PYGZbs{}n\PYGZob{}0,\PYGZhy{}3\PYGZcb{}\textbar{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{s}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

prints:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
1234567890
stuff    \textbar{}
stuff  \textbar{}
stuff\textbar{}
stuff\textbar{}
\end{Verbatim}

where the `\textbar{}' appears after any blank padding in each line.

\index{ASCII example}\index{example!ASCII}

\subsection{ASCII Codes}
\label{forexamples:index-3}\label{forexamples:ascii}\label{forexamples:ascii-codes}
Here is a reverse lookup from the
{\hyperref[foreachexamples:codeofstringchar]{\emph{Numeric Code of String Characters}}}:
Find the characters for a list of numeric codes. Just as we can cast a
\code{char} to an \code{int}, we can cast an \code{int} 0-127 to a \code{char}.

The Unicode used
by C\# is an extension of the ASCII codes corresponding to the
characters on a US keyboard.  The codes were originally
used to drive printers,
and the first 32 codes are non-printable instructions to the printer.
Characters 32 - 126 yield the 95 characters on a standard US keyboard.

A loop to print each code followed by a space and the corresponding
printable character
would be:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{3}\PYG{l+m}{2}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{7}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0,3\PYGZcb{} \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{i}\PYG{p}{,} \PYG{p}{(}\PYG{k+kt}{char}\PYG{p}{)}\PYG{n}{i}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

To make all the character line up we added a field width 3 for the code column.

If you run  this in csharp,
the first line printed does not appear to have a character:  That is the
blank character.  All the other characters are visible.

Let us make a more concise table, putting 8 entries per line.
We can print successive parts using \code{Write} instead of \code{WriteLine},
but we still need to advance to the next line after every 8th
entry, for codes 39, 47, 55, ....
Since they are 8 apart, their remainder when divided by 8 is always
the same:
\begin{quote}

7 = 39 \% 8 = 47 \% 8 = 55 \% 8 = ....
\end{quote}

We can add a newline after each of these is printed.  This requires a test:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{3}\PYG{l+m}{2}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{7}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0,3\PYGZcb{} \PYGZob{}1\PYGZcb{}  \PYGZdq{}}\PYG{p}{,} \PYG{n}{i}\PYG{p}{,} \PYG{p}{(}\PYG{k+kt}{char}\PYG{p}{)}\PYG{n}{i}\PYG{p}{)}\PYG{p}{;}
   \PYG{k}{if} \PYG{p}{(}\PYG{n}{i} \PYG{p}{\PYGZpc{}} \PYG{l+m}{8} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{7}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Recall that \code{Console.WriteLine()}
with no parameters \emph{only} advances to the next line.

Paste that whole code at once into csharp to see the result.

The next csharp\textgreater{} prompt appears right after \code{126 \textasciitilde{}}.
There is no eighth entry on the last line, and hence no advance to the
next line.  A program printing this table should include an extra
\code{Console.WriteLine()} after the loop.

\index{example!mod\_mult\_table.cs}\index{mod\_mult\_table.cs example}\index{nested loop!table}

\subsection{Modular Multiplication Table}
\label{forexamples:index-4}\label{forexamples:modular-mult-table}\label{forexamples:modular-multiplication-table}
We have introduced the remainder operator \code{\%} and mentioned that the corresponding
mathematical term is ``mod''.  We can extend that to the idea of modular arithmetic
systems.  For example, if we only look at remainders mod 7, we can just consider
numbers 0, 1, 2, 3, 4, 5, and 6.  We can do multiplication and addition and take
remainders mod 7 to get answers in the same range.  For example 3 * 5 mod 7
is \code{(3 * 5) \% 7} in C\#, which is 1.  As we look more at this system, we will
observe and explain more properties.

The next example is to make a table of multiplication, mod 7, and later generalize.

Tables generally have row and column labels.  We can aim for something like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{p}{*} \PYG{p}{\textbar{}} \PYG{l+m}{0} \PYG{l+m}{1} \PYG{l+m}{2} \PYG{l+m}{3} \PYG{l+m}{4} \PYG{l+m}{5} \PYG{l+m}{6}
\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}
\PYG{l+m}{0} \PYG{p}{\textbar{}} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0}
\PYG{l+m}{1} \PYG{p}{\textbar{}} \PYG{l+m}{0} \PYG{l+m}{1} \PYG{l+m}{2} \PYG{l+m}{3} \PYG{l+m}{4} \PYG{l+m}{5} \PYG{l+m}{6}
\PYG{l+m}{2} \PYG{p}{\textbar{}} \PYG{l+m}{0} \PYG{l+m}{2} \PYG{l+m}{4} \PYG{l+m}{6} \PYG{l+m}{1} \PYG{l+m}{3} \PYG{l+m}{5}
\PYG{l+m}{3} \PYG{p}{\textbar{}} \PYG{l+m}{0} \PYG{l+m}{3} \PYG{l+m}{6} \PYG{l+m}{2} \PYG{l+m}{5} \PYG{l+m}{1} \PYG{l+m}{4}
\PYG{l+m}{4} \PYG{p}{\textbar{}} \PYG{l+m}{0} \PYG{l+m}{4} \PYG{l+m}{1} \PYG{l+m}{5} \PYG{l+m}{2} \PYG{l+m}{6} \PYG{l+m}{3}
\PYG{l+m}{5} \PYG{p}{\textbar{}} \PYG{l+m}{0} \PYG{l+m}{5} \PYG{l+m}{3} \PYG{l+m}{1} \PYG{l+m}{6} \PYG{l+m}{4} \PYG{l+m}{2}
\PYG{l+m}{6} \PYG{p}{\textbar{}} \PYG{l+m}{0} \PYG{l+m}{6} \PYG{l+m}{5} \PYG{l+m}{4} \PYG{l+m}{3} \PYG{l+m}{2} \PYG{l+m}{1}
\end{Verbatim}

The border labels make the table much more readable, but let us start simpler,
with just the modular multiplications:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0}
\PYG{l+m}{0} \PYG{l+m}{1} \PYG{l+m}{2} \PYG{l+m}{3} \PYG{l+m}{4} \PYG{l+m}{5} \PYG{l+m}{6}
\PYG{l+m}{0} \PYG{l+m}{2} \PYG{l+m}{4} \PYG{l+m}{6} \PYG{l+m}{1} \PYG{l+m}{3} \PYG{l+m}{5}
\PYG{l+m}{0} \PYG{l+m}{3} \PYG{l+m}{6} \PYG{l+m}{2} \PYG{l+m}{5} \PYG{l+m}{1} \PYG{l+m}{4}
\PYG{l+m}{0} \PYG{l+m}{4} \PYG{l+m}{1} \PYG{l+m}{5} \PYG{l+m}{2} \PYG{l+m}{6} \PYG{l+m}{3}
\PYG{l+m}{0} \PYG{l+m}{5} \PYG{l+m}{3} \PYG{l+m}{1} \PYG{l+m}{6} \PYG{l+m}{4} \PYG{l+m}{2}
\PYG{l+m}{0} \PYG{l+m}{6} \PYG{l+m}{5} \PYG{l+m}{4} \PYG{l+m}{3} \PYG{l+m}{2} \PYG{l+m}{1}
\end{Verbatim}

This is more complicated in some respects than our previous table, so start slow,
with some pseudocode.  We need a row for each number 0-6, and so a \code{for} loop
suggests itself:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{r} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{r}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{print} \PYG{n}{row}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Each individual row also involves a repeated pattern:
calculate for the next number.  We can name the second number c for column.  The
next revision replaces ``print row'' by a loop:  a \emph{nested} loop, inside the loop for
separate rows:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{r} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{r}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{c} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{c} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{c}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
       \PYG{n}{print} \PYG{n}{modular} \PYG{n}{multiple} \PYG{n}{on} \PYG{n}{same} \PYG{n}{line}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

and the modular multiplication is just regular multiplication followed by
taking the remainder mod 7, so you might come up with the C\# code:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{r} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{r}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{c} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{c} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{c}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
       \PYG{k+kt}{int} \PYG{n}{modProd} \PYG{p}{=} \PYG{p}{(}\PYG{n}{r}\PYG{p}{*}\PYG{n}{c}\PYG{p}{)} \PYG{p}{\PYGZpc{}} \PYG{l+m}{7}\PYG{p}{;}
       \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{modProd} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

You can test this in csharp, and see it is not quite right!
Chopped-off output starts:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{0} \PYG{l+m}{1} \PYG{l+m}{2} \PYG{l+m}{3} \PYG{l+m}{4} \PYG{l+m}{5} \PYG{l+m}{6} \PYG{l+m}{0} \PYG{l+m}{2} \PYG{l+m}{4} \PYG{l+m}{6} \PYG{l+m}{1} \PYG{l+m}{3} \PYG{l+m}{5} \PYG{l+m}{0} \PYG{l+m}{3} \PYG{l+m}{6} \PYG{l+m}{2} \PYG{l+m}{5} \PYG{l+m}{1} \PYG{l+m}{4} \PYG{l+m}{0.}\PYG{p}{.}\PYG{p}{.}
\end{Verbatim}

Though we want each entry in a row on the same line, we need to go down to the
next line at the end of each line!  Where do we put in the newline in the code?
A line is \emph{all} the modular products by r, \emph{followed} by \emph{one} newline.
Each modular product for a row is printed in the inner \code{for} loop.  We want to
advance \emph{after} that, so the newline must be inserted \emph{outside the inner loop}.
On the other hand we do want it done for \emph{each} row, so it must be
\emph{inside the outer loop}:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{r} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{r}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{c} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{c} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{c}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
       \PYG{k+kt}{int} \PYG{n}{modProd} \PYG{p}{=} \PYG{p}{(}\PYG{n}{r}\PYG{p}{*}\PYG{n}{c}\PYG{p}{)} \PYG{p}{\PYGZpc{}} \PYG{l+m}{7}\PYG{p}{;}
       \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{modProd} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

You can copy and test that code in csharp, and it works!

It is important to be able to play computer on nested loops and follow execution,
statement by statement.  Look more closely at the code above,
noting the added line numbers.
The basic pattern \emph{is} sequential:  \emph{Complete} one statement before going on to the next.
\emph{Inside} the execution of a looping statement, there are extra rules, for testing and
looping through the whole body.  Within a loop body, each \emph{complete}
statement is executed sequentially.

Most new students can get successfully to line 4:
\begin{quote}

\begin{tabulary}{\linewidth}{|L|L|L|L|L|}
\hline
\textsf{\relax 
line
} & \textsf{\relax 
r
} & \textsf{\relax 
c
} & \textsf{\relax 
modProd
} & \textsf{\relax 
comment
}\\
\hline
1
 & 
0
 & 
-
 & 
-
 & 
initialize outer loop
\\
\hline
2
 & 
0
 & 
0
 & 
-
 & 
initialize inner loop
\\
\hline
3
 & 
0
 & 
0
 & 
0
 & \\
\hline
4
 & 
0
 & 
0
 & 
0
 & 
Write 0
\\
\hline\end{tabulary}

\end{quote}

After reaching the bottom of the loop, where do you go?
You finish the \emph{innermost} enclosing statement.
You are in the inner loop, so the next line is the \emph{inner} loop heading
where you increment c and continue with the loop since 1 \textless{} 7.  This
inner loop continues until you reach the bottom of the inner loop,
line 4, with c = 6, and return to the heading, line 2, and the test fails,
finishing the inner row loop:
\begin{quote}

\begin{tabulary}{\linewidth}{|L|L|L|L|L|}
\hline
\textsf{\relax 
line
} & \textsf{\relax 
r
} & \textsf{\relax 
c
} & \textsf{\relax 
modProd
} & \textsf{\relax 
comment
}\\
\hline
1
 & 
0
 & 
-
 & 
-
 & 
initialize outer loop
\\
\hline
2
 & 
0
 & 
0
 & 
-
 & 
0 \textless{} 7, enter loop body
\\
\hline
3
 & 
0
 & 
0
 & 
0
 & 
(0*0)\%7
\\
\hline
4
 & 
0
 & 
0
 & 
0
 & 
Write 0
\\
\hline
2
 & 
0
 & 
1
 & 
-
 & 
c=0+1=1,  1 \textless{} 7: true
\\
\hline
3
 & 
0
 & 
1
 & 
0
 & 
(0*1)\%7
\\
\hline
4
 & 
0
 & 
1
 & 
0
 & 
Write 0
\\
\hline
2
 & 
0
 & 
2
 & 
-
 & 
c=1+1=2,  2 \textless{} 7: true
\\
\hline
...
 &  &  &  & 
... through c = 6
\\
\hline
4
 & 
0
 & 
6
 & 
0
 & 
Write 0
\\
\hline
2
 & 
0
 & 
7
 & 
-
 & 
c=+1=7,  7 \textless{} 7: false
\\
\hline\end{tabulary}

\end{quote}

At this point the inner loop statement, lines 2-4, has completed,
and you continue.  You go on to the next statement in the
same sequential chuck as the inner loop statement in lines 2-4:
That sequential chunk is the the outer loop body, lines 2-6.
The next statement is line 6, advancing printing to the next line.
That is the last statement of the outer loop, so you
return to the heading of the outer loop and modify its loop
variable r.  The two lines just described are:
\begin{quote}

\begin{tabulary}{\linewidth}{|L|L|L|L|L|}
\hline
\textsf{\relax 
line
} & \textsf{\relax 
r
} & \textsf{\relax 
c
} & \textsf{\relax 
modProd
} & \textsf{\relax 
comment
}\\
\hline
6
 & 
0
 & 
-
 & 
-
 & 
print a newline
\\
\hline
1
 & 
1
 & 
-
 & 
-
 & 
r=s0+1=1, 1 \textless{} 7 enter outer loop
\\
\hline\end{tabulary}

\end{quote}

Then you go all the way through the inner loop again,
for all columns, with c going from 0 through 6, and exit at c=7,
finish the body of the outer loop by advancing to a new print line,
and return to the outer loop heading, setting r = 2..., until
all rows are completed.

The common error here is to forget what loop is the innermost one
that you are working on, and exit that loop before is is totally finished:
It finishes when the test of the condition controlling the loop becomes false.

Look back one more time and make sure the code for this \emph{simpler} table makes
sense before we continue to the one with labels....

The fancier table has a couple of extra rows at the top.  These two rows
are unlike the remaining rows in the body of the table, so they need special code.

If we go back to our pseudocode we could add to it:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{print} \PYG{n}{heading} \PYG{n}{row}
\PYG{n}{print} \PYG{n}{dash}\PYG{p}{\PYGZhy{}}\PYG{n}{row}
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{r} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{r}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{print} \PYG{n}{body} \PYG{n}{row}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

First analyze the heading row:  Some parts are repetitive and
some are not: Print \code{"* \textbar{}"} once, and then there is a repetitive pattern printing
0 - 6, which we can do with a simpler loop than in the table body:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}* \textbar{} \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{for} \PYG{p}{(} \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{i} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

The dashed line can be generated using \code{StringOfReps} from
{\hyperref[lab-nested-loops:lab-loops]{\emph{Lab: Loops}}}.  How many dashes?  A digit and a space for each of
seven columns and for a row header,
so we need
(7+1)*(1+1) characters, plus one for the `\textbar{}':  1 + (7+1)*(1+1).
Thinking ahead, we will leave that expression unsimplified.

We have done most of the work for the rows of the body of the table in the simpler
version.  We just
have a bit of printing for the initial row label.
Where does the code go?  It is repeated for each row, so it is inside
the outer loop, but it is just printed once per row, so it comes \emph{before} the
inner column loop.  The row label is r.
The whole code is in example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/mod7\_table/mod7\_table.cs}{mod7\_table/mod7\_table.cs} and below:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{//heading}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}* \textbar{} \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{k}{for} \PYG{p}{(} \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}  \PYG{c+c1}{//column headings}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{i} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}

      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{StringOfReps}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZhy{}\PYGZdq{}}\PYG{p}{,} \PYG{l+m}{1} \PYG{p}{+} \PYG{p}{(}\PYG{l+m}{7}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{*}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}

      \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{r} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{r}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}     \PYG{c+c1}{// table body}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{r} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \textbar{} \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}      \PYG{c+c1}{// row heading}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{c} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{c} \PYG{p}{\PYGZlt{}} \PYG{l+m}{7}\PYG{p}{;} \PYG{n}{c}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}  \PYG{c+c1}{// data columns}
            \PYG{k+kt}{int} \PYG{n}{modProd} \PYG{p}{=} \PYG{p}{(}\PYG{n}{r}\PYG{p}{*}\PYG{n}{c}\PYG{p}{)} \PYG{p}{\PYGZpc{}} \PYG{l+m}{7}\PYG{p}{;}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{modProd} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Besides the 0 row and 0 column in the mod 7 table,
note that in each line the products are a permutation of all the numbers 1-6.
That means it is
possible to define the \emph{inverse} of the multiplication operation, and mod 7 arithmetic
actually forms a mathematical \emph{field}.
Modular arithmetic (with much larger moduli!) is extremely important in
\emph{public key cryptography}, which
protects all your online financial transactions....
Knowing a lot more math is useful!
(But it is not required for this course.)

The inverse operation to multiplication for prime moduli is
easy to work out by brute force, going through the row of products.
A much more efficient
method is needed for cryptography:  That method involves
an elaboration of {\hyperref[gcdexamples:gcd]{\emph{Greatest Common Divisor}}}.

Finally, let us generalize this table to mod n.  With n up to about 25,
it is reasonable to print.
Most of the changes are just replacing 7 by n.
There is a further complication
with column width, since the numbers can be more than one digit long.
We can do formatting with a field width.
Unfortunately in C\# the field width must be a \emph{literal}
integer embedded in the format string,
but our number of digits in n is \emph{variable}.

Here is a good trick:  Construct the format string inside the program.
To get the format for a
number and an extra space
mod 7, we want format string ``\{0,1\} '', but for mod 11, we want ``\{0,2\} ''.
This 1 or 2 is the number of characters in n as a string,
given by

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{numberWidth} \PYG{p}{=} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}} \PYG{p}{+} \PYG{n}{n}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
\end{Verbatim}

We can create the format string
with a string concatenation expression:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{colFormat} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZob{}0,\PYGZdq{}} \PYG{p}{+} \PYG{n}{numberWidth} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}\PYGZcb{}\PYGZdq{}}\PYG{p}{;}
\end{Verbatim}

or use
\emph{another} format string and substitution.  This is an excuse to
illustrate including explicit braces (for the main format string).
Recall the explicit braces are doubled.  Check out this version:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{colFormat} \PYG{p}{=} \PYG{k+kt}{string}\PYG{p}{.}\PYG{n}{Format}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}\PYGZob{}0,\PYGZob{}0\PYGZcb{}\PYGZcb{}\PYGZcb{} \PYGZdq{}}\PYG{p}{,} \PYG{n}{numberWidth}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

which we use in the code for the whole function, below,
and in example program
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/mod\_mult\_table/mod\_mult\_table.cs}{mod\_mult\_table/mod\_mult\_table.cs}.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Print a table for modular multiplication mod n.}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{MultTable}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{numberWidth} \PYG{p}{=} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}} \PYG{p}{+} \PYG{n}{n}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
         \PYG{k+kt}{string} \PYG{n}{colFormat} \PYG{p}{=} \PYG{k+kt}{string}\PYG{p}{.}\PYG{n}{Format}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}\PYGZob{}0,\PYGZob{}0\PYGZcb{}\PYGZcb{}\PYGZcb{} \PYGZdq{}}\PYG{p}{,} \PYG{n}{numberWidth}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{string} \PYG{n}{rowHeaderFormat} \PYG{p}{=} \PYG{n}{colFormat} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}\textbar{} \PYGZdq{}}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{rowHeaderFormat}\PYG{p}{,}\PYG{l+s}{\PYGZdq{}*\PYGZdq{}}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// start main heading}
         \PYG{k}{for} \PYG{p}{(} \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{n}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{colFormat}\PYG{p}{,} \PYG{n}{i}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{StringOfReps}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZhy{}\PYGZdq{}}\PYG{p}{,}\PYG{p}{(}\PYG{n}{numberWidth}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{*}\PYG{p}{(}\PYG{n}{n}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{r} \PYG{p}{\PYGZlt{}} \PYG{n}{n}\PYG{p}{;} \PYG{n}{r}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{c+c1}{//rows of table body}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{rowHeaderFormat}\PYG{p}{,} \PYG{n}{r}\PYG{p}{)}\PYG{p}{;}
            \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{c} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{c} \PYG{p}{\PYGZlt{}} \PYG{n}{n}\PYG{p}{;} \PYG{n}{c}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{colFormat}\PYG{p}{,} \PYG{p}{(}\PYG{n}{r}\PYG{p}{*}\PYG{n}{c}\PYG{p}{)} \PYG{p}{\PYGZpc{}} \PYG{n}{n}\PYG{p}{)}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{string!reverse}\index{reverse string example!}

\subsection{Reversed String Returned}
\label{forexamples:reversed-string-returned}\label{forexamples:index-5}\label{forexamples:reverse-string-returned}
In {\hyperref[while-with-sequence:reversed-print-example]{\emph{String Backwards Exercise/Example}}} we discuss iterating through a string's
indices and characters to print the string reversed.  That might be useful,
but it logically the joining of two separate ideas:  reversing a string and
printing it.  We already know how to print a string as a step.  Now consider
the first part as its own function:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return s in reverse order.}
      \PYG{c+c1}{/// If s is \PYGZdq{}drab\PYGZdq{}, return \PYGZdq{}bard\PYGZdq{}.}
      \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{Reverse} \PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\end{Verbatim}

To go along with this chapter, we will use a \code{for} loop heading rather
a \code{while} loop as in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/reversed\_print/reversed\_print.cs}{reversed\_print/reversed\_print.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
\end{Verbatim}

A more significant difference is that in
the previous example we immediately printed,
individually, each letter that we wanted.  Now we need to create a single
string, with all the characters, before returning the result.

Let us think of the example in the documentation:  If we start with
\code{s} as \code{"drab"}, and we go through the letters one at a time in
reverse order, b a r d, we build up successively:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
b
ba
bar
bard
\end{Verbatim}

We need a loop with variables and operations.  The sequence
of reversed letters, \code{s{[}i{]}}, are the
last character on the end of each line above.

At least lines after the first are constructed from previous parts,
so, for instance,  \code{"bar"}  comes from combining the initial part \code{"ba"}
with the latest character \code{'r'} (\code{s{[}i{]}}).
We need a name for the initial part.
I used the name \code{rev}.
Combining with a string is done with the \code{+} operator.
Then when \code{rev} is \code{"ba"} and \code{s{[}i{]}} is \code{'r'}, the combination,
using the variable names, is

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{rev} \PYG{p}{+} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}
\end{Verbatim}

We want this in our loop, so we must be able to use
that expression \emph{each} time through the loop,
so \code{rev}  changes each time through the loop.  In the next iteration \code{rev}
is the \emph{result} of the previous expression.  The assignment statement
to give us the next version of \code{rev} can just be:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{rev} \PYG{p}{=} \PYG{n}{rev} \PYG{p}{+} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

That gives us the general rule.  Pay attention now to the beginning and end:
The end is simple:  The last value for \code{rev} is the complete reversed string,
so that is what we return.

How do we initialize \code{rev}?  You could imagine \code{rev} starting as \code{"b"},
but the the first character that we add is \code{'a'}, and we would not be going
through all the characters in our loop.  It is better to go all the way
back to the beginning:  If we use the general form with the first letter in the
reversed sequence,

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{rev} \PYG{p}{=} \PYG{n}{rev} \PYG{p}{+} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

then the result of the initial \code{rev} +  \code{'b'} should just be \code{"b"}.
So what would \code{rev} be?

Remember the empty string:  initialize \code{rev} to be \code{""}.

The result is:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return s in reverse order.}
      \PYG{c+c1}{/// If s is \PYGZdq{}drab\PYGZdq{}, return \PYGZdq{}bard\PYGZdq{}.}
      \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{Reverse} \PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{string} \PYG{n}{rev} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{rev} \PYG{p}{+}\PYG{p}{=} \PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{rev}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

We used our new operator \code{+=} to be more concise.

This function and a \code{Main} used to demonstrate it are in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/reversed\_string/reversed\_string.cs}{reversed\_string/reversed\_string.cs}.


\subsection{Exercises}
\label{forexamples:exercises}
\index{Random!static variable}
\index{Random!heads or tails exercise}\index{exercise!heads or tails}\index{heads or tails exercise}

\subsubsection{Head or Tails Exercise}
\label{forexamples:head-tails-exercise}\label{forexamples:head-or-tails-exercise}\label{forexamples:index-7}
Write a program \code{heads\_tails.cs}. It should include a function \code{Flip()},
that will just randomly print \code{Heads} or \code{Tails} \emph{once}.
Accomplish this by choosing 0 or 1 arbitrarily with a random
number generator.  More details follow.

Use a \code{Random} object, as in {\hyperref[lab-number-game:lab-number-game]{\emph{Number Guessing Game Lab}}}, \emph{except} this time it is
important \emph{not} to make the \code{Random} object be a local variable inside
the \code{Flip} function:  A new \code{Random} object in likely
initialized using the current time.  The \code{Flip} function has no interaction
with the user,
so it can be repeated very quickly, and new \code{Random} objects
may not register a new value
through several reruns of \code{Flip}.  This would give the same answer,
and be completely contrary to the idea of random results!

Hence it is generally a good idea to only create a single \code{Random} object
that stays in scope for the whole program.
One way to do that is to make it \emph{static}.  Place the declaration

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{n}{Random} \PYG{n}{r} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Random}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

inside your class but outside of any function, positioned like
the static constants discussed in {\hyperref[staticvariables:static-variables]{\emph{Static Variables}}}.

Then you can use \code{r} in any function in your class.
For \code{int} variables \code{low} and \code{higher}, with \code{low \textless{} higher}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{n} \PYG{p}{=} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next}\PYG{p}{(}\PYG{n}{low}\PYG{p}{,} \PYG{n}{higher}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

returns a (pseudo) random \code{int}, satisfying \code{low \textless{}= n \textless{} higher}.
If you select \code{low} and \code{higher} as 0 and 2,
so there are only two possible values for n,
then you can choose to print \code{Heads} or \code{Tails} with an
\code{if}-\code{else} statement based on the result.

\begin{notice}{warning}{Warning:}
We have discovered some problems with the \code{Next()} implementation
when running on Mono that sometimes results in random values not
being generated. This is likely a bug that will be fixed. If you
experience any problems with \code{Next()}, the following is for you!
\end{notice}

An alternative to generating random 0 and 1 values for heads and tails
is to generate random double-precision values. Using the same
variable, \code{r}, you can call \code{r.NextDouble()} to get a random value
between 0 and 1. You can consider any generated value \(n < 0.5\) to
be heads; \(n >= 0.5\) represents tails:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{double} \PYG{n}{n} \PYG{p}{=} \PYG{n}{r}\PYG{p}{.}\PYG{n}{NextDouble}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{if} \PYG{p}{(}\PYG{n}{n} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0.5}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{c+c1}{// heads}
\PYG{p}{\PYGZcb{}} \PYG{k}{else} \PYG{p}{\PYGZob{}}
   \PYG{c+c1}{// tails}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

In your \code{Main} method have a \code{for} loop calling  \code{Flip()}
10 times to test it, so you generate a random sequence of
10 heads and/or tails.  With these 10 rapid calls, it is important
that a new Random object is only created once.  The suggested static
variable declaration ensures that.

\index{exercise!GroupFlips}

\subsubsection{Group Flips Exercise}
\label{forexamples:group-flips-exercise}\label{forexamples:index-8}
Write a program \code{format\_flips.cs}. It should include the function \code{Flip()}
and the \code{static} \code{Random} declaration
from the last exercise.  Also include another function:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Print out the results from the total number of random flips of a coin.}
\PYG{c+c1}{/// Group them groupSize per line, each followed by a space.}
\PYG{c+c1}{/// The last line may contain fewer than groupSize flips}
\PYG{c+c1}{/// if total is not a multiple of groupSize.  The last line}
\PYG{c+c1}{/// should be followed by exactly one newline in all cases.}
\PYG{c+c1}{/// For example, GroupFlips(10, 4) *could* produce:}
\PYG{c+c1}{///   Heads Heads Tails Heads}
\PYG{c+c1}{///   Heads Tails Heads Tails}
\PYG{c+c1}{///   Tails Tails}
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{GroupFlips}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{total}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{groupSize}\PYG{p}{)}
\end{Verbatim}

Complete this function definition and test
with a variety of calls to \code{GroupFlips} in \code{Main}.
The output from the previous exercise would be produced by the call:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{GroupFlips}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\index{exercise!reverse string foreach}

\subsubsection{Reverse String \texttt{foreach} Exercise}
\label{forexamples:reverse-string-foreach-exercise}\label{forexamples:index-9}\label{forexamples:reverse-string-foreach}
We already have discussed {\hyperref[forexamples:reverse-string-returned]{\emph{Reversed String Returned}}}.
It used a \code{for} loop to go through the characters in
reverse order.  Write a version with the only loop heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{foreach}\PYG{p}{(}\PYG{k+kt}{char} \PYG{n}{ch} \PYG{k}{in} \PYG{n}{s}\PYG{p}{)} \PYG{p}{\PYGZob{}}
\end{Verbatim}

and no reference to indices in s.

\index{exercise!only letters}\index{only letters exercise!}

\subsubsection{Only Letters Exercise}
\label{forexamples:only-letters-exercise}\label{forexamples:index-10}\label{forexamples:only-letters-ex}
Write a program that defines and tests a function with
description and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return s with all non\PYGZhy{}letters removed.}
\PYG{c+c1}{/// For example OnlyLetters(\PYGZdq{}Hello, World!\PYGZdq{}) returns \PYGZdq{}HelloWorld\PYGZdq{}.}
\PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{OnlyLetters}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\end{Verbatim}

Assume the English alphabet.

\index{exercise!palindrome}\index{palindrome exercise!}

\subsubsection{Palindrome Exercise}
\label{forexamples:palindrome-ex}\label{forexamples:palindrome-exercise}\label{forexamples:index-11}
Write a program \code{palindrome.cs} that defines and tests a function with
description and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return true when s is a palindrome.}
\PYG{c+c1}{/// For example IsPalindrome(\PYGZdq{}A Toyota!\PYGZdq{}) returns true.}
\PYG{k}{static} \PYG{k+kt}{bool} \PYG{n+nf}{IsPalindrome}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\end{Verbatim}

A palindrome is a string that contains the same sequence of letters,
ignoring capitalization, forward and backward.  Non-letters are ignored.
Examples are ``Madam, I'm Adam.'' and ``Able was I `ere I saw Elba.''

\code{IsPalindrome} can be written very concisely by copying and using
functions from previous exercises.

\index{exercise!nested play computer}

\subsubsection{Nested Play Computer Exercise}
\label{forexamples:nested-play-computer-exercise}\label{forexamples:index-12}
Predict what these code fragments print.  Then check yourself in csharp:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{j} \PYG{p}{=} \PYG{n}{i}\PYG{p}{;} \PYG{n}{j} \PYG{p}{\PYGZlt{}} \PYG{l+m}{4}\PYG{p}{;} \PYG{n}{j}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{j}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}

\PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}abcdef\PYGZdq{}}\PYG{p}{;}
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;} \PYG{n}{i} \PYG{p}{+}\PYG{p}{=} \PYG{l+m}{2}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{k} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{k} \PYG{p}{\PYGZlt{}} \PYG{n}{i}\PYG{p}{;} \PYG{n}{k}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{s}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{exercise!power table}

\subsubsection{Power Table Exercise}
\label{forexamples:id2}\label{forexamples:index-13}\label{forexamples:power-table-exercise}\begin{enumerate}
\item {} 
Write a program \code{power\_table.cs} that completes and tests
the function with this heading.  Be sure your program tests
with several values for each parameter:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Print a table of powers of positive integers.}
\PYG{c+c1}{/// Assume 1 \PYGZlt{}= nMax \PYGZlt{}= 12, 1 \PYGZlt{}= powerMax \PYGZlt{}= 7.}
\PYG{c+c1}{/// Example: output of PowerTable(3, 4)}
\PYG{c+c1}{///       n\PYGZca{}1       n\PYGZca{}2      n\PYGZca{}3      n\PYGZca{}4}
\PYG{c+c1}{///         1         1        1        1}
\PYG{c+c1}{///         2         4        8       16}
\PYG{c+c1}{///         3         9       27       81}
\PYG{c+c1}{///}
\PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PowerTable}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{nMax}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{powerMax}\PYG{p}{)}
\end{Verbatim}

Make sure the table always ends up with right-justified columns.

\item {} 
Make the table have columns all the same width, but
make the width be as small as possible for the parameters
provided, leaving a minimal one space (but not less!) between columns
somewhere in the table. Consider heading widths, too.

\end{enumerate}

\index{labs!loops}

\section{Lab: Loops}
\label{lab-nested-loops:index-0}\label{lab-nested-loops::doc}\label{lab-nested-loops:lab-loops}\label{lab-nested-loops:id1}
Goals for this lab:
\begin{itemize}
\item {} 
Practice with loops.  You are encouraged to use a \code{for} loop where appropriate.

\item {} 
Use nested loops where appropriate.

\end{itemize}

Copy example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/loop\_lab\_stub/loop\_lab.cs}{loop\_lab\_stub/loop\_lab.cs} to a new project of yours,
and fill in function bodies for each part below:

\index{PrintReps}\begin{enumerate}
\item {} 
Complete

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Print n copies of s, end to end.}
      \PYG{c+c1}{/// For example PrintReps(\PYGZdq{}Ok\PYGZdq{}, 9) prints: OkOkOkOkOkOkOkOkOk}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintReps}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
\end{Verbatim}

Hint:  How would you do something like the example
\code{PrintReps("Ok", 9)} or with a higher count by hand?
Probably count under your breath as you write:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 1 2 3 4 5 6 7 8 9
OkOkOkOkOkOkOkOkOk
\end{Verbatim}

This is a counting loop.

\index{StringOfReps}
\item {} 
Complete

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a string containing n copies of s, end to end.}
      \PYG{c+c1}{/// For example StringOfReps(\PYGZdq{}Ok\PYGZdq{}, 9) returns: \PYGZdq{}OkOkOkOkOkOkOkOkOk\PYGZdq{}}
      \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{StringOfReps}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
\end{Verbatim}

Note the distinction from the previous part:  Here the function prints nothing.
Its work is \emph{returned} as a single string.  You have to build up the final
string.

\index{Factorial}
\item {} 
Complete \code{Factorial}, in a format much like SumToN in example
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sum\_to\_n\_test/sum\_to\_n\_test.cs}{sum\_to\_n\_test/sum\_to\_n\_test.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return n! (n factorial: 1*2*3 *...* n if n \PYGZgt{}=1; }
      \PYG{c+c1}{/// 0! is 1.).  For example Factorial(4) returns 1*2*3*4 = 24.}
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{Factorial}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
\end{Verbatim}

It is useful to think of the sequence of steps to calculate a
concrete example of a factorial, say 6!:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Start with 1
2 *1 = 2
3*2 = 6
4 * 6 = 24
5*24 = 120
6*120 = 720
\end{Verbatim}

\textbf{ALSO} find the largest value of \code{n} for which the function works.
(You might want to add a bit of code further testing Factorial,
to make this easier.)  Caution:  although a negative result from the
product of two positive numbers is clearly wrong, only half of the
allowed values are negative, so the first wrong answer could equally well
be positive.

\item {} 
Modify the function to return a \code{long}.
Then what is the largest value of \code{n} for which the function works?

\emph{Remember the values from this part and the previous part}
\emph{to tell the TA's checking out your work.}

\index{PrintRectangle}
\item {} 
Complete the method

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{// Print a filled rectange, where the filling is }
      \PYG{c+c1}{// the specified number of columns and rows of the character inChar,}
      \PYG{c+c1}{// surrounded by a border made of the character edgeChar.}
      \PYG{c+c1}{// For example printRectangle(3, 2, \PYGZsq{}i\PYGZsq{}, \PYGZsq{}e\PYGZsq{}) prints}
      \PYG{c+c1}{//    eeeee}
      \PYG{c+c1}{//    eiiie}
      \PYG{c+c1}{//    eiiie}
      \PYG{c+c1}{//    eeeee}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintRectangle}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{columns}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{rows}\PYG{p}{,} 
                                 \PYG{k+kt}{char} \PYG{n}{inChar}\PYG{p}{,} \PYG{k+kt}{char} \PYG{n}{edgeChar}\PYG{p}{)}
\end{Verbatim}

Here are further examples:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{PrintRectangle}\PYG{p}{(}\PYG{l+m}{5}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+s+sc}{\PYGZsq{} \PYGZsq{}}\PYG{p}{,} \PYG{l+s+sc}{\PYGZsq{}B\PYGZsq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{PrintRectangle}\PYG{p}{(}\PYG{l+m}{0}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+s+sc}{\PYGZsq{}\PYGZhy{}\PYGZsq{}}\PYG{p}{,} \PYG{l+s+sc}{\PYGZsq{}+\PYGZsq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

would print

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
BBBBBBB
B     B
BBBBBBB
++
++
++
++
\end{Verbatim}

Suggestion:  You are always encouraged to build up to a complicated solution
incrementally.
You might start by just creating the inner rectangle, without the border.

\item {} 
\textbf{40\% Extra Credit} Complete the method below.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Print the borders of the cells of a table. }
      \PYG{c+c1}{/// The borders divide the table into rows and columns.}
      \PYG{c+c1}{/// The blank space within a cell is width characters wide}
      \PYG{c+c1}{/// and continues down for height lines.}
      \PYG{c+c1}{/// The horizontal borders are dashes \PYGZsq{}\PYGZhy{}\PYGZsq{} and the vertical borders}
      \PYG{c+c1}{/// are vertical bars, \PYGZsq{}\textbar{}\PYGZsq{}, except that all intersections are \PYGZsq{}+\PYGZsq{}.}
      \PYG{c+c1}{/// For example PrintTableBorders(3, 2, 4, 1) prints}
      \PYG{c+c1}{///    +\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+}
      \PYG{c+c1}{///    \textbar{}    \textbar{}    \textbar{}    \textbar{}}
      \PYG{c+c1}{///    +\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+}
      \PYG{c+c1}{///    \textbar{}    \textbar{}    \textbar{}    \textbar{}}
      \PYG{c+c1}{///    +\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintTableBorders}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{columns}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{rows}\PYG{p}{,} 
                                    \PYG{k+kt}{int} \PYG{n}{width}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{height}\PYG{p}{)}
\end{Verbatim}

Here is further example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{PrintTableBorders}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{6}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

would print (with actual vertical bars)

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
+\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+
\textbar{}      \textbar{}      \textbar{}
\textbar{}      \textbar{}      \textbar{}
\textbar{}      \textbar{}      \textbar{}
+\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}\PYGZhy{}+
\end{Verbatim}

You can do this with lots of nested loops,
or much more simply you can use \code{StringOfReps}, possibly six times
in several assignment statements,
and print a single string.  Think of larger and larger building blocks.

The source of this book is plain text where some of the tables are laid out
in a format similar to the output of this function.  The Emacs editor
has a mode that maintains
a fancier related setup on the screen, on the fly,
as content is added inside the cells!

\end{enumerate}


\section{Chapter Review Questions}
\label{reviewfor:chapter-review-questions}\label{reviewfor::doc}\begin{enumerate}
\item {} 
When might you prefer a \code{for} loop in place of a \code{while} loop?
What do you gain?

\item {} 
When might you prefer a \code{while} loop or a \code{foreach} instead of
a \code{for} loop?

\item {} 
When you have nested \code{for} loops, and you reach the bottom of the \emph{body} of the
\emph{inner} loop, where does execution go next?

\item {} 
May you legally omit the initialization part of a \code{for} loop?

\item {} 
What happens when you omit the condition in a \code{for} loop?

\item {} 
In the heading of a \code{for} loop, how do you initialize or update
several variables?

\item {} 
Rewrite

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{num} \PYG{p}{/}\PYG{p}{=} \PYG{l+m}{2}\PYG{p}{;}
\end{Verbatim}

equivalently without the operand \code{/=}.

\item {} 
Rewrite

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{bigName} \PYG{p}{=} \PYG{n}{bigName} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{;}
\end{Verbatim}

with a statement that only includes \code{bigName} once.

\item {} 
Distinguish the effects of these two statements:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{x}\PYG{p}{\PYGZhy{}}\PYG{p}{=}\PYG{l+m}{2}\PYG{p}{;}

\PYG{n}{x}\PYG{p}{=}\PYG{p}{\PYGZhy{}}\PYG{l+m}{2}\PYG{p}{;}
\end{Verbatim}

\item {} 
What is printed?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}12345678\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{for}\PYG{p}{(} \PYG{k+kt}{int} \PYG{n}{p} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;} \PYG{n}{p} \PYG{p}{\PYGZlt{}} \PYG{l+m}{6}\PYG{p}{;} \PYG{n}{p}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{k+kt}{string} \PYG{n}{formatStr} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZob{}0:F\PYGZdq{}} \PYG{p}{+} \PYG{n}{p} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}\PYGZcb{}\PYGZdq{}}\PYG{p}{;}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{formatStr}\PYG{p}{,} \PYG{l+m}{1.2345678}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
What is printed?  (Just '',4'' has been inserted.)

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}12345678\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{for}\PYG{p}{(} \PYG{k+kt}{int} \PYG{n}{p} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;} \PYG{n}{p} \PYG{p}{\PYGZlt{}} \PYG{l+m}{6}\PYG{p}{;} \PYG{n}{p}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{k+kt}{string} \PYG{n}{formatStr} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZob{}0,4:F\PYGZdq{}} \PYG{p}{+} \PYG{n}{p} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}\PYGZcb{}\PYGZdq{}}\PYG{p}{;}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{formatStr}\PYG{p}{,} \PYG{l+m}{1.2345678}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
What is printed?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}123456\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{for}\PYG{p}{(} \PYG{k+kt}{int} \PYG{n}{w} \PYG{p}{=} \PYG{l+m}{6}\PYG{p}{;} \PYG{n}{w} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{p}{\PYGZhy{}}\PYG{l+m}{6}\PYG{p}{;} \PYG{n}{w} \PYG{p}{\PYGZhy{}}\PYG{p}{=} \PYG{l+m}{4}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{k+kt}{string} \PYG{n}{formatStr} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZob{}0,\PYGZdq{}} \PYG{p}{+} \PYG{n}{w} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}\PYGZcb{}\textbar{}\PYGZdq{}}\PYG{p}{;}
    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{formatStr}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}here\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\end{enumerate}

\index{file}

\chapter{Files, Paths, and Directories}
\label{files:files}\label{files:index-0}\label{files:files-paths-and-directories}\label{files::doc}
\index{file (StreamWriter)!stream abstraction}\index{stream}

\section{Files As Streams}
\label{fileabstraction:fileabstraction}\label{fileabstraction:index-0}\label{fileabstraction::doc}\label{fileabstraction:files-as-streams}
Thus far you have been able to save programs, but anything produced
during the execution of a program has been lost when the program
ends. Data has not \emph{persisted} past the end of execution. Just as
programs live on in files, you can generate and read data files in
C\# that persist after your program has finished running.

As far as C\# is concerned, a file is just a string (often very
large!) stored on your file system, that you can read or write,
gradually, line by line, or all together.

C\# has the abstraction of a \emph{stream},
as a sequence of characters to be processed sequentially.
A stream can either be written sequentially or read sequentially.
You have already read and written streams of
characters to the Console.  Most of the syntax that we use for files will be very similar,
using methods \code{ReadLine}, \code{WriteLine}, and \code{Write} in the same way you
used them for the \code{Console}.

Files can be handled very differently by different operating systems, but
C\# abstracts away the differences and provides stream interfaces between
a C\# program and files.

\index{file (StreamWriter)!write and close}\index{StreamWriter!WriteLine}\index{WriteLine!StreamWriter}\index{class!StreamWriter}\index{close file}

\section{Writing Files}
\label{filewrite:index-0}\label{filewrite:filewrite}\label{filewrite::doc}\label{filewrite:writing-files}
Try the following:
\begin{enumerate}
\item {} 
In Xamarin Studio build, \emph{not} run, the project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/first\_file}{first\_file}.  Build is
the first selection in the local popup menu for first\_file in the Solution pad.
Recall to get the local popup menu
\begin{itemize}
\item {} 
go to the Solution pad

\item {} 
right click on the project (Mac control-click)

\end{itemize}

\item {} 
Next open an operating system directory window for the project.
With Xamarin Studio open, a quick way to do that is to go to the same popup window,
and this time select ``Open Containing Folder''.

\item {} 
Besides the project files from the Solutions pad, in the directory window
you should also see a folder
\code{bin}.  Change to that folder and then to its sub-folder \code{Debug}.
This is where the build step put its result \code{first\_file.exe} and debug
information \code{first\_file.exe.mdb}.  You should see no other file.
Leave this window open.

\item {} 
Now, back in Xamarin Studio, run the project.  Depending on your operating system,
you may or may not see a Console Window pop up.  If you do see one, you
should not see any evidence of program results.  If you got a window, close it.

\item {} 
Look at the directory window again.  You should see a file \code{sample.txt}.
This is a file created by the program you ran.

\end{enumerate}

Here is the program:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{using} \PYG{n+nn}{System.IO}\PYG{p}{;}

\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{k}{class} \PYG{n+nc}{FirstFile}  \PYG{c+c1}{// basics of file writing}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{StreamWriter} \PYG{n}{writer} \PYG{p}{=} \PYG{k}{new} \PYG{n}{StreamWriter}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}sample.txt\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{writer}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}This program is writing\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{writer}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}our first file.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{writer}\PYG{p}{.}\PYG{n}{Close}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{. !part of namespace}
Look at the code.  Note the extra namespace being used at the top.  You will
always need to be using \code{System.IO} when working with files.  Here is a slightly
different use of a dot, \code{.}, to indicate a subsidiary namespace.

The first line of \code{Main} creates a \code{StreamWriter} object assigned to the
variable  \code{writer}.  A \code{StreamWriter}
links C\# to your
computer's file system for writing, not reading.
Files are objects, like a Random, and use the \code{new} syntax to create a new one.
The parameter in the constructor
gives the name of the file to connect to the program, \code{sample.txt}.

\begin{notice}{warning}{Warning:}
If the file already existed,  the old contents are
\emph{destroyed} silently by creating a \code{StreamWriter}.
\end{notice}

If you do not use
any operating system directory separators in the name (\code{'\textbackslash{}'} or \code{'/'},
depending on your operating system), then the file will lie in the
\emph{current directory}, discussed more shortly.  The Xamarin Studio default is for this
current directory to be this Debug directory.  This will be inconvenient
in many circumstances, and later in the chapter we will see how to minimize the
issue.

The second and third lines of \code{Main} write the specified strings to lines in the file.
Note that the \code{StreamWriter} object \code{writer}, not \code{Console},
comes before the dot and \code{WriteLine}.
This is yet another variation on the use of a dot, \code{.}:  between an object and
a function tied to this object.  In this situation the function tied to an object
is more specifically called a \emph{method}, in object-oriented terminology.  All the
uses of a dot (except for a numerical literal value) share a common idea, indicating
a named part or attribute of a larger thing.

The last line of \code{Main} is important for cleaning up. Until this line, this
C\# program controls the file, and nothing may be actually
written to the operating system file yet:  Since initiating a file operation
is thousands of times
slower than memory operations, C\# \emph{buffers} data, saving small
amounts and writing a larger chunk all at once.

\begin{notice}{warning}{Warning:}
The call to the \code{Close} method
is essential for C\# to make sure everything is really
written, and to relinquish control of the file for use by
other programs.
\end{notice}

It is a common bug
to write a program where you have the code to add all the data you
want to a file, but the program does not end up creating a file.
Usually this means you forgot to close the file!

As discussed above, Xamarin Studio places \code{sample.txt} in the
\code{Debug} sub-subfolder, a hard-to-guess place in the file system,
that is \emph{not} shown in the Solution pad, so do not look for it there!
As you should have checked above, you \emph{can} see it in an operating system file
window.  Do drill down to the Debug folder if you have not already;
open the \code{sample.txt} file with your favorite text processor.
It should contain just what was written!

If you were to run the program from the command line instead of from Xamarin Studio,
the file would appear in the current directory.

\index{StreamWriter!format string}\index{StreamWriter!Write}
Just as you can use a {\hyperref[data_writeline-substitution:format-strings]{\emph{String Format Operation}}} with
functions \code{Write} and \code{WriteLine} of the \code{Console} class,
you can also use a format string with the corresponding methods of a
\code{StreamWriter}, and embed fields by using braces in
the format string.

\index{file (StreamWriter)!read and close}\index{StreamReader!ReadLine}\index{close file}

\section{Reading Files}
\label{fileread:index-0}\label{fileread:fileread}\label{fileread:reading-files}\label{fileread::doc}
In Xamarin Studio, go to project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/print\_first\_file}{print\_first\_file}.
Right click on the project in the Solution pad, and select Open Containing Folder.
Drill down two folders through \code{bin} to \code{Debug}.
You should find a copy of the \code{sample.txt} that we stored there.  You can open it and
look at it if you like.

Run the example program
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/print\_first\_file/print\_first\_file.cs}{print\_first\_file/print\_first\_file.cs}, shown below:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{using} \PYG{n+nn}{System.IO}\PYG{p}{;}

\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{k}{class} \PYG{n+nc}{PrintFirstFile}  \PYG{c+c1}{// basics of reading file lines }
   \PYG{p}{\PYGZob{}}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}  
      \PYG{p}{\PYGZob{}}
         \PYG{n}{StreamReader} \PYG{n}{reader} \PYG{p}{=} \PYG{k}{new} \PYG{n}{StreamReader}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}sample.txt\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{string} \PYG{n}{line} \PYG{p}{=} \PYG{n}{reader}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}  \PYG{c+c1}{// first line}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{line}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{line} \PYG{p}{=} \PYG{n}{reader}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}         \PYG{c+c1}{// second line}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{line}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{reader}\PYG{p}{.}\PYG{n}{Close}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}                   
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Now you have read a file and used it in a program.

In the first line of \code{Main} the operating system file (\code{sample.txt}) is
associated again with a C\# variable name (\code{reader}),
this time for reading as a \code{StreamReader} object.
A \code{StreamReader} can only open an existing file, so
\code{sample.txt} must already exist.

Again we have parallel names to those used with \code{Console},
but in this case the \code{ReadLine} method returns the next line from the file.
Here the string from the file line is assigned to
the variable \code{line}. Each call the ReadLine reads the
next line of the file.

Using the \code{Close} method is
generally optional with files being read. There is nothing to lose
if a program ends without closing a file that was being read. \footnote{
If, for some reason, you want to reread this same file while the
same program is running, you need to close it and reopen it.
}

\index{StreamReader!EndOfStream}\index{EndOfStream}

\subsection{Reading to End of Stream}
\label{fileread:reading-to-end-of-stream}\label{fileread:endofstream}\label{fileread:index-1}
In \code{first\_file.cs}, we explicitly coded reading two lines.  You will often
want to process each line in a file, without knowing the total number of
lines while programming.  This means that files provide us with our
second kind of a sequence:  this time the sequence of lines in the file!
To process all of them will require a loop and a new test to make sure that you
have not yet come to the end of the file's stream: You can use the \code{EndOfStream}
property. It has the wrong sense (true at the end of the file), so we negate it,
testing for \code{!reader.EndOfStream} in the example program \code{print\_file\_lines.cs}.
This little program reads and prints the contents of a file specified by the
user, one line at a time:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{using} \PYG{n+nn}{System.IO}\PYG{p}{;}

\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{k}{class} \PYG{n+nc}{PrintFileLines}  \PYG{c+c1}{// demo of using EndOfStream test}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{string} \PYG{n}{userFileName} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter name of file to print: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{var} \PYG{n}{reader} \PYG{p}{=} \PYG{k}{new} \PYG{n}{StreamReader}\PYG{p}{(}\PYG{n}{userFileName}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{p}{!}\PYG{n}{reader}\PYG{p}{.}\PYG{n}{EndOfStream}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{string} \PYG{n}{line} \PYG{p}{=} \PYG{n}{reader}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{line}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{reader}\PYG{p}{.}\PYG{n}{Close}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{var}\index{type!var}\begin{description}
\item[{\code{var}}] \leavevmode
For conciseness (and variety) we declared \code{reader}
using the more compact syntax with \code{var}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{var} \PYG{n}{reader} \PYG{p}{=} \PYG{k}{new} \PYG{n}{StreamReader}\PYG{p}{(}\PYG{n}{userFileName}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

You can use \code{var} in place of a declared type to shorten your code
with a couple of restrictions:
\begin{itemize}
\item {} 
Use an initializer, from which the type of the variable can be inferred.

\item {} 
Declare a local variable inside a method body or in a loop heading.

\item {} 
Declare only a single variable in the statement.

\end{itemize}

We could have used this syntax long ago, but as the type names become longer,
it is more useful!

\end{description}

Things to note about reading from files:

\index{StreamReader!null from ReadLine}\index{ReadLine!null with StreamReader}\begin{itemize}
\item {} 
Reading from a file returns the part read, of course.  Never forget the
\emph{side effect}:  The location in the file advances past the part just read.
The next read does \emph{not} return the \emph{same} thing as last time.  It returns
the \emph{next} part of the file.

\item {} 
Our \code{while} test conditions so far have been in a sense ``backward looking'':
We have tested a variable that has \emph{already been set}.
The test with \code{EndOfStream} is
\emph{forward looking}:  looking at what has not been processed yet.  Other than
making sure the file is opened, there is no variable that needs to be set
before a \code{while} loop testing for \code{EndOfStream}.

\item {} 
If you use ReadLine at the end of the file, the special value \code{null} (no object)
is returned.  \emph{This} is not an error, but if you try to apply any string methods
to the \code{null} value returned, \emph{then} you get an error!

\end{itemize}

\index{file (StreamWriter)!ReadToEnd}\index{StreamReader!ReadToEnd}\index{ReadToEnd}\phantomsection\label{fileread:readtoend}
Though \code{print\_file\_lines.cs} was a nice simple illustration of a loop reading
lines, it was very verbose considering the final effect of the program,
just to print the whole file.
You can read the entire remaining contents of a file
as a single (multiline) string, using the
\code{StreamReader} method \code{ReadToEnd}.  In place of the reading and printing
loop we could have just had:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{wholeFile} \PYG{p}{=} \PYG{n}{reader}\PYG{p}{.}\PYG{n}{ReadToEnd}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{wholeFile}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\code{ReadToEnd} does not strip off a newline, like \code{ReadLine} does,
so we do not want to add an extra newline
when writing.  We use the \code{Write} method instead of \code{WriteLine}.

\index{example!sum\_files.cs}\index{sum\_files.cs example}

\subsection{Example: Sum Numbers in File}
\label{fileread:index-5}\label{fileread:example-sum-numbers-in-file}
We have summed the numbers from 1 to \code{n}.  In that case we generated
the next number \code{i} automatically using i++.  We could also read numbers
from a file containing one number per line (plus possible white space):

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{CalcSum}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{filename}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
   \PYG{k+kt}{var} \PYG{n}{reader} \PYG{p}{=} \PYG{k}{new} \PYG{n}{StreamReader}\PYG{p}{(}\PYG{n}{filename}\PYG{p}{)}\PYG{p}{;}
   \PYG{k}{while} \PYG{p}{(}\PYG{p}{!}\PYG{n}{reader}\PYG{p}{.}\PYG{n}{EndOfStream}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{k+kt}{string} \PYG{n}{sVal} \PYG{p}{=} \PYG{n}{reader}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Trim}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{sum} \PYG{p}{+}\PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{sVal}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{n}{reader}\PYG{p}{.}\PYG{n}{Close}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
   \PYG{k}{return} \PYG{n}{sum}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{File class!Exists}\index{Exists - File class method}
Below and in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sum\_file/sum\_file.cs}{sum\_file/sum\_file.cs} is a more elaborate, complete example,
that also exits gracefully if you give a bad file name.
If you give a good file name, it skips lines that contain only whitespace.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{using} \PYG{n+nn}{System.IO}\PYG{p}{;}

\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{k}{class} \PYG{n+nc}{SumFile}  \PYG{c+c1}{// sum a file integers, one per line}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{string} \PYG{n}{filename} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}
                            \PYG{l+s}{\PYGZdq{}Enter the name of a file of integers: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{File}\PYG{p}{.}\PYG{n}{Exists}\PYG{p}{(}\PYG{n}{filename}\PYG{p}{)}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}The sum is \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{CalcSum}\PYG{p}{(}\PYG{n}{filename}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{else} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Bad file name \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{filename}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// Read the named file and}
      \PYG{c+c1}{/// return the sum of an int }
      \PYG{c+c1}{/// from each line that is not just white space. }
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{CalcSum}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{filename}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
         \PYG{k+kt}{var} \PYG{n}{reader} \PYG{p}{=} \PYG{k}{new} \PYG{n}{StreamReader}\PYG{p}{(}\PYG{n}{filename}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{p}{!}\PYG{n}{reader}\PYG{p}{.}\PYG{n}{EndOfStream}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{string} \PYG{n}{sVal} \PYG{p}{=} \PYG{n}{reader}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Trim}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{sVal}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{sum} \PYG{p}{+}\PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{sVal}\PYG{p}{)}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{reader}\PYG{p}{.}\PYG{n}{Close}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{return} \PYG{n}{sum}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

A useful function used in \code{Main} for avoiding filename typo errors
is \code{File.Exists} in the \code{System.IO} namespace

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{bool} \PYG{n}{File}\PYG{p}{.}\PYG{n}{Exists}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{filenamePath}\PYG{p}{)}
\end{Verbatim}

It is true if the named files exists in the operating system's file structure.

You should see the file \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sum\_file/numbers.txt}{sum\_file/numbers.txt} in the Xamarin Studio project.
It is in the right form for the program.  If you run the program and enter the
response:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
numbers.txt
\end{Verbatim}

you should be told that the file does not exist.  Recall that the executable
created by Xamarin Studio is two directories down through \code{bin}
to \code{Debug}.  This is the default
\emph{current directory} when Xamarin Studio runs the program.
You can refer to
a file that is not in the current directory.
A full description is in the next section, but briefly, what we need now:
The symbol for the parent directory is \code{..}.
The hierarchy of folders and files are separated by
\code{\textbackslash{}} in Windows and \code{/} on a Mac,  so you can test the program successfully
if you use the file name:
\code{..\textbackslash{}..\textbackslash{}numbers.txt} in Windows and \code{../../numbers.txt} on a Mac.  On a Mac, running
the program looks like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Enter the name of a file of integers: ../../numbers.txt
The sum is 16
\end{Verbatim}

In {\hyperref[fio:fio]{\emph{FIO Helper Class}}} we will discuss a more flexible way of finding files to open,
that works well in Xamarin Studio and many other situations.

\index{exercise!safe sum}\index{safe sum exercise}

\subsubsection{Safe Sum File Exercise}
\label{fileread:safe-sum-file-exercise}\label{fileread:index-7}\begin{enumerate}
\item {} 
Copy \code{sum\_file.cs} to a file \code{safe\_sum\_file.cs} in a new project of yours.
Modify the program: Write
a new function with the heading below.  Use it in \code{Main}, in place of the \code{if}
statement that checks (only once) for a legal file:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// Prompt the user to enter a file name to open for reading.}
\PYG{c+c1}{// Repeat until the name of an existing file is given.}
\PYG{c+c1}{// Open and return the file.}
\PYG{k}{public} \PYG{k}{static} \PYG{n}{StreamReader} \PYG{n+nf}{PromptFile}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{prompt}\PYG{p}{)}
\end{Verbatim}

\item {} 
A user who forgot the file name woud be stuck!
Elaborate the function and program, so that an empty line entered means
``give up'', and \code{null} (no object) should be returned.  The main program needs to
test for this and quit gracefully in that case.

\end{enumerate}


\subsection{Example Copy to Upper Case}
\label{fileread:example-copy-to-upper-case}
Here is a simple fragment from example file \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/copy\_upper/copy\_upper.cs}{copy\_upper/copy\_upper.cs}.
It copies a file line by line to a new file in upper case:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
         \PYG{k+kt}{var} \PYG{n}{reader} \PYG{p}{=} \PYG{k}{new} \PYG{n}{StreamReader}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}text.txt\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{var} \PYG{n}{writer} \PYG{p}{=} \PYG{k}{new} \PYG{n}{StreamWriter}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}upper\PYGZus{}text.txt\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{p}{!}\PYG{n}{reader}\PYG{p}{.}\PYG{n}{EndOfStream}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{string} \PYG{n}{line} \PYG{p}{=} \PYG{n}{reader}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{writer}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{line}\PYG{p}{.}\PYG{n}{ToUpper}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{reader}\PYG{p}{.}\PYG{n}{Close}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{writer}\PYG{p}{.}\PYG{n}{Close}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

You may test this in the Xamarin Studio example project copy\_upper:
\begin{enumerate}
\item {} 
Expand the copy\_upper project in the Solution pad.  The project
includes the input file.  You may not see it at first.  You need to expand the folder
for \code{bin} and then \code{Debug}.  You see \code{text.txt}.

\item {} 
To see
what else is in the file system directory,
you can select the Debug folder and right click and select
Open Containing Folder.
You should see \code{text.txt} but not \code{upper\_text.txt}.
Leave that operating system file folder open.

\item {} 
Go back to Xamarin Studio and run the project.  Now look at the
operating system \code{Debug} folder again.  You should see \code{upper\_text.txt}.
You can open it and see that it holds an upper case version of the contents
of \code{text.txt}.

\end{enumerate}

This is another case where the \code{ReadToEnd} function could have eliminated the loop.
\footnote{
Besides the speed and efficiency of this second approach,
there is also a technical improvement:  There may or may not be
a newline at the end of the very last line of the file.  The \code{ReadLine}
method works either way, but does not let you know the difference.
In the line-by-line version, there is always a newline after the
final line written with \code{WriteLine}.
The \code{ReadToEnd} version will have newlines exactly matching the input.
}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{contents} \PYG{p}{=} \PYG{n}{reader}\PYG{p}{.}\PYG{n}{ReadToEnd}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{writer}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{contents}\PYG{p}{.}\PYG{n}{ToUpper}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\index{path}

\section{Path Strings}
\label{paths:path-strings}\label{paths:index-0}\label{paths::doc}\label{paths:id1}
When a program is running, there is alway a \emph{current working directory}.
When you run a project through Xamarin Studio, by default the current directory is the directory
two levels below the project directory.

Files in the current working directory can to referred to by their simple names,
e.g., \emph{sample.txt}.

Referring to files not in the current directory is more complicated.
You should be aware from using the Windows Explorer or the Finder that
files and  directories are located in a hierarchy of directories in the
file system.  On a Mac, the file system is unified in
one hierarchy. On Windows, each drive has its own hierarchy.

Files are generally referred to by a chain of directories before
the final name of the file desired.  A \emph{path string} is used
to represent such a sequence of names.  Elements of the directory chain are separated
by operating system specific punctuation:  In Windows the separator is backslash, \textbackslash{},
and on a Mac it is (forward) slash, /.  For example on a Mac the path

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
/Users/anh
\end{Verbatim}

starts with a /, meaning the \emph{root} or top directory in the hierarchy, and Users is
a subdirectory, and anh is a subdirectory of Users (in this case the home directory
for the user with login anh).
It is similar with Windows, except there may be a drive in the beginning,
and the separator is a \textbackslash{}, so

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
C:\PYGZbs{}Windows\PYGZbs{}System32
\end{Verbatim}

is on C: drive; Windows is a subdirectory of the root directory \textbackslash{}, and System32 is
a subdirectory of Windows.
Each drive in Windows has a separate file hierarchy underneath it.

Paths starting from the root of a file system, with \code{\textbackslash{}} or \code{/} are called
\emph{absolute paths}.
Since there is always a current directory, it makes sense to allow a path to be \emph{relative}
to the current directory.  In that case do \emph{not} start with the slash that would
indicate the root directory.  For example, if the current directory is
your home directory, you likely have a subdirectory \code{Downloads}, and the
\code{Downloads}
directory might contain \code{examples.zip}.  From the home directory, this file could
be referred to as \code{Downloads\textbackslash{}examples.zip} or  \code{Downloads/examples.zip} on a Mac.

Relative to a Xamarin Studio project directory, the current directory for execution
of the program is \code{bin\textbackslash{}Debug} or  \code{bin/Debug} on a Mac.

Referring to files in the current directory just by their plain file name is
actually an example of using relative paths.

With relative paths, you sometimes want to move up the directory hierarchy:  \code{..}
(two periods) refers to the directory one level up the chain.

Next imagine reversing the relative path from a Xamarin Studio project directory to the
current directory for execution:  If the current directory is the execution
directory, then \code{..} refers to directory \code{bin}, and then
\code{..\textbackslash{}..} or \code{../..} refers to the project directory.  Further, if the
project directory contains the file \code{numbers.txt}, then it could be referred to
relative to the execution directory as
\code{..\textbackslash{}..\textbackslash{}numbers.txt} or \code{../../numbers.txt}.

Occasionally you need to
refer explicitly to the current directory:  It is referred to as ''.'' (a single
period).


\subsection{Paths in C\#}
\label{paths:paths-in-c}
The differing versions of paths for Windows and a Mac are a pain to deal with. Luckily C\#
abstracts away the differences.  It has a \code{Path} class in the \code{System.IO}
namespace that provides many handy functions for dealing with paths in
an operating system independent way:

For one thing, C\# knows the path separator character for your operating system,
\code{Path.DirectorySeparatorChar}.

More useful is the function \code{Path.Combine}, which takes any number of string parameters
for sequential parts of a path, and creates a single string appropriate for the
current operating system.  For example,
\code{Path.Combine("bin", "Debug")} will return \code{"bin\textbackslash{}Debug"} or \code{"bin/debug"}
as appropriate.
\code{Path.Combine("..", "..", "numbers.txt")} will return a string with characters
\code{..\textbackslash{}..\textbackslash{}numbers.txt} or \code{../../numbers.txt}.

Even if you know you are going to be on Windows, file paths are a problem because
\code{\textbackslash{}} is the string escape character.  To enter the Windows path above explicitly
you would need to have \code{"..\textbackslash{}\textbackslash{}..\textbackslash{}\textbackslash{}numbers.txt"}, or the raw string prefix,
\code{@} can come to the rescue:  \code{@"..\textbackslash{}..\textbackslash{}numbers.txt"}.

You can look at the \code{Path} class in the MSDN documentation
for many other operations with path strings.

Path strings are used by the {\hyperref[dir-file:directory-class]{\emph{Directory Class}}} and by the {\hyperref[dir-file:file-class]{\emph{File Class}}}.

\index{Directory}

\section{Directory Class}
\label{dir-file:directory-class}\label{dir-file:index-0}\label{dir-file::doc}\label{dir-file:id1}
The \code{Directory} class is in the \code{System.IO} namespace.
Directories in the file system are referenced by {\hyperref[paths:path-strings]{\emph{Path Strings}}}.
You can look at the MSDN documentation for a wide variety of functions in the
\code{Directory} class including ones to list all the files in a directory
or to check if a path string represents an actual directory.

\index{File class}

\section{File Class}
\label{dir-file:file-class}\label{dir-file:id2}\label{dir-file:index-1}
We will generally access operating system files using the \code{Stream} abstraction,
discussed earlier in this chapter.
There is also a \code{File} class in the \code{System.IO} namespace, with a number
of specialized and convenience functions.
We already used the \code{File.Exists} function.

You can look at the MSDN documentation for other uses of the \code{File} class.

\index{command line!execution}\index{execution on command line}

\section{Command Line Execution}
\label{cmdline-execution:index-0}\label{cmdline-execution::doc}\label{cmdline-execution:command-line-execution}\label{cmdline-execution:cmdline-execution}
C\# shields you from the differences
between operating systems
with its \code{File}, \code{Path}, and \code{Directory} classes.

If you leave Xamarin Studio and go to the command line as described in
{\hyperref[cmdline:commandline]{\emph{Command Line Introduction}}}, then you are exposed to the differences
between the operating systems.  \emph{Look over that section.}

Thus far we have let Xamarin Studio hide what actually is happening when
you execute a program.  The natural environment for the text-based programs
that we are writing is the command line.
We need to get outside of Xamarin Studio.
\begin{enumerate}
\item {} 
To show off the transition, first build or run the \code{addition1} example project
from inside Xamarin Studio.

\item {} 
Open a terminal on a Mac or a Mono Command Prompt console in Windows.

\item {} 
Following the
{\hyperref[cmdline:commandline]{\emph{Command Line Introduction}}},
change the current directory to the addition1 example project directory.

\item {} 
Then change to the subdirectory \code{bin} and then the subdirectory \code{Debug}.

\item {} 
Enter the command to list the directory (\code{dir} in Windows; \code{ls} on a Mac).

\item {} 
You should see \code{addition1.exe}.  This is the compiled program
created by Xamarin Studio.  Enter the command

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
mono addition1.exe
\end{Verbatim}

This should run your program.  Note that when you complete it, the window does not
disappear!  You keep that history.  Keep this terminal/console window open
until the end of the chapter.

\item {} 
Windows only:  On Windows, Xamarin Studio creates a regular Windows executable file.
For consistency you can use the command above, but you no longer need Mono.
You can just enter the command \code{addition1.exe} or the shorter \code{addition1}.

\end{enumerate}

\index{mcs}\index{command line!compile}\index{compile on command line}

\subsection{MCS: Compiling}
\label{cmdline-execution:index-1}\label{cmdline-execution:gmcs}\label{cmdline-execution:mcs-compiling}
Continue with the same terminal/console window.
Let us now consider creating an executable program for \code{addition1.cs},
directly, without using Xamarin Studio:
\begin{enumerate}
\item {} 
Enter the command \code{cd ..} and then \emph{repeat}: \code{cd ..},
to go up to the project directory.

\item {} 
Print a listing of the directory.
You should see
\code{addition1.cs} but not \code{addition1.exe}.

\item {} 
Try the command

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
mono addition1.exe
\end{Verbatim}

You should get an error message, because \code{addition1.exe} is not in the current
directory.

\item {} 
Enter the command

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
mcs addition1.cs
\end{Verbatim}

This is the Mono system compiler, building from the source code.

\item {} 
Print a listing of the directory.  You should see
now \code{addition1.exe}, created by the compiler.

\item {} 
Try the command again:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
mono addition1.exe
\end{Verbatim}

\end{enumerate}

Now try a program that had multiple files.  The project version addition3
uses the library class UIF.  Continue with the same terminal/console window:
\begin{enumerate}
\item {} 
Enter the commands:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
cd ../addition3
mcs addition3.cs
\end{Verbatim}

You should get an error about missing the UIF class. The mcs program
does not know about the information Xamarin Studio keeps in its references.

\item {} 
Extend the command:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
mcs addition3.cs ../ui/uif.cs
\end{Verbatim}

That should work, now referring to both needed files.

\item {} 
Enter the command

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
mono addition3.exe
\end{Verbatim}

\item {} 
Now let us try a project where we read a file.  Enter commands
\begin{quote}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
cd ../sum\PYGZus{}file
mcs sum\PYGZus{}file.cs
mono sum\PYGZus{}file.exe
\end{Verbatim}
\end{quote}

We ran this program earlier through Xamarin Studio.  Recall that that
entering the file name \code{numbers.txt} failed, and to refer to the right
place for the \code{numbers.txt} file, we needed to use \code{..\textbackslash{}..\textbackslash{}numbers.txt}
or \code{../../numbers.txt}.  This time \emph{just enter} \code{numbers.txt}.  The
program should work, giving the answer 16.

\end{enumerate}

By default mcs and mono read from and write to the current directory of the
terminal/console.  In the situation above, \code{sum\_file.cs} and \code{numbers.txt}
were in the project directory, which is the current directory.
Then sum\_file.exe was written to and run from
the same directory.

This is unlike the Xamarin Studio default, where the current directory for execution
is not the project directory.

Under the hood, Xamarin Studio uses mcs also, with a bunch of further options
in the parameters, changing the execution directory and also arranging
for better debugging information when you get a runtime error.

\index{NAnt build tool}
Xamarin Studio keeps track of all of the parts of your projects, and recompiles only
as needed.  There are
also command-line tools that manage multi-file projects neatly, remembering
the parts, and compiling only as necessary.
One example is NAnt, which comes with Mono.

\index{FIO file I/O}\index{library!FIO}

\section{FIO Helper Class}
\label{fio:fio-helper-class}\label{fio:index-0}\label{fio::doc}\label{fio:fio}
We have already discussed and used the \code{UI} class to aid keyboard input.
Now we are going to develop an \code{FIO} class for our libraries.  The \code{FIO} class aids
file input and output with Xamarin Studio, and illustrates a number of
more generally useful ideas.

You saw in the last section how we might refer to \code{numbers.txt} in different
ways depending on the execution environment.  Our situation
is based on the particular choices made by the creators of Xamarin Studio.
More generally, there are many times when a program may need a file
that may be stored in one of several directories.

Our \code{FIO} class will address this issue, and we will set up the
parameters to work specifically with both Xamarin Studio and command line
development.

We use one idea that is discussed more in the next chapter:  We need a sequence
of directory strings to look through.  At this point we have only discussed
sequences of individual characters.   The variable \code{paths}
contains a sequence of directory paths to check.  In our case we make the
sequence contain
\code{"."}, the current directory, \code{".."}, the parent directory, and
\code{Path.Combine("..", "..")}, the parent's parent.
We make \code{paths} a static variable, so
it is visible in all the functions in the class.

Then the sequence \code{paths}
can be used in the \code{foreach} loop:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Find a directory containing the filename}
      \PYG{c+c1}{/// and return the full file path, if it exists. }
      \PYG{c+c1}{/// Otherwise return null.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{GetPath}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{filename}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{dir} \PYG{k}{in} \PYG{n}{paths}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{string} \PYG{n}{filePath} \PYG{p}{=} \PYG{n}{Path}\PYG{p}{.}\PYG{n}{Combine}\PYG{p}{(}\PYG{n}{dir}\PYG{p}{,} \PYG{n}{filename}\PYG{p}{)}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{File}\PYG{p}{.}\PYG{n}{Exists}\PYG{p}{(}\PYG{n}{filePath}\PYG{p}{)}\PYG{p}{)}
               \PYG{k}{return} \PYG{n}{filePath}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{k}{null}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

For each directory path in \code{paths}, we create a \code{filePath} as if the
file were in that directory.  We return the first path that actually exists.
We allow for the file to not be in any of the directories in \code{paths}.  If
we do not find it, we return \code{null} (no object).

For convenience, we have an elaboration, using \code{GetPath},
that directly opens the file to read:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Find a directory containing filename;}
      \PYG{c+c1}{/// return a new StreamReader to the file}
      \PYG{c+c1}{/// or null if the file does not exist.}
      \PYG{k}{public} \PYG{k}{static} \PYG{n}{StreamReader} \PYG{n+nf}{OpenReader}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{filename}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}                                
         \PYG{k+kt}{string} \PYG{n}{filePath} \PYG{p}{=} \PYG{n}{GetPath}\PYG{p}{(}\PYG{n}{filename}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{filePath} \PYG{p}{=}\PYG{p}{=} \PYG{k}{null}\PYG{p}{)}
            \PYG{k}{return} \PYG{k}{null}\PYG{p}{;}
         \PYG{k}{else}
            \PYG{k}{return} \PYG{k}{new} \PYG{n+nf}{StreamReader}\PYG{p}{(} \PYG{n}{filePath}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

We have a variation on \code{GetPath} that just return the path to the
directory containing the file.  Here is the heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a directory conaining the filename, if it exists. }
      \PYG{c+c1}{/// Otherwise return null.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{GetLocation}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{filename}\PYG{p}{)}
\end{Verbatim}

This is useful in case you want to later write into the same directory
that you read from.  You can get a location from \code{GetLocation} and then
write to the same directory, creating a \code{StreamWriter}. Use the convenience
function:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Join the location directory and filename;}
      \PYG{c+c1}{/// open and return a StreamWriter to the file. }
      \PYG{k}{public} \PYG{k}{static} \PYG{n}{StreamWriter} \PYG{n+nf}{OpenWriter}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{location}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{filename}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}           
         \PYG{k+kt}{string} \PYG{n}{filePath} \PYG{p}{=} \PYG{n}{Path}\PYG{p}{.}\PYG{n}{Combine}\PYG{p}{(}\PYG{n}{location}\PYG{p}{,} \PYG{n}{filename}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{return} \PYG{k}{new} \PYG{n+nf}{StreamWriter}\PYG{p}{(}\PYG{n}{filePath}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

The entire \code{FIO} class is in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/fio/fio.cs}{fio/fio.cs}

We illustrate the use of \code{FIO} functions in example file
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/fio\_usage/fio\_usage.cs}{fio\_usage/fio\_usage.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{using} \PYG{n+nn}{System.IO}\PYG{p}{;}

\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{k}{class} \PYG{n+nc}{FIOTest}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{args}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{string} \PYG{n}{sample} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}sample.txt\PYGZdq{}}\PYG{p}{;}
         \PYG{k+kt}{string} \PYG{n}{output} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}output.txt\PYGZdq{}}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Directory of \PYGZob{}0\PYGZcb{}: \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} 
                           \PYG{n}{sample}\PYG{p}{,} \PYG{n}{FIO}\PYG{p}{.}\PYG{n}{GetLocation}\PYG{p}{(}\PYG{n}{sample}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Path to  \PYGZob{}0\PYGZcb{}: \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} 
                           \PYG{n}{sample}\PYG{p}{,} \PYG{n}{FIO}\PYG{p}{.}\PYG{n}{GetPath}\PYG{p}{(}\PYG{n}{sample}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{StreamReader} \PYG{n}{reader1} \PYG{p}{=} \PYG{n}{FIO}\PYG{p}{.}\PYG{n}{OpenReader}\PYG{p}{(}\PYG{n}{sample}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{reader1} \PYG{p}{!}\PYG{p}{=} \PYG{k}{null}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{reader1}\PYG{p}{.}\PYG{n}{ReadToEnd}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}First reader test passed.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{reader1}\PYG{p}{.}\PYG{n}{Close}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}

         \PYG{n}{StreamReader} \PYG{n}{reader2} \PYG{p}{=} \PYG{n}{FIO}\PYG{p}{.}\PYG{n}{OpenReader}\PYG{p}{(}\PYG{n}{FIO}\PYG{p}{.}\PYG{n}{GetLocation}\PYG{p}{(}\PYG{n}{sample}\PYG{p}{)}\PYG{p}{,} 
                                               \PYG{n}{sample}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{reader2} \PYG{p}{!}\PYG{p}{=} \PYG{k}{null}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Second reader test passed.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{reader2}\PYG{p}{.}\PYG{n}{Close}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}

         \PYG{n}{StreamWriter} \PYG{n}{writer1} \PYG{p}{=} \PYG{n}{FIO}\PYG{p}{.}\PYG{n}{OpenWriter}\PYG{p}{(}\PYG{n}{FIO}\PYG{p}{.}\PYG{n}{GetLocation}\PYG{p}{(}\PYG{n}{sample}\PYG{p}{)}\PYG{p}{,} 
                                               \PYG{n}{output}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{writer1}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}File in the same directory as \PYGZob{}0\PYGZcb{}.\PYGZdq{}}\PYG{p}{,} \PYG{n}{sample}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{writer1}\PYG{p}{.}\PYG{n}{Close}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Writer test passed; file written at \PYGZbs{}n \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} 
                           \PYG{n}{FIO}\PYG{p}{.}\PYG{n}{GetPath}\PYG{p}{(}\PYG{n}{output}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

IF you look at the fio\_usage project in our examples solution, you see that
\code{sample.txt} is a file in the project folder.  The program
ends up writing to a new file in the same (project) directory.  Remember that even
though the new file \code{output.txt}
appears in the project directory, it does not appear in the
Solution pad unless you add it to the project.  You can see it in the file system,
and open it if you like.

If you want to open a terminal/console and go to the project directory, you can compile
and run this program, and it will still work, even though the current directory
has changed.

You are encouraged to make a library project fio in \emph{your} work solution, copying
the fio.cs file. (Follow instruction like for ui in
{\hyperref[libraryclass:library-projects-in-xamarinstudio]{\emph{Library Projects in Xamarin Studio (Optional)}}}.)  You can test your new library by also
copying the fio\_test project to your solution.
If you do this now and stick to one work solution, then you will be ready for
several later uses of \code{FIO}.


\subsection{File Line Removal Exercise}
\label{fio:file-line-removal-exercise}
Complete the function described below, and make a Main program and
sample file to test it:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Take all lines from reader that do not start with startToRemove}
\PYG{c+c1}{/// and copy them to writer.}
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{FileLineRemoval}\PYG{p}{(}\PYG{n}{StreamReader} \PYG{n}{reader}\PYG{p}{,} \PYG{n}{StreamWriter} \PYG{n}{writer}
                            \PYG{k+kt}{char} \PYG{n}{startToRemove}\PYG{p}{)}
\end{Verbatim}

For example, in Unix/Mac scripts lines starting with \code{'\#'} are
comment lines.  Making \code{startToRemove} be \code{'\#'} would write only non-comment lines
to the writer.


\section{Chapter Review Questions}
\label{reviewfiles:chapter-review-questions}\label{reviewfiles::doc}\begin{enumerate}
\item {} 
After writing everything you want to a file through a \code{StreamWriter},
what do you still need to remember to do?

\item {} 
If you want to create a file path in an operating system independent way for
file f.txt in directory d2, which is a subdirectory of d1, which is a
subdirectory of the current directory, how would you do it?

\item {} 
Windows uses \code{\textbackslash{}} as a path separator.  If you want to write a literal
directly for a Windows path, what issue is there in C\#?

\item {} 
In a file path, how do you refer to the parent directory of the
current directory, without using the actual name of the parent directory?

\item {} 
If you are reading from a \code{StreamReader} \code{inFile}, what is logically
wrong with the following:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{if} \PYG{p}{(}\PYG{n}{inFile}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Contains}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}!\PYGZdq{}}\PYG{p}{)}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{inFile}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}\PYGZbs{}n contains the symbol !\PYGZdq{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\end{enumerate}

\index{array}\index{type!array}

\chapter{Arrays}
\label{arrays:arrays}\label{arrays:index-0}\label{arrays:array}\label{arrays::doc}
\index{array!one dimensional}

\section{One Dimensional Arrays}
\label{onedim:one-dimensional-arrays}\label{onedim:index-0}\label{onedim::doc}\label{onedim:one-dim-arrays}
\index{array!{[} {]} declaration}

\subsection{Basic Syntax}
\label{onedim:index-1}\label{onedim:basic-syntax}
A string is an immutable sequence of characters.  Arrays provide more general sequences,
with the same indexing notation, but with free choice of the type of the items in the
sequence, and the ability to change the elements in the sequence.

For example, if we want the type for an array with \code{int} elements, it is \code{int{[}{]}}.
In general for any element type, the type for an array of the element type is
\begin{quote}

\textbf{type}\code{{[}{]}}
\end{quote}

so

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{;}
\end{Verbatim}

declares \code{a} to refer to an array containing \code{int} elements.  You do \emph{not}
know how many elements will be allowed in this array from this declaration.
We must give further information to create the corresponding array object.
A new object can be created using the \code{new} syntax.  An array must get a definite
length, which can be a literal integer or any integer expression.  For example

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{;}
\PYG{n}{a} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{4}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

or combined with the declaration,

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{4}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

creates an array that holds 4 integers.  The elements of the array must get initial values.
Numerical arrays get initialized to all 0's with this syntax.

For a variety of reasons, including bookkeeping by the compiler, the actual data for
an array is \emph{not} stored directly in the memory location allocated by the declaration.
The array could have any number of items, and hence the memory requirements are not known
at compile time.  Like all other object (as opposed to primitive) types,
what is actually stored at the memory location declared for \code{a} is a \emph{reference} to the
actual place where the data for the array is stored.
In actual compiler implementation this reference is an address in memory.
In diagrams we will illustrate object references with an arrow \emph{pointing} to the actual
location for the object's data.  For example after \code{a} is initialized:

{\hfill\includegraphics[width=437.25pt]{newArray1.png}\hfill}

The small box beside \code{a} is meant to indicate the memory space allocated when \code{a} is
declared.  As you can see that space does not actually contain the array, but only a
\emph{reference} to the array, pointing to the actual sequence of data for the array.
To make it easy to refer to the elements in the diagram, we also label the indices
associated with each element, though they are not actual a part of what is stored in memory.

The general syntax to create a  new array is
\begin{quote}

\code{new} \textbf{type}\code{{[}} \emph{length} \code{{]}}
\end{quote}

After the type, there are square brackets enclosing an expression for the length
of the array - this length is unchangeable after creation.

\index{{[} {]}!array indexing}\index{array!indexing {[} {]}}\index{index!array}
The elements inside an array can to referenced with the same index notation used
earlier for strings.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{a}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]}
\end{Verbatim}

refers to the element at index 2 (third element because of 0 based indexing).

Unlike with strings, this element can not only be read, but also be assigned to:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{a}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{7}\PYG{p}{;}
\PYG{n}{a}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{;}
\PYG{n}{a}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{9}\PYG{p}{;}
\PYG{n}{a}\PYG{p}{[}\PYG{l+m}{3}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{6}\PYG{p}{;}
\end{Verbatim}

These four assignment statements
would replace the original 0 values for each element in the array.

This is a verbose way to specify all array values. An array with the
same final data could be created with the single declaration:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{b} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+m}{7}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{,} \PYG{l+m}{9}\PYG{p}{,} \PYG{l+m}{6}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\end{Verbatim}

{\hfill\includegraphics[width=433.5pt]{newArray2.png}\hfill}

The list in braces ONLY is allowed as an initialization of a variable
in a \emph{declaration}, not in a later assignment statement.
Technically it is an initializer, not an array literal.

Individual array elements can \emph{both} be used in expressions, and be assigned to.
Continuing with the
earlier example code:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{a}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{4}\PYG{p}{*}\PYG{n}{a}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]} \PYG{p}{\PYGZhy{}} \PYG{n}{a}\PYG{p}{[}\PYG{l+m}{3}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

\code{a{[}2{]}} now equals 4*5 - 6 = 14.

Arrays, like strings, have a \code{Length} property:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{b}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints 4}
\end{Verbatim}

Just as we saw that using a variable for an index was useful with
strings, in practice array elements are almost always referred to with an index
variable.  A very common pattern is to deal with each element in sequence,
and the syntax is the same as for a string.  Print all elements of array \code{b}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{b}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{,} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{b}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

You could also use \code{while} syntax.  The \code{foreach} syntax would be:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{foreach}\PYG{p}{(} \PYG{k+kt}{int} \PYG{n}{x} \PYG{k}{in} \PYG{n}{b}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The \code{int} type for \code{x} matches the element type of the array \code{b}.

The shorter \code{foreach} syntax is not as general as the \code{for} syntax.
For example, to print only the first \emph{3} elements of b:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{b}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

but the \code{foreach} syntax would not work, since it must process \emph{all} elements.

Also use the \code{for} syntax to assign new values to the array elements,
rather than just use the values in expressions:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{for}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{b}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{b}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{5}\PYG{p}{*}\PYG{n}{i}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Now the array \code{b} of our earlier examples (of length 4) would contain 0, 5,
10, and 15.

\begin{notice}{warning}{Warning:}
There is no analog of \emph{changing} the value of \code{b{[}i{]}} with a
\code{foreach} loop.  To change values in an array, we must
assign to each location in the array by \emph{index}.
A \code{foreach} loop only provides the \emph{value} of each sequence element
for us to read.
\end{notice}

We have had the array indices so far be given by a single symbol,
which is the most common case in practice, but in fact what appears
inside the square braces can be any \code{int} \emph{expression}.
Like parentheses, square brackets \emph{delimit}
the inside expression, which gets evaluated first, before the array value is
looked up.  Consider this csharp sequence:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} int[] a = \PYGZob{}5, 9, 15, \PYGZhy{}4\PYGZcb{};
csharp\PYGZgt{} int i = 2;
csharp\PYGZgt{} a[i];
15
\end{Verbatim}

This should be clear.  Now think first, what should \code{a{[}i+1{]}} be?

...

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} a[i+1];
\PYGZhy{}4
\end{Verbatim}

In steps:  \code{a{[}i+1{]}} is \code{a{[}2+1{]}} is \code{a{[}3{]}} is -4. Be careful,
\code{a{[}i+1{]}} is \emph{NOT} \code{a{[}i{]} + 1} (which would be 16).

\index{array!as parameter}\index{example!PrintStrings}\phantomsection\label{onedim:printstrings}
The code above to print each element of an array performs a
unified and possibly useful operation, so it would make sense to
encapsulate it into a function.  A function can take any type as a
parameter, so an array type is perfectly reasonable!  Above we
printed each element of an array of integers.  This time lets choose strings,
so the formal parameter is an array of strings:  \code{string{[}{]}}.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Print the strings in data, one per line.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintStrings}\PYG{p}{(}\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{foreach}\PYG{p}{(} \PYG{k+kt}{string} \PYG{n}{s} \PYG{k}{in} \PYG{n}{data}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

With this definition, the code fragment

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{hamlet} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+s}{\PYGZdq{}To be\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}or not\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}to be!\PYGZdq{}}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{n}{PrintStrings}\PYG{p}{(}\PYG{n}{hamlet}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

would print:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
To be
or not
to be!
\end{Verbatim}

Here we are just reading the data from the array parameter.
We will see that there are more wrinkles to array parameters in {\hyperref[onedim:alias]{\emph{References and Aliases}}}.

\index{function!return array}\index{array!returned by method}
An array type can also be
returned like any other type.  Examine the function definition:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return an array with string data obtained from the user.}
      \PYG{c+c1}{/// The length of the array and the number of entries to}
      \PYG{c+c1}{///   prompt the user for is n.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{InputNStrings}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}                         
         \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{lines} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{string}\PYG{p}{[}\PYG{n}{n}\PYG{p}{]}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter \PYGZob{}0\PYGZcb{} string(s).\PYGZdq{}}\PYG{p}{,} \PYG{n}{n}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{n}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{lines}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}next string: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{lines}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

This code follows a standard pattern for functions returning an array:
\begin{itemize}
\item {} 
In order to return an array, we must \emph{first create} a new array
with the \code{new} syntax.  We must set the proper length (\code{n} here).

\item {} 
And we are not done with one line of creation:  Since the array has
multiple parts, we need a loop to assign all the values.  We have a simple
\code{for} loop to assign to each element in turn.

\item {} 
Finally we must return the array that we created!

\end{itemize}

\index{command line!parameter}\index{parameter!command line to Main}\index{Main!parameters}

\subsection{Parameters to Main}
\label{onedim:command-line-param}\label{onedim:index-5}\label{onedim:parameters-to-main}
The \code{Main} function may take an array of strings as parameter, as in example
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/print\_param/print\_param.cs}{print\_param/print\_param.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
   \PYG{c+c1}{/// Demonstrate the use of command line parameters. }
   \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{args}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}There are \PYGZob{}0\PYGZcb{} command line parameters.\PYGZdq{}}\PYG{p}{,} \PYG{n}{args}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;}
      \PYG{k}{foreach}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s} \PYG{k}{in} \PYG{n}{args}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

   \PYG{p}{\PYGZcb{}}
\end{Verbatim}

By convention, the formal parameter for \code{Main} is called \code{args},
short for arguments.

Compile and run the program from the command line.
Run it again with some things at the end of the line like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
mono print\PYGZus{}param.exe hi there 123
\end{Verbatim}

This should print for you:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
There are 3 command line parameters.
hi
there
123
\end{Verbatim}

See what quoted strings do.  Use command line parameters (with the quotes)
\code{"hi there" 123}.
This should print for you:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{There} \PYG{n}{are} \PYG{l+m}{2} \PYG{n}{command} \PYG{n}{line} \PYG{n}{parameters}\PYG{p}{.}
\PYG{n}{hi} \PYG{n}{there}
\PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{3}
\end{Verbatim}

\index{Xamarin Studio!command line parameters}\index{command line!parameters in Xamarin Studio}
You can simulate command line parameters inside Xamarin Studio:
\begin{enumerate}
\item {} 
Open the local popup menu for the project you are using.

\item {} 
Select Run With \textgreater{}

\item {} 
In the submenu select Custom Parameters.

\item {} 
That brings up a dialog where you can enter the
desired command line parameters.

\item {} 
Optionally you can remember this setup by clicking on
box in front of ``Save this configuration as a custom execution mode''.
If you check it, you get a place to enter a Custom Mode Name.

\item {} 
End up clicking the Execute button.

\item {} 
If you set a Custom Mode, later when you get to the submenu after
``Run With \textgreater{}'', you will see your custom mode name to select!

\end{enumerate}

Try it!

\index{Xamarin Studio!combined with command line execution}\index{command line!execution combined with Xamarin Studio editing}
An alternative when you want to use command line parameters repeatedly is
\begin{enumerate}
\item {} 
Use Xamarin Studio for editing and compiling.
To compile but not run, the command is \textbf{Build} rather than \textbf{Run}.

\item {} 
Meanwhile keep a console/terminal
window open in the \code{Debug} directory, and enter execution
commands there, including the command line parameters
actually on the command line!
Even if you have a long set of parameters, you can easily run your
program multiple times with the same parameters by just pressing
the up arrow key in the terminal when you see the next command line prompt,
taking you back to the previous command
(or keep going back several commands).  This is also
convenient if you want to slightly edit the parameters: you can
edit a line that you redisplay from your command history.

\item {} 
Do not close this window until you are done with your session of executing
from the command line.  By using the same terminal window, you also
save the history of all your runs.  You can scroll the window up
to see past executions.

\end{enumerate}

If one run leads you to go back and fix a bug, go back to step one to
build the program again, and continue executing in the same terminal window.


\subsubsection{Modified Parameter Print Exercise}
\label{onedim:modified-parameter-print-exercise}
Modify a copy of \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/print\_param/print\_param.cs}{print\_param/print\_param.cs} to contain the earlier
example function {\hyperref[onedim:printstrings]{\emph{PrintStrings}}}, and call it.

\index{exercise!command line adder}\index{command line adder exercise}\index{Main!parameter exercise}\index{parameter!for Main exercise}

\subsubsection{Command Line Adder Exercise}
\label{onedim:id1}\label{onedim:index-8}\label{onedim:command-line-adder-exercise}
Write a program \code{adder.cs} that calculates and prints the sum of
command line parameters, so if you make the command line parameters
in Xamarin Studio be

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
2 5 22
\end{Verbatim}

then the program prints 29.

Do try running from the command line:  If you compiled with
Xamarin Studio, that means going down to the bin/Debug directory.
Recall Xamarin Studio for Windows produces a Windows executable,
not a Mono file, so you can run

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
adder 2 5 22
\end{Verbatim}

but on a Mac you need to run with mono:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
mono adder.exe 2 5 22
\end{Verbatim}

\index{string!Split}\index{Split method for strings}

\subsection{String Method Split}
\label{onedim:string-method-split}\label{onedim:split}\label{onedim:index-9}
A string method producing an array:
\begin{description}
\item[{\code{string{[}{]} Split(char} \textbf{separator} \code{)}}] \leavevmode
Returns an array of substrings from \emph{this} string.  They are the pieces left
after chopping out the separator character from the string.
A piece may be the empty string.
Example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} var fruitString = \PYGZdq{}apple pear banana\PYGZdq{};
csharp\PYGZgt{} string[] fruit = fruitString.Split(\PYGZsq{} \PYGZsq{});
csharp\PYGZgt{} fruit;
\PYGZob{} \PYGZdq{}apple\PYGZdq{}, \PYGZdq{}pear\PYGZdq{}, \PYGZdq{}banana\PYGZdq{} \PYGZcb{}
csharp\PYGZgt{} fruit[1];
\PYGZdq{}pear\PYGZdq{}
csharp\PYGZgt{} var s = \PYGZdq{}  extra   spaces \PYGZdq{};
csharp\PYGZgt{} s.Split(\PYGZsq{} \PYGZsq{});
\PYGZob{} \PYGZdq{}\PYGZdq{}, \PYGZdq{}\PYGZdq{}, \PYGZdq{}extra\PYGZdq{}, \PYGZdq{}\PYGZdq{}, \PYGZdq{}\PYGZdq{}, \PYGZdq{}spaces\PYGZdq{}, \PYGZdq{}\PYGZdq{} \PYGZcb{}
\end{Verbatim}

\end{description}

Note: The response with the list in braces is a purely \emph{csharp} convention for displaying
sequences for the user.  There is no corresponding string displayed by C\# Write commands.
Also see that the string is split at \emph{each} \code{separator},
even if that produces empty strings.

\index{IntsFromString1}\index{index!parallel arrays}\phantomsection\label{onedim:ints-from-string1}
\code{Split} is useful for parsing a line with several parts.  You might get a group of
integers on a line of text, for instance from:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string} \PYG{n}{input} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}
   \PYG{l+s}{\PYGZdq{}Please enter some integers, separated by single spaces: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

To extract the numbers, you want to the separate the entries in the string
with \code{Split}, \emph{and} you probably want further processing:
If you want them as integers, not strings, you must convert each one separately.

It is useful to put this idea in a function.
See the type returned.  It is an array \code{int{[}{]}} for the int results:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return ints taken from space separated integers in a string.}
\PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{IntsFromString1}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{input}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{integers} \PYG{p}{=} \PYG{n}{input}\PYG{p}{.}\PYG{n}{Split}\PYG{p}{(}\PYG{l+s+sc}{\PYGZsq{} \PYGZsq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{n}{integers}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{]}\PYG{p}{;}
   \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)}
      \PYG{n}{data}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{integers}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
   \PYG{k}{return} \PYG{n}{data}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

In a call to \code{IntsFromString1("2 5 22")},  \code{integers} would be
an array containing strings \code{"2"}, \code{"5"}, and \code{"22"}.
We need the conversions to \code{int} to go in a new array that we call \code{data}.
We must set its length, which will clearly be the same as for \code{integers},
\code{integers.Length}.
To assign elements into \code{data} we need a loop providing indices,
like the \code{for} loop provided.  Then for each index, we parse a
string in \code{integers} into an \code{int},
and place the \code{int} in the corresponding location in \code{data}.  We need to return
\code{data} at the end to make it accessible to the caller.

Again we use the basic pattern for returning an array.

Dealing with arrays is hard for many students for several reasons:
\begin{itemize}
\item {} 
You have new array declaration and creation syntax.

\item {} 
Array are compound objects, so there is a lot to think about.

\item {} 
Loops are hard for many people, and you almost always deal with loops.

\item {} 
You usually must deal with index variables, and there are many
patterns.

\end{itemize}

The last point is significant,
so it is important to note the special pattern in the example above:

\begin{notice}{note}{Note:}
The use of the same index variable for more than one array is
a standard way to have
\emph{related} entries in \emph{corresponding} positions in the arrays.
\end{notice}

We will introduce a refinement of this function in the
{\hyperref[onedim:intsfromstring-exercise]{\emph{IntsFromString Exercise}}}.  It will rely on a more complicated
index-handling pattern.


\subsubsection{NewUpper Exercise}
\label{onedim:new-upper}\label{onedim:newupper-exercise}
Complete the definition for

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return an array that is the same as data}
      \PYG{c+c1}{/// except all strings are in upper case.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{NewUpper}\PYG{p}{(}\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
\end{Verbatim}

and write a \code{Main} driver to demonstrate it.  Use the example function
{\hyperref[onedim:printstrings]{\emph{PrintStrings}}} in your demonstration.

\index{alias}

\subsection{References and Aliases}
\label{onedim:alias}\label{onedim:index-11}\label{onedim:references-and-aliases}
Object variables, like arrays, are references,
and this has important implications for
assignment.

With a primitive type like an \code{int}, an assignment copies the data:

{\hfill\includegraphics[width=132.75pt]{intCopy.png}\hfill}

In the diagram, the contents of the memory box labeled \code{b} is copied to the
memory box labeled \code{d}. The value of \code{d} starts off equal to the value of \code{b},
but can later be changed independently.

Contrast an assignment with arrays.  The value that is copied is the \emph{reference},
not the array data itself, so both end up pointing at the \emph{same}  actual array:

{\hfill\includegraphics[width=433.5pt]{arrayAlias.png}\hfill}

Hereafter, array assignments like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{b}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]} \PYG{p}{=} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{;}
\PYG{n}{d}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{5}\PYG{l+m}{5}\PYG{p}{;}
\end{Verbatim}

would both change the \emph{same} array.  Now \code{b} and \code{d} are essentially
names for the same thing (the actual array).  The technical term matches English:
The names are \emph{aliases}.

This may seem like a pretty silly discussion.   Why bother to give two different
names to the same object?  Isn't one enough?  In fact it is very important
in function/method calls.  An array reference can be passed as an actual value,
and it is the array \emph{reference} that is copied to the formal parameter, so
the formal parameter name is an \textbf{alias} for the actual parameter name.

\begin{notice}{note}{Note:}
If an array passed as a parameter to a method has elements changed in the
method, then the change affects the actual parameter array.
The change \emph{remains} in the actual parameter array \emph{after}
the method has terminated.
\end{notice}

\index{example!Scale}\index{Scale example}\index{array!parameter}
For example, consider the following function:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// Modify a by multiplying all elements by multiplier.}
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Scale}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{multiplier}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{a}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{n}{a}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{*}\PYG{p}{=} \PYG{n}{multiplier}\PYG{p}{;}  \PYG{c+c1}{// or:  a[i] = a[i] * multiplier}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The fragment:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{nums} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{4}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{n}{Scale}\PYG{p}{(}\PYG{n}{nums}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

would \emph{change} nums, so it ends up containing elements 10, 20, and 5.


\subsubsection{AllToUpper Exercise}
\label{onedim:all-to-upper}\label{onedim:alltoupper-exercise}
Complete the function with this heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Modifiy the array data so}
      \PYG{c+c1}{///   all strings are in upper case.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{AllToUpper}\PYG{p}{(}\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
\end{Verbatim}

Write a \code{Main} method to demonstrate it.  Use the example function
{\hyperref[onedim:printstrings]{\emph{PrintStrings}}} to show off your result.

\index{array!anonymous initialization}

\subsection{Anonymous Array Initialization}
\label{onedim:anonymous-array-initialization}\label{onedim:id2}\label{onedim:index-13}
Sometimes you only want to use an array with specific values
as a parameter to a function.  You could write something like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{temp} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{7}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{n}{SomeFunc}\PYG{p}{(}\PYG{n}{temp}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

but if \code{temp} is never going to be referenced again, you can
do this without using a name:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{SomeFunc}\PYG{p}{(}\PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{p}{\PYGZob{}}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{7}\PYG{p}{\PYGZcb{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

Like with the use of \code{var}, the compiler can infer the type of the array, and the
last example could be shortened to

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{SomeFunc}\PYG{p}{(}\PYG{k}{new}\PYG{p}{[}\PYG{p}{]} \PYG{p}{\PYGZob{}}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{7}\PYG{p}{\PYGZcb{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

It is essential to include the \code{new int{[}{]}} or \code{new{[}{]}}
\emph{in addition to}  the \code{\{3, 1, 7\}}.

Such an approach could also be used if you want to return a fixed
length array, where you have values for each parts, as in:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{minVal} \PYG{p}{=} \PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
\PYG{k+kt}{int} \PYG{n}{maxVal} \PYG{p}{=} \PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
\PYG{c+c1}{// ...}
\PYG{k}{return} \PYG{k}{new}\PYG{p}{[}\PYG{p}{]} \PYG{p}{\PYGZob{}}\PYG{n}{minVal}\PYG{p}{,} \PYG{n}{maxVal}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\end{Verbatim}


\subsubsection{Testing NewUpper Exercise/Example}
\label{onedim:testing-newupper-exercise-example}
Elaborate {\hyperref[onedim:new-upper]{\emph{NewUpper Exercise}}} so your \code{Main} method calls
\code{NewUpper} with an anonymous array as part of the demonstration.

You can see our code for all the string array exercises in example project
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/string\_array/string\_array.cs}{string\_array/string\_array.cs}, and with the \code{Main}
demonstration method in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/string\_array/string\_array\_demo.cs}{string\_array/string\_array\_demo.cs}.

\index{OOP!default value}\index{default value in instance}

\subsection{Default Initializations}
\label{onedim:default-initializations}\label{onedim:default-fields}\label{onedim:index-14}
Did you notice that when the first example array of integers was created,
it was filled with zeros?  It is a safety feature of C\# that the internal fields
of objects always get a specific value, not random data.  Here are the defaults:


\begin{threeparttable}
\capstart\caption{Default Values}

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Type
} & \textsf{\relax 
Value
}\\
\hline
primitive numeric types
 & 
0
\\
\hline
bool
 & 
false
\\
\hline
all object types
 & 
null
\\
\hline\end{tabulary}

\end{threeparttable}


\begin{notice}{warning}{Warning:}
An array with elements of object type, like \code{string{[}{]}},
without a specific initializer,
gets initialized to  all \code{null} values.  The creation is totally
legal, but if you try to use the created value, like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{words} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{string}\PYG{p}{[}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{words}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;}  \PYG{c+c1}{// run time error here}
\end{Verbatim}

The error is because \code{null} is not an object - it does not have a \code{Length}
property.  If, for example,
you want an array of empty strings you would need to initialize it with
a loop:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{words} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{string}\PYG{p}{[}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{;}
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{words}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{words}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}
\end{notice}


\subsection{Array Examples and Exercises}
\label{onedim:array-examples-and-exercises}
\index{index!variable not in loop heading}\index{example!remove\_zeros.cs}
We have been using array index variables all though this chapter.
We have been getting you started in situations where
they all just advanced continually in a
\code{for} loop heading.  The fanciest situations have been where the same index
is used to reference more than one array in parallel.

Now that you have some experience,
this section will include a variety of exercises where array index
variables need to be manipulated in fancier ways.  Consider this heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a new array with all the 0\PYGZsq{}s that are in}
      \PYG{c+c1}{/// data removed.  If data contains 0, 3, 0, 0, 5, 9}
      \PYG{c+c1}{/// then an array containing 3, 5, 9 is returned. }
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{NoZeros}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
\end{Verbatim}

We have a starting array \code{data} and we need to create an ending array,
but the corresponding nonzero data is \emph{not}
at corresponding index values in \code{data}!

Since we are returning a new array, we need to create it, and for that
we need a length.  How would you do that by hand?
Go through the original array, look at individual elements, and count the nonzero
ones.  We can do a counting loop Say we put our count into the variable
\code{countNonZero}. Then create a new \code{int} array, say \code{notzero},  with the
proper length.

The next part is new.  Clearly we need to get non-zero values from the original array
\code{data} and put them in the other array, \code{notzero}.
As we said, the array indices are
not in sync.  That means we are going to need to deal with their indices
separately: The index in \code{data} is not going to relate directly to the
index in \code{notzero}.

We could just have a separate index variable for each array.
Think about \code{data}:
We do want to go through it sequentially, and we are only \emph{reading} the
sequential values, so we can actually use a \code{foreach} loop and not
keep track of that index directly at all!

On the other hand we need to assign values \emph{into} \code{notzero}, and hence we will
need to refer to an index variable for \code{notzero},
say \code{i}.

However, we cannot just assign the index values in a
\code{for} loop heading as we have been before!
We have to be more careful and think when and how does \code{i} change?

This might be a good place to do this by hand, for instance with the sample
data in the function documentation.  Keep track of what \code{i}
should be as you iterate through the elements of \code{data}, one step at a time:
How do you change
\code{i} and when?  You are \emph{encouraged} to stop and actually do this manually,
on paper, and think before going on....

You should see that:
\begin{itemize}
\item {} 
We start by being ready to fill the place at index 0 in \code{notzero}.

\item {} 
We only copy a non-zero element of \code{data}, so we need an \code{if}
statement in the body again.

\item {} 
Each such non-zero number
is placed after the last number we copied into \code{notzero}.

\item {} 
This means that each time we copy an element to \code{notzero} we advance \code{i}!

\end{itemize}

If you get those ideas together, hopefully you can write the needed code.
Our version is:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Return a new array with all the 0\PYGZsq{}s that are in}
      \PYG{c+c1}{/// data removed.  If data contains 0, 3, 0, 0, 5, 9}
      \PYG{c+c1}{/// then an array containing 3, 5, 9 is returned. }
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{NoZeros}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{countNonZero} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
         \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n} \PYG{k}{in} \PYG{n}{data}\PYG{p}{)} \PYG{p}{\PYGZob{}}  \PYG{c+c1}{//find new length}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{n} \PYG{p}{!}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{countNonZero}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{notzero} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{n}{countNonZero}\PYG{p}{]}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}  \PYG{c+c1}{// index where to put the next value}
         \PYG{k}{foreach}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n} \PYG{k}{in} \PYG{n}{data}\PYG{p}{)} \PYG{p}{\PYGZob{}} 
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{n} \PYG{p}{!}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{c+c1}{// copy non\PYGZhy{}zero elements}
               \PYG{n}{notzero}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=} \PYG{n}{n}\PYG{p}{;}
               \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{notzero}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Adding a \code{Main} demostration method, you get our full example
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/remove\_zeros/remove\_zeros.cs}{remove\_zeros/remove\_zeros.cs}.


\subsubsection{Initialization Exercise}
\label{onedim:initialization-exercise}\begin{enumerate}
\item {} 
In the \code{NoZeros{}` function above,
what are the values in the array {}`{}`notzero} just after
line 12 is executed?

\item {} 
In the {\hyperref[onedim:new-upper]{\emph{NewUpper Exercise}}}  or our version of \code{NewUpper} in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/string\_array/string\_array\_demo.cs}{string\_array/string\_array\_demo.cs}
consider the execution of the \code{NewUpper} function
immediately after you first create
the string array that you are going to later return.
Right then, what are the element values in that array?

\end{enumerate}

\index{exercise!ExtractItems}\index{ExtractItems exercise}

\subsubsection{ExtractItems Exercise}
\label{onedim:index-16}\label{onedim:extractitems-exercise}
A string intended to indicate a sequence of items could be like in the
discussion  above of {\hyperref[onedim:ints-from-string1]{\emph{IntsFromString1}}}.
As illustrated there, individual items
are separated out neatly with \code{Split}.  If you want to act on a user-generated
string, it is probably better to allow more leeway:
Commas are often used to separate items or comma with blank, or several blanks.

In this exercise write a version that will accept all those variations
and return an array of non-empty strings, without the commas or blanks.
Complete this function:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return an array of non\PYGZhy{}empty strings that are separated}
\PYG{c+c1}{/// in the original string by any combination of commas and blanks.}
\PYG{c+c1}{/// Example:  ExtractItems(\PYGZdq{}  extra  spaces,plus,  more, \PYGZdq{}) returns an}
\PYG{c+c1}{/// array containing \PYGZob{}\PYGZdq{}extra\PYGZdq{}, \PYGZdq{}spaces\PYGZdq{}, \PYGZdq{}plus\PYGZdq{}, \PYGZdq{}more\PYGZdq{}\PYGZcb{}}
\PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{ExtractItems}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
\end{Verbatim}

Hints: It is possible to deal with more than one separator character, but
the simplest thing likely is to use string method \code{Replace}
and just replace all the
commas by spaces.  If you then \code{Split} on each space you get all the non-empty
strings that you want \emph{and} maybe a number of
empty strings.  You need to create a final array with just the nonempty
strings from the split.  When you create the array to be returned,
you need know its size.  Then populate it
with just the nonempty string pieces.
Handling the indices for the new array also adds complication.


\subsubsection{IntsFromString Exercise}
\label{onedim:id3}\label{onedim:intsfromstring-exercise}
Write a function
\code{IntsFromString} with a corresponding signature and intent
like {\hyperref[onedim:ints-from-string1]{\emph{IntsFromString1}}}, but make it
more robust by allowing all the separator combinations of
\code{ExtractItems} from the last exercise, so
\code{IntsFromString(" 2, 33  4,55 6 77  ")} returns an array containing \code{int}
values 2, 33, 4, 55, 6, 77.  (Don't reinvent the wheel: call \code{ExtractItems}.)
Also write a \code{Main} function so you can demonstrate the use of
\code{IntsFromString}.

\index{exercise!TrimAll for arrays}\index{TrimAll exercise}

\subsubsection{Trim All Exercise}
\label{onedim:index-17}\label{onedim:id4}\label{onedim:trim-all-exercise}
Write a program \code{trimmer.cs} that includes and tests a
function with heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// Trim all elements of a and replace them in the array.}
\PYG{c+c1}{//  Example: If a contains \PYGZob{}\PYGZdq{} is  \PYGZdq{}, \PYGZdq{} it\PYGZdq{}, \PYGZdq{}trimmed?   \PYGZdq{}\PYGZcb{}}
\PYG{c+c1}{//  then after the function call the array contains}
\PYG{c+c1}{//  \PYGZob{}\PYGZdq{}is\PYGZdq{}, \PYGZdq{}it\PYGZdq{}, \PYGZdq{}trimmed?\PYGZdq{}\PYGZcb{}.}
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{TrimAll}\PYG{p}{(}\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
\end{Verbatim}

\index{exercise!Dups}\index{Dups exercise for arrays}

\subsubsection{Count Duplicates Exercise}
\label{onedim:dups-exercise}\label{onedim:index-18}\label{onedim:count-duplicates-exercise}
Write a program \code{count\_dups.cs} that includes and tests a
function with heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// Return the number of duplicate pairs in an array a.}
\PYG{c+c1}{// Example: for elements 2, 5, 1, 5, 2, 5}
\PYG{c+c1}{// the return value would be 4 (one pair of 2\PYGZsq{}s three pairs of 5\PYGZsq{}s.}
\PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{dups}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
\end{Verbatim}

\index{exercise!Mirror}\index{Mirror exercise for arrays}

\subsubsection{Mirror Array Exercise}
\label{onedim:index-19}\label{onedim:mirror-array-exercise}\label{onedim:mirror-exercise}
Write a program \code{make\_mirror.cs} that includes and tests a
function with heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// Create a new array with the elements of a in the opposite order.}
\PYG{c+c1}{// \PYGZob{}\PYGZdq{}aA\PYGZdq{}, \PYGZdq{}bB\PYGZdq{}, \PYGZdq{}cC\PYGZdq{}\PYGZcb{} produces a new array \PYGZob{}\PYGZdq{}cC\PYGZdq{}, \PYGZdq{}bB\PYGZdq{}, \PYGZdq{}aA\PYGZdq{}\PYGZcb{}}
\PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{Mirror}\PYG{p}{(}\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
\end{Verbatim}

\index{exercise!Reverse for arrays}\index{Reverse exercise for arrays}

\subsubsection{Reverse Array Exercise}
\label{onedim:index-20}\label{onedim:reverse-exercise}\label{onedim:reverse-array-exercise}
Write a program \code{reverse\_array.cs} that includes and tests a
function with heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// Reverse the order of array elements}
\PYG{c+c1}{// If array a first contains \PYGZdq{}aA\PYGZdq{}, \PYGZdq{}bB\PYGZdq{}, \PYGZdq{}cC\PYGZdq{},}
\PYG{c+c1}{// than it ends up containing \PYGZdq{}cC\PYGZdq{}, \PYGZdq{}bB\PYGZdq{}, \PYGZdq{}aA\PYGZdq{}.}
\PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Reverse}\PYG{p}{(}\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
\end{Verbatim}

Do this \emph{without} creating a second array.  (There is a
trick here.)

\index{exercise!Histogram}\index{Histogram exercise}

\subsubsection{Histogram Exercise}
\label{onedim:index-21}\label{onedim:histogram-exercise}\label{onedim:id5}
Write a program \code{make\_histogram.cs} that includes and tests a
function with heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// Return a histogram array counting repetitions of values}
\PYG{c+c1}{// start through end in array a.  The count for value start+i}
\PYG{c+c1}{// is at index i of the returned array, starting at i == 0.}
\PYG{c+c1}{// For example:}
\PYG{c+c1}{// Histogram(new int[]\PYGZob{}2, 0, 3, 5, 3, 5\PYGZcb{}, 2, 5) counts how}
\PYG{c+c1}{// many times the numbers 2 through 5, inclusive, occur in}
\PYG{c+c1}{// the original array, and returns a new array containing}
\PYG{c+c1}{// \PYGZob{}1, 2, 0, 2\PYGZcb{}, that is, 1 2, 2 3\PYGZsq{}s, 0 4\PYGZsq{}s, and 2 5\PYGZsq{}s. The}
\PYG{c+c1}{// count of 2\PYGZsq{}s appears as the first (0th) element of the}
\PYG{c+c1}{// returned array, the count of 3\PYGZsq{}s as the second, etc.}
\PYG{c+c1}{// Similarly, Histogram(new int[]\PYGZob{}2, 0, 3, 5, 3, 5\PYGZcb{}, \PYGZhy{}1, 1)}
\PYG{c+c1}{// returns the new array \PYGZob{}0, 1, 0\PYGZcb{},}
\PYG{c+c1}{// that is, 0 \PYGZhy{}1\PYGZsq{}s, 1 0, and 0 1\PYGZsq{}s.}
\PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{Histogram}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{start}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{end}\PYG{p}{)}
\end{Verbatim}

This problem clearly requires you to loop through all the elements of
array \code{a}.  You should \emph{not} need any further nested loop.


\subsubsection{Histogram Interval Exercise}
\label{onedim:histogram-interval-exercise}\label{onedim:id6}
This is a slight elaboration of the previous problem, where
you count entries in intervals, not just of width 1.

Write a program \code{make\_histogram2.cs} that includes and tests a
function with heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{// Return a histogram array counting repetitions of values}
\PYG{c+c1}{// in array a in the n half\PYGZhy{}open intervals [start, start + width),}
\PYG{c+c1}{// [start+width, start+2*width), ... [}
\PYG{c+c1}{// [start + (n\PYGZhy{}1)*width, start + n*width) .  The counts for}
\PYG{c+c1}{// each of the n intervals, in order, goes in the returned array}
\PYG{c+c1}{// of length n.  For example}
\PYG{c+c1}{// Histogram(new[]\PYGZob{}89, 69, 100, 83, 99, 81\PYGZcb{}, 60, 10, 5)}
\PYG{c+c1}{// would return an array containing counts 1, 0, 3, 1, 1,}
\PYG{c+c1}{// for 1 in sixties, 0 in seventies, 3 in eighties, 1 in nineties,}
\PYG{c+c1}{// and 1 in range 100 through 109.}
\PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{HistogramIntervals}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{start}\PYG{p}{,}
                                       \PYG{k+kt}{int} \PYG{n}{width}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
\end{Verbatim}

The previous exercise version \code{Histogram(a, start, end)}
would return the same
result as \code{HistogramIntervals(a, start, 1, end-start+1)}.

Again, the only loop needed should be to process each element of \code{a}.

\index{exercise!power table 2}

\subsubsection{Power Table Exercise 2}
\label{onedim:power-table-exercise-2}\label{onedim:index-22}\label{onedim:power-table-exercise2}
Write a program \code{power\_table2.cs{}`} producing a table much
like {\hyperref[forexamples:power-table-exercise]{\emph{Power Table Exercise}}}, with right-justified columns,
but this time make each separate column have the minimum width
necessary - so there is a single space (and no less)
in front of some entry in
\emph{each} column, except the first.
Be careful: take the heading widths into account; the
parameter limits are important, too; test them:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Print a table of powers of positive integers.}
\PYG{c+c1}{/// Assume 1 \PYGZlt{}= nMax \PYGZlt{}= 14, 1 \PYGZlt{}= powerMax \PYGZlt{}= 10}
\PYG{c+c1}{/// Example: output of PowerTable(4, 5)}
\PYG{c+c1}{/// n\PYGZca{}1 n\PYGZca{}2 n\PYGZca{}3 n\PYGZca{}4  n\PYGZca{}5}
\PYG{c+c1}{///   1   1   1   1    1}
\PYG{c+c1}{///   2   4   8  16   32}
\PYG{c+c1}{///   3   9  27  81  243}
\PYG{c+c1}{///   4  16  64 256 1024}
\PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PowerTable}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{nMax}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{powerMax}\PYG{p}{)}
\end{Verbatim}


\section{Musical Scales and Arrays}
\label{music:musical-scales-and-arrays}\label{music::doc}
Music in the western classical tradition uses a twelve-tone \emph{chromatic}
scale. Any of the tones in this scale can be the basis of a major scale.
Most musicians (especially pianists) learn the C-major scale in the early
days of study, owing to the ability to play this scale entirely with the
ivory (white) keys.

The following declaration shows how to initialize an array consisting
of the twelve tones of the chromatic scale, starting from the C note.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{static} \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{tones} \PYG{p}{=} \PYG{p}{\PYGZob{}} \PYG{l+s}{\PYGZdq{}C\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}C\PYGZsh{}\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}D\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}D\PYGZsh{}\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}E\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}F\PYGZdq{}}\PYG{p}{,}
         \PYG{l+s}{\PYGZdq{}F\PYGZsh{}\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}G\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}G\PYGZsh{}\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}A\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}A\PYGZsh{}\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}B\PYGZdq{}} \PYG{p}{\PYGZcb{}}\PYG{p}{;}
\end{Verbatim}

Even if you're not a musician, learning the basic principles is fairly
straightforward.

The well-known C-major scale, which is often sung as:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Do} \PYG{n}{Re} \PYG{n}{Mi} \PYG{n}{Fa} \PYG{n}{So} \PYG{n}{La} \PYG{n}{Ti} \PYG{n}{Do}
\end{Verbatim}

has the following progression:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{C}  \PYG{n}{D}  \PYG{n}{E}  \PYG{n}{F}  \PYG{n}{G}  \PYG{n}{A}  \PYG{n}{B}  \PYG{n}{C}
\end{Verbatim}

This progression is known as the \emph{diatonic major} scale. If you look at
the \code{tones} array, you can actually figure out the intervals associated
with this array:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{C} \PYG{p}{+} \PYG{l+m}{2} \PYG{p}{=} \PYG{n}{D}
\PYG{n}{D} \PYG{p}{+} \PYG{l+m}{2} \PYG{p}{=} \PYG{n}{E}
\PYG{n}{E} \PYG{p}{+} \PYG{l+m}{1} \PYG{p}{=} \PYG{n}{F}
\PYG{n}{F} \PYG{p}{+} \PYG{l+m}{2} \PYG{p}{=} \PYG{n}{G}
\PYG{n}{G} \PYG{p}{+} \PYG{l+m}{2} \PYG{p}{=} \PYG{n}{A}
\PYG{n}{A} \PYG{p}{+} \PYG{l+m}{2} \PYG{p}{=} \PYG{n}{B}
\PYG{n}{B} \PYG{p}{+} \PYG{l+m}{1} \PYG{p}{=} \PYG{n}{C}
\end{Verbatim}

So given any starting note, the major scale can be \emph{generated} from the
intervals (represented as an array).

So, for example, if you want the F-major scale, you can get it by starting
at F and applying the steps of 2, 2, 1, 2, 2, 2, 1:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
F + 2 = G
G + 2 = A
A + 1 = B\PYGZsq{} (flat) a.k.a. A\PYGZsh{})
B\PYGZsq{}+ 2 = C
C + 2 = D
D + 2 = E
E + 1 = F
\end{Verbatim}

So this is the F-major scale:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
F G A B\PYGZsq{} C D E F
\end{Verbatim}

We begin by creating a helper function, \code{FindTone()}, which does a
linear search to find the key of the scale we want to compute. The
aim is to make it easy for the user to just specify the key of interest.
Then we can use this position to compute the scale given the major
(or minor, covered shortly) interval array.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{FindTone}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{key}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{tones}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{key} \PYG{p}{=}\PYG{p}{=} \PYG{n}{tones}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}
               \PYG{k}{return} \PYG{n}{i}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

To see what this function does, pick your favorite key (C and G are very
common for beginners).
\begin{itemize}
\item {} 
\code{FindTone("C")} gives 0, the first position in the \code{tones} array.

\item {} 
\code{FindTone("G")} gives 8.

\end{itemize}

For example,
C is the first note in the array of tones, so \code{FindTone("C")} would give
us 0. \code{FindTone("F")} would give us 6.

So let's take a look at \code{ComputeScale()} which does the work of
computing a scale, given a key and an array of steps. The scale array
is allocated by the \code{Main()} method, primarily to allow the same
array to be used repeatedly for calculating other scales.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{ComputeScale}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{key}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{steps}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{scale}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{tonePosition} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{startTone}\PYG{p}{;}

         \PYG{n}{startTone} \PYG{p}{=} \PYG{n}{FindTone}\PYG{p}{(}\PYG{n}{key}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{startTone} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)}
            \PYG{k}{return}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{steps}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{+}\PYG{l+m}{1} \PYG{p}{!}\PYG{p}{=} \PYG{n}{scale}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{)}
            \PYG{k}{return}\PYG{p}{;}
         \PYG{n}{tonePosition} \PYG{p}{=} \PYG{n}{startTone}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{steps}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{scale}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=} \PYG{n}{tonePosition} \PYG{p}{\PYGZpc{}} \PYG{n}{tones}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{tonePosition} \PYG{p}{+}\PYG{p}{=} \PYG{n}{steps}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}
\begin{enumerate}
\item {} 
The first thing to note is the \emph{setup} of this code. We're going to
keep the \code{startTone} (obtained by calling \code{FindTone()}) and
\code{tonePosition}, which is the note we are presently visiting in
the \code{tones} array.

\item {} 
Remember that every scale (e.g. C, D, F\#, etc.) can always be
obtained by looking at \code{tones} and using the appropriate
intervals (the \code{steps} parameter) to compute the next note, given
a current note.

\item {} 
We do some simple checks in line 6 (to ensure that a valid key
was specified by the caller) and in line 8 to ensure that the
number of steps + 1 is the length of the scale--and the length
of the scale is 8. (We technically don't have to limit the scale
to 8, because scales can keep going until you run out of playable
notes on the instrument.)

\item {} 
We'll now start at the initial position (where we found the base
note of the key) and enter a for loop to compute all of the notes
in the scale. This loop iterates over the entries in the \code{steps}
array to decide what the next note is.

\item {} 
The next note in the scale, \code{scale{[}i{]}} is computed by taking
\code{tonePosition \% tones.GetLength(0)}. We need to do this, because
in most scales, you will eventually end up ``falling off the end''
of the \code{tones} array, which mens that you need to continue
computing notes from the \emph{beginning} of the array. You can inspect
this for yourself by picking a scale (say, B) that is starting at
the end of the \code{tones} array. This means you will need to go
to the beginning of the array to get C\# (which is 2 tones away
from B).

\item {} 
The next note is found by adding \code{steps{[}i{]}} to \code{tonePosition}.

\end{enumerate}

The following function writes the scale out (rather naively) by just
printing the notes from our existing \code{tones} array.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{WriteScale}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{scale}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{k}{in} \PYG{n}{scale}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} \PYGZdq{}}\PYG{p}{,} \PYG{n}{tones}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

We say that the output is \emph{naive} because any musician will tell you
that a scale should be printed in a normalized way. For example, the F-major
scale (shown above in our earlier explanation) is never written with A\# as
one of its notes. It is written as B-flat. It's easy to manage the various
cases by consulting the circle of fifths, which gives us guidance on the
number of flats/sharps each scale has.

Lastly, we put this all together.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main} \PYG{p}{(}\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{args}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{scale} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{8}\PYG{p}{]}\PYG{p}{;} 
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{major} \PYG{p}{=} \PYG{p}{\PYGZob{}} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{1} \PYG{p}{\PYGZcb{}}\PYG{p}{;}
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{minor} \PYG{p}{=} \PYG{p}{\PYGZob{}} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{2} \PYG{p}{\PYGZcb{}}\PYG{p}{;}

         \PYG{k+kt}{string} \PYG{n}{name} \PYG{p}{=} \PYG{n}{args}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{;}  \PYG{c+c1}{// need command line tone name}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} major scale\PYGZdq{}}\PYG{p}{,} \PYG{n}{name}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{ComputeScale}\PYG{p}{(}\PYG{n}{name}\PYG{p}{,} \PYG{n}{major}\PYG{p}{,} \PYG{n}{scale}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{WriteScale}\PYG{p}{(}\PYG{n}{scale}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} minor scale\PYGZdq{}}\PYG{p}{,} \PYG{n}{name}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{ComputeScale}\PYG{p}{(}\PYG{n}{name}\PYG{p}{,} \PYG{n}{minor}\PYG{p}{,} \PYG{n}{scale}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{WriteScale}\PYG{p}{(}\PYG{n}{scale}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

This \code{Main()} method shows how to set up the steps for both major
and minor scales. We've already explained how to express the steps of
a major scale. The minor scale basically drops the 3rd and 7th by a
semitone (a single step), which gives us a different pattern.

You can run this program to see the major and minor scales.


\section{Linear Searching}
\label{searching:linear-searching}\label{searching::doc}\label{searching:searching}
In this section, we'll take a look at how to search for a value in an
array.  Although a fairly straightforward topic, it is one that comes
up repeatedly in programming.

\index{algorithms!linear search}\index{search!linear}\index{linear search}

\subsection{Linear Search}
\label{searching:index-0}\label{searching:linear-search}
By far, one of the most common searches you will see in typical
programs. It also happens to be one of the more \emph{misused} searches,
which is another reason we want you to know about it.

Here is the code from example \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/searching/searching.cs}{searching/searching.cs}
to perform a linear search for an integer in an
array:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Return the index of the first position in data}
      \PYG{c+c1}{/// where item appears, or \PYGZhy{}1 if item does not appear.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{IntArrayLinearSearch}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{item}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{N}\PYG{p}{=}\PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{N}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{data}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{n}{item}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{k}{return} \PYG{n}{i}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Here's what it does:
\begin{itemize}
\item {} 
In lines 5-6 we set up a loop to go from 0 to N-1. We often use N
to indicate the size of the array (and it's much easier to type
than \code{data.Length}.

\item {} 
In line 7, we see whether we found a match for the item we are searching.
If we find the match, we immediately leave the loop by returning the
position where it was found.

\item {} 
It is worth noting here that the array, \code{data}, may or my not
be in sorted order. So our search reports the first location where
we found the value. It is entirely possible that the more than
one position in the array contains the matching value. If you
wanted to find the next one, you could modify the \code{IntArrayLinearSearch()}
method to have a third parameter, \code{start}, that allows us
to continue searching from where we left off. It might look
something like the following:

\end{itemize}

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Return the first index \PYGZgt{}= start in data where}
      \PYG{c+c1}{/// item appears, or \PYGZhy{}1 if item does not appear there.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{IntArrayLinearSearch}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{item}\PYG{p}{,} 
                                             \PYG{k+kt}{int} \PYG{n}{start}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{N}\PYG{p}{=}\PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{start} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{return} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{n}{start}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{N}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{data}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{n}{item}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{k}{return} \PYG{n}{i}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}                               
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The following code in \code{Main} of \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/searching/searching\_demo.cs}{searching/searching\_demo.cs}
demonstrates how to use the linear search:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
         \PYG{k+kt}{string} \PYG{n}{input} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}
           \PYG{l+s}{\PYGZdq{}Please enter integers, separated by spaces and/or comma: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data} \PYG{p}{=} \PYG{n}{ExtractFromString}\PYG{p}{.}\PYG{n}{IntsFromString}\PYG{p}{(}\PYG{n}{input}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}data[\PYGZob{}0\PYGZcb{}]=\PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{i}\PYG{p}{,} \PYG{n}{data}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k+kt}{string} \PYG{n}{prompt} \PYG{p}{=} 
            \PYG{l+s}{\PYGZdq{}Please enter a number to find (blank line to end): \PYGZdq{}}\PYG{p}{;}
         \PYG{n}{input} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{input}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{int} \PYG{n}{searchItem} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{input}\PYG{p}{)}\PYG{p}{;}
            \PYG{k+kt}{int} \PYG{n}{searchPos} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptIntInRange}\PYG{p}{(}
               \PYG{l+s}{\PYGZdq{}At what position should the search start? \PYGZdq{}}\PYG{p}{,}
               \PYG{l+m}{0}\PYG{p}{,} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;}
            \PYG{k+kt}{int} \PYG{n}{foundPos} \PYG{p}{=} 
               \PYG{n}{Searching}\PYG{p}{.}\PYG{n}{IntArrayLinearSearch}\PYG{p}{(}\PYG{n}{data}\PYG{p}{,}\PYG{n}{searchItem}\PYG{p}{,} \PYG{n}{searchPos}\PYG{p}{)}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{foundPos} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Item \PYGZob{}0\PYGZcb{} not found\PYGZdq{}}\PYG{p}{,} \PYG{n}{searchItem}\PYG{p}{)}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}} 
            \PYG{k}{else} \PYG{p}{\PYGZob{}}
               \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Item \PYGZob{}0\PYGZcb{} found at position \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} 
                  \PYG{n}{searchItem}\PYG{p}{,} \PYG{n}{foundPos}\PYG{p}{)}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
            \PYG{n}{input} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
\end{Verbatim}

In this example, we ask the user to enter all the data for the array
on one line. To convert the string to an int array we
use the result of the {\hyperref[onedim:intsfromstring-exercise]{\emph{IntsFromString Exercise}}} that we put in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/searching/extract\_from\_string.cs}{searching/extract\_from\_string.cs}.

To allow easy termination of the testing loop, we do not use \code{PromptInt}
for \code{searchItem}, because any
\code{int} could be the search target.  By using \code{PromptLine}, we can allow an empty
string as the response, and we test for that to terminate the loop.

The rest is mostly self-explanatory.

\index{PF4}\index{recursion}\index{SP1}\index{history}\index{sorting}

\section{Sorting Algorithms}
\label{sorting:index-0}\label{sorting:sorting-algorithms}\label{sorting:sorting}\label{sorting::doc}
Sorting algorithms represent foundational knowledge that every computer scientist and
IT professional should at least know at a basic level. And it turns out to be a great
way of learning about why arrays are important.

In this section, we're going to take a look at a number of well-known sorting algorithms
with the hope of sensitizing you to the notion of \emph{performance}--a topic that is covered
in greater detail in courses such as algorithms and data structures.

This is not intended to be a comprehensive reference at all. The idea is to learn how
these classic algorithms are coded in the teaching language for this course, C\#, and to
understand the essentials of analyzing their performance, both theoretically and
experimentally. For a full theoretical treatment, we recommend the outstanding textbook
by Niklaus Wirth \phantomsection\label{sorting:id1}{\hyperref[sorting:wirthadp]{{[}WirthADP{]}}}, who invented the Pascal language. (We have also adapted
some examples from Thomas W. Christopher's \phantomsection\label{sorting:id2}{\hyperref[sorting:tcsortingjava]{{[}TCSortingJava{]}}} animated sorting algorithms
page.

The sorts and supporting functions are all in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sorting/sorting.cs}{sorting/sorting.cs}, but we start one bit at a time:

\index{exchanging array elements}\index{array!exchange elements}

\subsection{Exchanging Array Elements}
\label{sorting:index-1}\label{sorting:exchanging-array-elements}
We'll begin by introducing you to a simple method, whose only purpose in life is to
swap two data values at positions \code{m} and \code{n} in a given integer array:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Exchange the elements of data at indices m and n.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Exchange}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{m}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{temporary} \PYG{p}{=} \PYG{n}{data}\PYG{p}{[}\PYG{n}{m}\PYG{p}{]}\PYG{p}{;}
         \PYG{n}{data} \PYG{p}{[}\PYG{n}{m}\PYG{p}{]} \PYG{p}{=} \PYG{n}{data}\PYG{p}{[}\PYG{n}{n}\PYG{p}{]}\PYG{p}{;}
         \PYG{n}{data} \PYG{p}{[}\PYG{n}{n}\PYG{p}{]} \PYG{p}{=} \PYG{n}{temporary}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

For example if we have an array nums, shown with indices:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 nums: \PYGZhy{}1  8 11 22  9 \PYGZhy{}5  2
index:  0  1  2  3  4  5  6
\end{Verbatim}

Then after \code{Exchange(nums, 2, 5)} the array would look like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 nums: \PYGZhy{}1  8 \PYGZhy{}5 22  9 11  2
index:  0  1  2  3  4  5  6
\end{Verbatim}

In general, swapping two values in an array is
no different than swapping any two integers.
Suppose we have the following integers \code{a} and \code{b}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{;}
\PYG{k+kt}{int} \PYG{n}{t}\PYG{p}{;}

\PYG{n}{a} \PYG{p}{=} \PYG{l+m}{2}\PYG{l+m}{5}\PYG{p}{;}
\PYG{n}{b} \PYG{p}{=} \PYG{l+m}{3}\PYG{l+m}{5}\PYG{p}{;}
\PYG{n}{t} \PYG{p}{=} \PYG{n}{a}\PYG{p}{;}
\PYG{n}{a} \PYG{p}{=} \PYG{n}{b}\PYG{p}{;}
\PYG{n}{b} \PYG{p}{=} \PYG{n}{t}\PYG{p}{;}
\end{Verbatim}

After this code does its job, the value of \code{a} would be 35
and the value of \code{b} would be 25.

So in the \code{Exchange()} function above,
if we have two different array elements at positions \code{m} and \code{n},
we are basically getting each value at these positions,
e.g. \code{data{[}m{]}} and \code{data{[}n{]}} and treating them
as if they were \code{a} and \code{b} in the above code.

You might find it helpful at this time to verify that
the above code does what we're saying it does, and a
good way is to type it directly into the C\# interpreter (csharp)
so you can see it for yourself.

The \code{Exchange()} function is vital to all of the sorting algorithms in the following way.
It is used whenever two items are found to be out of order.
When this occurs, they will be \emph{swapped}. This doesn't mean
that the item comes to its final resting place in the array.
It just means that for the moment, the items
have been reordered so we'll get closer to having a sorted array.

Let's now take a look at the various sorting algorithms.

\index{sorting!bubble sort}\index{algorithms!bubble sort}\index{array!nested loop}\index{bubble sort}

\subsection{Bubble Sort}
\label{sorting:bubble-sort}\label{sorting:index-2}
The Bubble Sort algorithm works by repeatedly scanning
through the array exchanging adjacent elements that are out of order.  Watching
this work with a strategically-placed \code{Console.WriteLine()} in the outer
loop, you will see that the sorted array grows right to left. Each
sweep picks up the largest remaining element and moves to the right as
far as it can go. It is therefore not necessary to scan through the
entire array each sweep, but only to the beginning of the sorted
portion.

We define the number of \emph{inversions} as the number of element pairs that
are out of order. They needn't be adjacent. If \code{data{[}7{]} \textgreater{} data{[}16{]}},
that's an inversion. Every time an inversion is required,
we also say that there is corresponding data \emph{movement}. If you look at the
\code{Exchange()} code, you'll observe that a swap requires three movements
to take place, which happens very quickly on most processors but still amounts
to a significant cost.

There can be at most \(N \cdot \frac{N-1}{2}\) inversions in the
array of length \(N\). The maximum
number of inversions occurs when the array is sorted in reverse order
and has no equal elements.

Bubble Sort exchanges only adjacent elements.
Each such exchange removes precisely one inversion; therefore,
Bubble Sort requires \(O(N^2)\) exchanges.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{IntArrayBubbleSort} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{N} \PYG{p}{=} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{j}\PYG{p}{=}\PYG{n}{N}\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{;} \PYG{n}{j}\PYG{p}{\PYGZgt{}}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{j}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i}\PYG{p}{\PYGZlt{}}\PYG{n}{j}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{k}{if} \PYG{p}{(}\PYG{n}{data}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZgt{}} \PYG{n}{data}\PYG{p}{[}\PYG{n}{i} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{]}\PYG{p}{)} \PYG{p}{\PYGZob{}}
                  \PYG{n}{Exchange} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{i}\PYG{p}{,} \PYG{n}{i} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;}
               \PYG{p}{\PYGZcb{}}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{sorting!selection sort}\index{algorithms!selection sort}\index{nested loop}\index{selection sort}

\subsection{Selection Sort}
\label{sorting:selection-sort}\label{sorting:index-3}
The Selection Sort algorithm works to minimize the amount of data movement,
hence the number of \code{Exchange()} calls.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Among the indices \PYGZgt{}= start for data, }
      \PYG{c+c1}{/// return the index of the minimal element.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{IntArrayMin} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{start}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{N} \PYG{p}{=} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{,} \PYG{n}{minPos} \PYG{p}{=} \PYG{n}{start}\PYG{p}{;} 
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{pos}\PYG{p}{=}\PYG{n}{start}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{;} \PYG{n}{pos} \PYG{p}{\PYGZlt{}} \PYG{n}{N}\PYG{p}{;} \PYG{n}{pos}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{data}\PYG{p}{[}\PYG{n}{pos}\PYG{p}{]} \PYG{p}{\PYGZlt{}} \PYG{n}{data}\PYG{p}{[}\PYG{n}{minPos}\PYG{p}{]}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{minPos} \PYG{p}{=} \PYG{n}{pos}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{minPos}\PYG{p}{;} 
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{IntArraySelectionSort} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{N} \PYG{p}{=} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{N}\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{int} \PYG{n}{k} \PYG{p}{=} \PYG{n}{IntArrayMin}\PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{i}\PYG{p}{)}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{i} \PYG{p}{!}\PYG{p}{=} \PYG{n}{k}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{Exchange}\PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{i}\PYG{p}{,} \PYG{n}{k}\PYG{p}{)}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

It's a remarkably simple algorithm to explain. As shown in the code, the
actual sorting is done by a function, \code{IntArraySelectionSort()}, which
takes an array of data as its only parameter, like Bubble sort.
The way Selection Sort works is as follows:
\begin{enumerate}
\item {} 
An outer loop visits each item in the array to find out whether it is the
minimum of all the elements after it.
If it is not the minimum, it is going to be swapped with whatever
item in the rest of the array is the minimum.

\item {} 
We use a helper function,
\code{IntArrayMin()}
to find the position of the minimum value in the rest of the array.
This function has a parameter, \code{start} to indicate where
we wish to begin the search.
So as you can see from the loop in \code{IntArraySelectionSort()},
when we start with position \code{i}, and we compare to the later elements
from position \code{i + 1} to the end of the array, updating the position of the
smallest element so far.

\end{enumerate}

An illustration to accompany the discussion:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 data: 12  8 \PYGZhy{}5 22  9  2
index:  0  1  2  3  4  5
        i     k
\end{Verbatim}

The first time through the loop, \code{i} is 0, and \code{k} gets the value 2, since data{[}2{]}
is -5, the smallest element.  Those two positions get swapped.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 data: \PYGZhy{}5  8 12 22  9  2
index:  0  1  2  3  4  5
\end{Verbatim}

The next
time through the loop i is 1 and k becomes 5:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 data: \PYGZhy{}5  8 12 22  9  2
index:  0  1  2  3  4  5
           i           k
\end{Verbatim}

After the swap:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 data: \PYGZhy{}5  2 12 22  9  8
index:  0  1  2  3  4  5
\end{Verbatim}

and so on.  Here is the data after each of the last three swaps:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYGZhy{}5  2  8 22  9 12

\PYGZhy{}5  2  8  9 22 12

\PYGZhy{}5  2  8  9 12 22
\end{Verbatim}

Consider the first call to \code{IntArrayMin}.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 data: 12  8 \PYGZhy{}5 22  9  2
index:  0  1  2  3  4  5
\end{Verbatim}

Initially \code{minPos} is 0.  Here are the
changes for each value of \code{pos}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
pos=1:  8 = data[1] \PYGZlt{} data[0] = 12, so minPos becomes 1
pos=2: \PYGZhy{}5 = data[2] \PYGZlt{} data[1] = 8, so minPos becomes 2
pos=3: 22 = data[3] is not \PYGZlt{} data[2] = \PYGZhy{}5, so minPos still 2
pos=4:  9 = data[4] is not \PYGZlt{} data[2] = \PYGZhy{}5, so minPos still 2
pos=5:  2 = data[5] is not \PYGZlt{} data[2] = \PYGZhy{}5, so minPos still 2
\end{Verbatim}

and 2 gets returned, and we ge the swap

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 data: \PYGZhy{}5  8 12 22  9  2
index:  0  1  2  3  4  5
\end{Verbatim}

The next call to \code{IntArrayMin} has \code{start} as 1, so \code{minPos} is initially 1,
and we compare to the elements of data at index 2, 3, 4, and 5....

We won't do the full algorithmic analysis here. Selection Sort is interesting because
it does most of its work through \emph{comparisons}, with the same number of them no matter
how the data are ordered, exactly
\(N \cdot \frac{N-1}{2}\), which is
\(O(N^2)\) The
number of \emph{exchanges} is O(N). The comparisons are a non-trivial cost,
however, and do show
in our own performance experiments with randomly-generated data.

\index{Shuffle exercise}\index{exercise!Shuffle}

\subsubsection{Shuffle Exercise}
\label{sorting:index-4}\label{sorting:shuffle-exercise}
Complete the \code{Shuffle} function and add a \code{Main} method to test it:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Shuffle the elements of an array into random positions,}
\PYG{c+c1}{/// changing the array.  An array containing}
\PYG{c+c1}{/// 2, 5, 7, 7, 7, 9 *might* end up in the order}
\PYG{c+c1}{/// 7, 7, 2, 9, 7, 5.}
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Shuffle}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
\end{Verbatim}

Use a Random and do something close to a reverse of selection sort, using
\code{Exchange} with a random position.

\index{sorting!insertion sort}\index{algorithms!insertion sort}\index{nested loop}\index{insertion sort}

\subsection{Insertion Sort}
\label{sorting:index-5}\label{sorting:insertion-sort}
In the Insertion Sort algorithm, we build up a longer and longer sorted
list from the bottom of the array. We repeatedly insert the next element
into the sorted part of the array by sliding it down (using our familiar
\code{Exchange()} method) to its proper position.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{IntArrayInsertionSort} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{N} \PYG{p}{=} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{j}\PYG{p}{=}\PYG{l+m}{1}\PYG{p}{;} \PYG{n}{j}\PYG{p}{\PYGZlt{}}\PYG{n}{N}\PYG{p}{;} \PYG{n}{j}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{n}{j}\PYG{p}{;} \PYG{n}{i}\PYG{p}{\PYGZgt{}}\PYG{l+m}{0} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{data}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{\PYGZlt{}} \PYG{n}{data}\PYG{p}{[}\PYG{n}{i}\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{]}\PYG{p}{;} \PYG{n}{i}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{Exchange} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{i}\PYG{p}{,} \PYG{n}{i} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Consider the earlier example array as we illustrate some of the steps.
I use the symbol `-` for an element that we know to
be in the sorted list at the beginning of the array,
and `@' over the next one we are trying to insert \emph{at} the right position.
We start with a one-element sorted list and try to position the second element:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
        \PYGZhy{}  @
 data: 12  8 \PYGZhy{}5 22  9  2
index:  0  1  2  3  4  5
\end{Verbatim}

After each outer loop in sequence we end up with:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
        \PYGZhy{}  \PYGZhy{}  @
 data:  8 12 \PYGZhy{}5 22  9  2
index:  0  1  2  3  4  5

        \PYGZhy{}  \PYGZhy{}  \PYGZhy{}  @
 data: \PYGZhy{}5  8 12 22  9  2
index:  0  1  2  3  4  5

        \PYGZhy{}  \PYGZhy{}  \PYGZhy{}  \PYGZhy{}  @
 data: \PYGZhy{}5  8 12 22  9  2
index:  0  1  2  3  4  5

        \PYGZhy{}  \PYGZhy{}  \PYGZhy{}  \PYGZhy{}  \PYGZhy{}  @
 data: \PYGZhy{}5  8  9 12 22  2
index:  0  1  2  3  4  5

        \PYGZhy{}  \PYGZhy{}  \PYGZhy{}  \PYGZhy{}  \PYGZhy{}  \PYGZhy{}
 data: \PYGZhy{}5  2  8  9 12 22
index:  0  1  2  3  4  5
\end{Verbatim}

Let us illustrate several times just through the inner loop, the first time,
when the 8 is moved into
position from index \code{j} = 1, so \code{i} starts at 1.  We show the letter i
over the data at index \code{i}, and show the comparison test to be done with a \emph{\textgreater{}}
with a `?' over it.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
          ? i
 data: 12 \PYGZgt{} 8  \PYGZhy{}5  22   9   2   1\PYGZgt{}0 and 12\PYGZgt{}8: true, so swap, loop
index:  0   1   2   3   4   5

        i
 data:  8  12  \PYGZhy{}5  22   9   2   0\PYGZgt{}0 false, skip comparison of data, end loop
index:  0   1   2   3   4   5
\end{Verbatim}

Let us also illustrate at a later time through the inner loop, when the 9 is moved into
position from index \code{j} = 4, so \code{i} starts at 4.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
                      ? i
 data: \PYGZhy{}5   8  12  22 \PYGZgt{} 9   2  4\PYGZgt{}0 and 22\PYGZgt{}9: true, so swap, loop
index:  0   1   2   3   4   5

                  ? i
 data: \PYGZhy{}5   8  12 \PYGZgt{} 9  22   2  3\PYGZgt{}0 and 12\PYGZgt{}9: true, so swap, loop
index:  0   1   2   3   4   5

              ? i
 data: \PYGZhy{}5   8 \PYGZgt{} 9  12  22   2  2\PYGZgt{}0 and 8\PYGZgt{}9: false, end inner loop
index:  0   1   2   3   4   5
\end{Verbatim}

The 9 started at index \code{j} = 4, and now the list is sorted up through index 4.

This will require as many exchanges as Bubble Sort,
since only one inversion is removed per exchange. So Insertion Sort also
requires \(O(N^2)\) exchanges. On average Insertion Sort requires
only half as many comparisons as Bubble Sort, since the average distance an
element must move for random input is one-half the length of the sorted
portion.

\index{sorting!Shell sort}\index{nested loop}\index{Shell sort}\index{algorithms!Shell sort}

\subsection{Shell Sort}
\label{sorting:shell-sort}\label{sorting:index-6}
Shell Sort is basically a trick to make Insertion Sort run faster. If
you take a quick glance at the code and look beyond the presence of
two additional \emph{outer loops}, you'll notice that the code looks very similar.

Since Insertion Sort removes one inversion per exchange, it cannot run
faster than the number of inversions in the data, which in worst case is
\(O(N^2)\). Of course, it can't run faster than N, either, because
it must look at each element, whether or not the element is out of
position. We can't do any thing about the lower bound O(N), but we can
do something about the number of steps to remove inversions.

The trick in Shell Sort is to start off swapping elements that are
further apart.  While this may remove only one inversion sometimes,
often many more inversions are removed with intervening elements.
Shell Sort considers the subsequences of elements spaced k
elements apart. There are k such sequences starting at positions 0
through k-1 in the array. In these sorts, elements k positions apart are
exchanged, removing between 1 and 2(k-1)+1 inversions.

Swapping elements far apart is not sufficient, generally, so
a Shell Sort will do several
passes with decreasing values of k, ending with k=1.
The following examples experiment
with different series of values of k.

In this first example, we sort all subsequences of elements 8 apart,
then 4, 2, and 1. Please note that these intervals are to show how the
method works--not how the method works \emph{best}.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Shell sort of data using specified swapping intervals.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{IntArrayShellSort} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{intervals}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{N} \PYG{p}{=} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
         \PYG{c+c1}{// The intervals for the shell sort must be sorted, ascending}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{k}\PYG{p}{=}\PYG{n}{intervals}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{;} \PYG{n}{k}\PYG{p}{\PYGZgt{}}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{k}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{int} \PYG{n}{interval} \PYG{p}{=} \PYG{n}{intervals}\PYG{p}{[}\PYG{n}{k}\PYG{p}{]}\PYG{p}{;}
            \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{m}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{m}\PYG{p}{\PYGZlt{}}\PYG{n}{interval}\PYG{p}{;} \PYG{n}{m}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{j}\PYG{p}{=}\PYG{n}{m}\PYG{p}{+}\PYG{n}{interval}\PYG{p}{;} \PYG{n}{j}\PYG{p}{\PYGZlt{}}\PYG{n}{N}\PYG{p}{;} \PYG{n}{j}\PYG{p}{+}\PYG{p}{=}\PYG{n}{interval}\PYG{p}{)} \PYG{p}{\PYGZob{}}
                  \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{n}{j}\PYG{p}{;} \PYG{n}{i}\PYG{p}{\PYGZgt{}}\PYG{p}{=}\PYG{n}{interval} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{data}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{\PYGZlt{}}\PYG{n}{data}\PYG{p}{[}\PYG{n}{i}\PYG{p}{\PYGZhy{}}\PYG{n}{interval}\PYG{p}{]}\PYG{p}{;} 
                       \PYG{n}{i}\PYG{p}{\PYGZhy{}}\PYG{p}{=}\PYG{n}{interval}\PYG{p}{)} \PYG{p}{\PYGZob{}}
                     \PYG{n}{Exchange} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{i}\PYG{p}{,} \PYG{n}{i} \PYG{p}{\PYGZhy{}} \PYG{n}{interval}\PYG{p}{)}\PYG{p}{;}
                  \PYG{p}{\PYGZcb{}}
               \PYG{p}{\PYGZcb{}}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{IntArrayShellSortNaive} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{intervals} \PYG{p}{=} \PYG{p}{\PYGZob{}} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{4}\PYG{p}{,} \PYG{l+m}{8} \PYG{p}{\PYGZcb{}}\PYG{p}{;}
         \PYG{n}{IntArrayShellSort} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{intervals}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

In general, shell sort with sequences of jump sizes that
are powers of one another doesn't
do as well as one where most jump sizes are not multiples of others,
mixing up the data more.
In  addition, the number of intervals must be increased as the size of the array to
be sorted increases, which explains why we allow an \emph{arbitrary} array of intervals
to be specified.

Without too much explanation, we show how you can choose the intervals differently
in an \emph{improved} shell sort, where the intervals have been chosen so as not to be
multiples of one another.

Donald Knuth has suggested a couple of methods for computing the intervals:
\begin{gather}
\begin{split}h_0 = 1\end{split}\notag\\\begin{split}h_{k+1} = 3 h_k + 1\end{split}\notag\\\begin{split}t = \lfloor log_3 n \rfloor - 1\end{split}\notag
\end{gather}
Here we are using notation for the \emph{floor} function
\(\lfloor x \rfloor\) means the largest integer \(\le x\).

This results in a sequence 1, 4, 13, 40, 121.... You stop computing values in the
sequence when \(t = log_3 n - 1\). (So for n=50,000, you should have about 9-10
intervals.)

For completeness, we note that \(log_3 n\) must be sufficiently large (and \textgreater{} 2)
for this method to work. Our code ensures this by taking the \emph{maximum} of
\(log_3 n\) and 1.

Knuth also suggests:
\begin{gather}
\begin{split}h_0 = 1\end{split}\notag\\\begin{split}h_{k+1} = 2 h_k + 1\end{split}\notag\\\begin{split}t = \lfloor log_2 n \rfloor - 1\end{split}\notag
\end{gather}
This results in a sequence 1, 3, 7, 15, 31....

Here is the improvement to our naive method that dynamically calculates
the intervals based on the first suggestion of Knuth:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Generates the intervals for Shell sort on a  }
      \PYG{c+c1}{/// list of length n via an algorithm from Knuth.}
      \PYG{k}{static} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{GenerateIntervals} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{n} \PYG{p}{\PYGZlt{}} \PYG{l+m}{2}\PYG{p}{)} \PYG{p}{\PYGZob{}}  \PYG{c+c1}{// no sorting will be needed}
            \PYG{k}{return} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k+kt}{int} \PYG{n}{t} \PYG{p}{=} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Max} \PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{)}\PYG{n}{Math}\PYG{p}{.}\PYG{n}{Log} \PYG{p}{(}\PYG{n}{n}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{)} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{intervals} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{n}{t}\PYG{p}{]}\PYG{p}{;}       
         \PYG{n}{intervals} \PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{l+m}{1}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{t}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)}
            \PYG{n}{intervals} \PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{3} \PYG{p}{*} \PYG{n}{intervals} \PYG{p}{[}\PYG{n}{i} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{p}{]} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}
         \PYG{k}{return} \PYG{n}{intervals}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{IntArrayShellSortBetter} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{intervals} \PYG{p}{=} \PYG{n}{GenerateIntervals} \PYG{p}{(}\PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{IntArrayShellSort} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{intervals}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Shell sort is a complex sorting algorithm to make ``work well'', which is why it is not
seen often in practice. It is, however, making a bit of a comeback in embedded systems.

We nevertheless think it is a very cool algorithm to have heard of as a computer science
student and think it has promise in a number of situations, especially in systems where
there are limits on available memory (e.g. embedded systems).

\index{sorting!Quicksort}\index{algorithms!Quicksort}\index{recursion!Quicksort}\index{Quicksort}

\subsection{Quicksort a.k.a. Partition Sort}
\label{sorting:index-7}\label{sorting:quicksort-a-k-a-partition-sort}
This sort is a more advanced example that uses \emph{recursion}. We list it because it
is one of the best sorts for \emph{random} data, having an \emph{average} time behavior of
\(O(N  \log N)\).
Quicksort is a rather interesting case. While it has an excellent average
behavior, it has a worst case performance of \(O(N ^2)\).

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Sort elements of data in index range [lowI, highI].}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{IntArrayQuickSort} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{,} 
                                            \PYG{k+kt}{int} \PYG{n}{lowI}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{highI}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{afterSmall} \PYG{p}{=} \PYG{n}{lowI}\PYG{p}{,} \PYG{n}{beforeBig} \PYG{p}{=} \PYG{n}{highI}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{pivot} \PYG{p}{=} \PYG{n}{data}\PYG{p}{[}\PYG{p}{(}\PYG{n}{lowI} \PYG{p}{+} \PYG{n}{highI}\PYG{p}{)} \PYG{p}{/} \PYG{l+m}{2}\PYG{p}{]}\PYG{p}{;}  
         \PYG{c+c1}{// in loop data[i] \PYGZlt{}= pivot if i \PYGZlt{} afterSmall}
         \PYG{c+c1}{//         data[i] \PYGZgt{}= pivot if i \PYGZgt{} beforeBig}
         \PYG{c+c1}{//         region with aftersmall \PYGZlt{}= i \PYGZlt{}= beforeBig}
         \PYG{c+c1}{//             shrinks to nothing.}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{afterSmall} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{beforeBig}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{while} \PYG{p}{(}\PYG{n}{data}\PYG{p}{[}\PYG{n}{afterSmall}\PYG{p}{]} \PYG{p}{\PYGZlt{}} \PYG{n}{pivot}\PYG{p}{)}
               \PYG{n}{afterSmall}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
            \PYG{k}{while} \PYG{p}{(}\PYG{n}{pivot} \PYG{p}{\PYGZlt{}} \PYG{n}{data}\PYG{p}{[}\PYG{n}{beforeBig}\PYG{p}{]}\PYG{p}{)}
               \PYG{n}{beforeBig}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{afterSmall} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{beforeBig}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{Exchange} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{afterSmall}\PYG{p}{,} \PYG{n}{beforeBig}\PYG{p}{)}\PYG{p}{;}
               \PYG{n}{afterSmall}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
               \PYG{n}{beforeBig}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}  \PYG{c+c1}{// after loop: beforeBig \PYGZlt{} afterSmall, and}
         \PYG{c+c1}{//      data[i] \PYGZlt{}= pivot for i \PYGZlt{}= beforeBig, }
         \PYG{c+c1}{//      data[i] == pivot for i if beforeBig \PYGZlt{} i \PYGZlt{} afterSmall, }
         \PYG{c+c1}{//      data[i] \PYGZgt{}= pivot for i \PYGZgt{}= afterSmall. }
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{lowI} \PYG{p}{\PYGZlt{}} \PYG{n}{beforeBig}\PYG{p}{)} \PYG{c+c1}{// at least two elements}
            \PYG{n}{IntArrayQuickSort} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{lowI}\PYG{p}{,} \PYG{n}{beforeBig}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{afterSmall} \PYG{p}{\PYGZlt{}} \PYG{n}{highI}\PYG{p}{)} \PYG{c+c1}{// at least two elements}
            \PYG{n}{IntArrayQuickSort} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{afterSmall}\PYG{p}{,} \PYG{n}{highI}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{IntArrayQuickSort} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{data}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{1}\PYG{p}{)}
            \PYG{n}{IntArrayQuickSort} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{l+m}{0}\PYG{p}{,} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Though the initial call is to sort an entire array, this is accomplished by
dealing with sections, so the main work is done in the version with the
two extra parameters, giving the lowest and highest index considered.

It picks an arbitrary element as \emph{pivot}, and then swaps
elements with values above and below the pivot until the part of the array
being processed is in three sections:
\begin{enumerate}
\item {} 
elements \textless{}= pivot;

\item {} 
possibly an element equal to pivot

\item {} 
elements \textgreater{}= pivot.

\end{enumerate}

Though sections 1 and 3 are not sorted, there are no inversions \emph{between} any two
separate sections, so only the smaller sections 1 and 3 need to be sorted \emph{separately},
and only then if they have at least two elements.  They can be sorted
by calling the \emph{same} function,
but with a smaller range of indices to deal with in each case.
These \emph{recursive} calls stop when a part is reduced to one element.

\index{loop!invariant}
Another optional glimpse at an advanced topic:  The outer \code{while} loop
in lines 11-20 has fairly complicated logic.  To prove it is correct
overall, you can state and prove the simpler \emph{loop invariant} expressed
in the comments above the loop, lines 7-10.  This allows the conclusion
after the loop in comment lines 21-24.

\index{Random}\index{seed}\index{regenerate random numbers}

\subsection{Random Data Generation}
\label{sorting:index-9}\label{sorting:random-data-generation}
Now it is time to talk about how we are going to check the performance in
a real-world situation. We're going to start by modeling the situation when
the data are in random order.

The following code generates a random array:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Fill data with pseudo\PYGZhy{}random data seeded by randomSeed.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{IntArrayGenerate} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{randomSeed}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Random} \PYG{n}{r} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Random} \PYG{p}{(}\PYG{n}{randomSeed}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)}
            \PYG{n}{data} \PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

There are a few things to note in this code:
\begin{enumerate}
\item {} 
We use the random number generator option to include a \emph{seed}. Random numbers
aren't truly random. The particular sequence is just determined by a seed.
The simplest way to create a Random object uses a seed taken from the system clock.

\item {} 
In order to regenerate a particular example, we actually need the random sequence to be
consistent, so we know that each of the sorting algorithms is being tested
using the same random data.

\item {} 
Because the sorting algorithms \emph{modify} the data that are passed to it, we
need to have a way of regenerating the sequence for the next test.
Hence we specify the same seed each time.
(We could also copy the data, but it is kind of a waste of memory.)

\end{enumerate}

This completes the discussion of the \code{Sorting} class in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sorting/sorting.cs}{sorting/sorting.cs}.

\index{Stopwatch}\index{performance - Stopwatch and TimeSpan}\index{timing}

\subsection{Timing}
\label{sorting:timing}\label{sorting:index-10}
Separate from the basic sorts is the idea of checking their performance.
The rest of the code is in the driver class in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sorting/sorting\_demo.cs}{sorting/sorting\_demo.cs}.

We need the ability to time the various sorting algorithms. Luckily, the
.Net framework/library gives us a
way of doing so through its \code{Stopwatch} class. This class supports methods that you
would expect if you've ever used a stopwatch (the kind found in sports):
\begin{itemize}
\item {} 
Reset: Resets the elapsed time to zero. We need this so we can use the same Stopwatch
for each sorting algorithm.

\item {} 
Start: Starts the stopwatch. Will keep recording time until stopped.

\item {} 
Stop: Stops the stopwatch.

\item {} 
ElapsedMilliseconds: Not really a method but a property (like a variable). We'll use this to
get the total time that has elapsed between pairs of Start/Stop events in milliseconds.

\end{itemize}

So let's take a look at the \code{Main()}
method's code to see how we compare the sorting algorithms.
The \code{Main()} method should be thought of as an \emph{experiment} that tests the performance
of each of the sorting algorithms.
As all of the tests follow the same pattern,
we're going to look at the basic variable setup first, and then one test.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
         \PYG{k+kt}{int} \PYG{n}{arraySize}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{randomSeed}\PYG{p}{;}
         \PYG{n}{Stopwatch} \PYG{n}{watch} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Stopwatch} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{;}
\end{Verbatim}

The variables declared here are to set up the apparatus:
\begin{itemize}
\item {} 
\code{arraySize}: The size of the array where we wish to test the performance. We will
use this to create an array with \code{arraySize} random values.

\item {} 
\code{randomSeed}: This allows the user to vary the seed that is used to create
the random array. We often want to do this to determine whether our performance
results are stable when run a large number of times with different distributions.
We won't go into too much detail here but consider it an important part of building
good performance benchmarks.

\item {} 
\code{watch}: The stopwatch object we're using to do the timings of all experiments.

\item {} 
\code{data}:  The array to be sorted.

\end{itemize}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{args}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZlt{}} \PYG{l+m}{2}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{arraySize} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Please enter desired array size: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{randomSeed} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}
               \PYG{l+s}{\PYGZdq{}Please enter an initial random seed value: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}} \PYG{k}{else} \PYG{p}{\PYGZob{}}
            \PYG{n}{arraySize} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse} \PYG{p}{(}\PYG{n}{args} \PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{randomSeed} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse} \PYG{p}{(}\PYG{n}{args} \PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{data} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{n}{arraySize}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

This code is designed so we can accept the parameters \code{arraySize} and \code{randomSeed}
from the command line or by prompting the user. When programmers design benchmarks, they
often try to make it possible to run them with minimal user interaction. For the purposes
of teaching, we wanted to make it possible to run it with or without command-line parameters.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
         \PYG{n}{TimeSetup}\PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{randomSeed}\PYG{p}{,} \PYG{n}{watch}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Sorting}\PYG{p}{.}\PYG{n}{IntArrayQuickSort}\PYG{p}{(}\PYG{n}{data}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{//this line varies by experiment}
         \PYG{n}{TimeResult}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Quick Sort\PYGZdq{}}\PYG{p}{,} \PYG{n}{watch}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

This code fragment is one of the tests in \code{Main}.  All of the tests set up
for timing first, run the desired sorting algorithm (bubble sort in this case),
and report the timing results.  Since the timing setup and reporting is
always done the same way, they actions are placed in helping methods:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Set up data and watch for sort timing}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{TimeSetup} \PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{randomSeed}\PYG{p}{,} 
         \PYG{n}{Stopwatch} \PYG{n}{watch}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Sorting}\PYG{p}{.}\PYG{n}{IntArrayGenerate} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{randomSeed}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{watch}\PYG{p}{.}\PYG{n}{Reset}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{watch}\PYG{p}{.}\PYG{n}{Start}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// Report sort timing results from watch}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{TimeResult} \PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{sortType}\PYG{p}{,} \PYG{n}{Stopwatch} \PYG{n}{watch}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{watch}\PYG{p}{.}\PYG{n}{Stop} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{double} \PYG{n}{elapsedTime} \PYG{p}{=} \PYG{n}{watch}\PYG{p}{.}\PYG{n}{ElapsedMilliseconds}\PYG{p}{/}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{l+m}{0}\PYG{l+m}{0.0}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{n}{sortType} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}: \PYGZob{}0:F3\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{elapsedTime}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\code{TimeSetup}:
\begin{enumerate}
\item {} 
Creates the `random' array of \code{data}, based on \code{randomSeed}.

\item {} 
Resets the \code{Stopwatch} object to zero.

\item {} 
Starts the \code{Stopwatch}.

\end{enumerate}

After the sort, \code{TimeResult}:
\begin{enumerate}
\item {} 
Stops the \code{Stopwatch} and get the elapsed time (\code{watch.ElapsedMilliseconds}).
The value
is an integer (long) number of
milliseconds (thousandths of a second).

\item {} 
Prints the performance results in seconds.

\end{enumerate}

You can see all of the tests in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sorting/sorting\_demo.cs}{sorting/sorting\_demo.cs}.


\subsection{Running the Code}
\label{sorting:running-the-code}
Here's the output of a trial run on one of our computers. The results will vary
depending on your computer's CPU, among other factors.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
bin/Debug\PYGZdl{} mono Sorting.exe 1000 12
Quick Sort: 0.000
Naive Shell Sort: 0.000
Better Shell Sort: 0.000
Insertion Sort: 0.001
Selection Sort: 0.002
Bubble Sort: 0.003
bin/Debug\PYGZdl{} mono Sorting.exe 1000 55
Quick Sort: 0.000
Naive Shell Sort: 0.000
Better Shell Sort: 0.000
Insertion Sort: 0.001
Selection Sort: 0.002
Bubble Sort: 0.003
bin/Debug\PYGZdl{} mono Sorting.exe 10000 2
Quick Sort: 0.001
Naive Shell Sort: 0.019
Better Shell Sort: 0.002
Insertion Sort: 0.134
Selection Sort: 0.174
Bubble Sort: 0.321
bin/Debug\PYGZdl{} mono Sorting.exe 50000 2
Quick Sort: 0.006
Naive Shell Sort: 0.441
Better Shell Sort: 0.015
Insertion Sort: 3.239
Selection Sort: 4.172
Bubble Sort: 8.028
bin/Debug\PYGZdl{} mono Sorting.exe 100000 2
Quick Sort: 0.014
Naive Shell Sort: 1.794
Better Shell Sort: 0.034
Insertion Sort: 13.158
Selection Sort: 16.736
Bubble Sort: 31.334
\end{Verbatim}

At least based on randomly-generated arrays, the performance can be summarized
as follows:
\begin{itemize}
\item {} 
Bubble Sort is rather unimpressive as expected. In fact, this algorithm is never
used in practice but is of historical interest. Like the brute-force style of
searching, it does way too much work to come up with the right answer!

\item {} 
Selection Sort and Insertion Sort are also rather unimpressive on their own. Even though
Selection Sort can in theory do a lot less data movement, it must make a large
number of comparisons to find the minimum value to be moved. Again it is way too much work.
Insertion Sort, while unimpressive, fares a bit better and turns out to be a
nice building block (if modified) for the Shell Sort. Varying the interval size
drastically reduces the amount of data movement (and the distance it has to move).

\item {} 
Shell Sort does rather well, especially when we pick the right intervals.
In practice, the intervals also need to be adjusted based on the size of the
array, which is what we do as larger array sizes are considered. This is no trivial
task but a great deal of work has already been done in the past to determine
functions that generate good intervals.

\item {} 
The Quicksort is generally fastest on random data.  It is by far the
most commonly used sorting algorithm. Yet there are signs that Shell sort
is making a comeback in embedded systems, because it concise to code
and is still quite fast.  See
\phantomsection\label{sorting:id3}{\hyperref[sorting:wikipediashellsort]{{[}WikipediaShellSort{]}}}, where it is mentioned that
the \phantomsection\label{sorting:id4}{\hyperref[sorting:uclibc]{{[}uClibc{]}}} library makes use of Shell sort in its \code{qsort()} implementation,
rather than implementing the library sort with the more common quicksort.

\end{itemize}

\index{search!binary}\index{binary search}\index{algorithms!binary search}

\section{Binary Searching}
\label{binarysearching:binary-searching}\label{binarysearching:binarysearching}\label{binarysearching:index-0}\label{binarysearching::doc}
Binary search is an improvement over linear searching that works only
if the data in the array are sorted beforehand.

Suppose we have the following array data shown under the array indices:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
10  20  30  40  50  60  70  80  90  100 115 125 135 145 155 178 198
\end{Verbatim}

Binary search works by keeping track of the midpoint (mid) and the minimum (min) and
maximum (max) index positions where the item \emph{might be}.

If we are looking for a number, say, 115, here is a visual on how we might go about it.
We display the indices over the data being considered.
Here min and max are the smallest and largest index to still consider.
A textual explanation follows the visual:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16
  10  20  30  40  50  60  70  80  90 100 115 125 135 145 155 178 198
min=0 max=16 mid=8
                                     100 115 125 135 145 155 178 198
min=9 max=16 mid=12
                                     100 115 125
min=9 max=11 mid=10
Item 115 found at position 10
\end{Verbatim}
\begin{itemize}
\item {} 
We start by testing the data at position 8. 115 is greater than the value at position
8 (100), so we assume that the value must be somewhere between positions 9 and 16.

\item {} 
In the second pass, we test the data at position 12 (the midpoint between 9 and 16).
115 is less than the value at position 12, so we assume that the value must be somewhere
between positions 9 and 11.

\item {} 
In the last pass, we test the value at position 10. The value 115 is at this position,
so we're done.

\end{itemize}

So binary search (as its name might suggest) works by dividing the interval to be searched
during each pass in half. If you think about how it's working here with 17 items. Because
there is integer division here, the interval will not always be precisely half. it is the
floor of dividing by 2 (integer division, that is).

With the data above, you see that the algorithm determined the item within 3 steps.
To reduce to one element
to consider, it could be 4 or 5 steps.  Note that \(4 < log_2 17 < 5\).

Now that we've seen how the method works, here is the code
in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/binary\_searching/binary\_searching.cs}{binary\_searching/binary\_searching.cs} that does the work:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{c+c1}{/// Return the index of item in a non\PYGZhy{}empty sorted array data,}
      \PYG{c+c1}{/// or return \PYGZhy{}1 if item is not in the array.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{IntArrayBinarySearch}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{item}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{min} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{,} \PYG{n}{max} \PYG{p}{=} \PYG{n}{data}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{;}
         \PYG{k}{while}\PYG{p}{(}\PYG{n}{min} \PYG{p}{\PYGZlt{}}\PYG{p}{=} \PYG{n}{max}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{int} \PYG{n}{mid} \PYG{p}{=} \PYG{p}{(}\PYG{n}{min}\PYG{p}{+}\PYG{n}{max}\PYG{p}{)} \PYG{p}{/} \PYG{l+m}{2}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{data}\PYG{p}{[}\PYG{n}{mid}\PYG{p}{]} \PYG{p}{=}\PYG{p}{=} \PYG{n}{item}\PYG{p}{)}
               \PYG{k}{return} \PYG{n}{mid}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{item} \PYG{p}{\PYGZgt{}} \PYG{n}{data}\PYG{p}{[}\PYG{n}{mid}\PYG{p}{]}\PYG{p}{)}
               \PYG{n}{min} \PYG{p}{=} \PYG{n}{mid} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{;}
            \PYG{k}{else}
               \PYG{n}{max} \PYG{p}{=} \PYG{n}{mid} \PYG{p}{\PYGZhy{}} \PYG{l+m}{1}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}} 
         \PYG{k}{return} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Here's a quick explanation, because it largely follows from the above explanation.
\begin{itemize}
\item {} 
Line 5: Initially item could be anywhere in the array,
so minimum is at position 0 and maximum is at position
N-1 (data.Length - 1).

\item {} 
The loop to make repeated passes over the array begins on line 6.
We can only continue searching if there is some data left to consider
(\code{min \textless{}= max}).

\item {} 
Line 7 does just what we expect:
It calculates the median position (mid).

\item {} 
It is always possible that we've found the item, which is what we test on line 8,
and return with our answer if we found it.

\item {} 
Lines 10-13: If not, we continue.  If the item is greater than the value
at this mid position, we know it is in the ``upper half''.
Otherwise, it's in the ``lower half''.

\item {} 
Line 15: Otherwise the binary search loop terminates, and we
return -1 (to indicate not found).
The -1 value is a commonly-returned indicator of failure in search operations
(especially on arrays, lists, and strings),
so we use this mostly out of respect for tradition.
It makes particular sense,
because -1 is not within the \emph{index set} of the array (which starts
at 0 in C\# and ends at \code{data.Length - 1}.

\end{itemize}

Of course we generally would be searching in an array with multiple elements.
It is still important to check \emph{edge cases}:  Check that the code correctly
returns -1 if the array has length 0 (a legal length).

Similar to linear searching, we provide a main program that tests it out.
in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/binary\_searching/binary\_searching\_demo.cs}{binary\_searching/binary\_searching\_demo.cs}.  It uses
an elaboration of binary search that prints
out the steps visually, as in the introduction to this section.
It also references previous example projects: functions from files
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/searching/extract\_from\_string.cs}{searching/extract\_from\_string.cs} and \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sorting/sorting.cs}{sorting/sorting.cs}.

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
         \PYG{k+kt}{string} \PYG{n}{input} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}
            \PYG{l+s}{\PYGZdq{}Please enter some comma/space separated integers: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data} \PYG{p}{=} \PYG{n}{ExtractFromString}\PYG{p}{.}\PYG{n}{IntsFromString}\PYG{p}{(}\PYG{n}{input}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Sorting}\PYG{p}{.}\PYG{n}{IntArrayShellSortBetter}\PYG{p}{(}\PYG{n}{data}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{string} \PYG{n}{prompt} \PYG{p}{=}
            \PYG{l+s}{\PYGZdq{}Please enter a number to find (empty line to end): \PYGZdq{}}\PYG{p}{;}
         \PYG{n}{input} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{input}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{!}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{int} \PYG{n}{searchItem} \PYG{p}{=} \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{input}\PYG{p}{)}\PYG{p}{;}
            \PYG{k+kt}{int} \PYG{n}{foundPos} \PYG{p}{=} \PYG{n}{BinarySearching}\PYG{p}{.}\PYG{n}{IntArrayBinarySearchPrinted}\PYG{p}{(}
                                                    \PYG{n}{data}\PYG{p}{,} \PYG{n}{searchItem}\PYG{p}{)}\PYG{p}{;}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{foundPos} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)}
               \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Item \PYGZob{}0\PYGZcb{} not found\PYGZdq{}}\PYG{p}{,} \PYG{n}{searchItem}\PYG{p}{)}\PYG{p}{;}
            \PYG{k}{else}
               \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Item \PYGZob{}0\PYGZcb{} found at position \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} 
                  \PYG{n}{searchItem}\PYG{p}{,} \PYG{n}{foundPos}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{input} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptLine}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
\end{Verbatim}


\subsection{Elaborated Binary Search Exercise}
\label{binarysearching:elaborated-binary-search-exercise}
Even if you do not find \code{item} in a binary search, it is sometimes useful to know
where \code{item} lies in relation to the array elements.  It could be
before the first element, in between two elements, or after the last element.
Suppose \code{N} is the (positive) array length.
Instead of just returning -1 if \code{item} is not in the array, return
\begin{itemize}
\item {} 
-1 if \code{item \textless{} data{[}0{]}}

\item {} 
\code{-(k+1)} if \code{data{[}k-1{]} \textless{} item \textless{} data{[}k{]}}

\item {} 
\code{-(N+1)} if \code{data{[}N-1{]} \textless{} item}

\end{itemize}

Modify \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/binary\_searching/binary\_searching.cs}{binary\_searching/binary\_searching.cs} into
\code{binary\_searching2.cs} so this extra information is returned
(and indicated clearly in a main testing program derived from
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/binary\_searching/binary\_searching\_demo.cs}{binary\_searching/binary\_searching\_demo.cs}).
This should \emph{not} require a change to the \code{while} loop, \emph{nor}
require any added loop.
\phantomsection\label{lab-array1d:lab-arrays1d}
\index{labs!arrays}

\section{Lab: Arrays}
\label{lab-array1d:index-0}\label{lab-array1d::doc}\label{lab-array1d:lab-arrays}

\subsection{Overview}
\label{lab-array1d:overview}
In this lab, we'll practice working with arrays. Arrays are
fundamental to computer science, especially when it comes to
formulating various \emph{algorithms}. We've already learned a bit about
arrays through the \code{string} data type. In many ways, a character
string reveals the secrets of arrays:
\begin{itemize}
\item {} 
each element of a string is a common type (char)

\item {} 
we can use indexing to find any given character, e.g. \code{s{[}i{]}} gives
us the character at position \code{i}.

\item {} 
we know that the string has a finite length, e.g. \code{s.Length}.

\end{itemize}

So you've already learned these \emph{concepts}. But practice is useful
creating and manipulating arrays with different kinds of data.


\subsection{Goals}
\label{lab-array1d:goals}
In this lab, we're going to practice:
\begin{itemize}
\item {} 
creating arrays that hold numerical data

\item {} 
populating an array with data

\item {} 
using the tools of loops and decisions to do something interesting with the data

\item {} 
printing the data

\end{itemize}


\subsection{Tasks}
\label{lab-array1d:tasks}
Copy the example file \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/array\_lab\_stub/array\_lab.cs}{array\_lab\_stub/array\_lab.cs} to
a new project of yours.
Complete the body of a function
for each main part, and call each function in \code{Main} several times with
actual parameters chosen to test it well.  To label your illustrations, make
liberal use of the first function, \code{PrintNums}, to display and label inputs
and outputs.  Where several tests are appropriate for the same function,
you might want to write a separate testing function that prints
and labels inputs, passes the data on to the function being tested,
and prints results.

Recall that you can declare an array in two ways:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{myArray1} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{;}
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{myArray2} \PYG{p}{=} \PYG{p}{\PYGZob{}} \PYG{l+m}{7}\PYG{p}{,} \PYG{l+m}{7}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2} \PYG{p}{\PYGZcb{}}\PYG{p}{;}
\end{Verbatim}

The first declaration creates an array initialized to
all zeroes. The second creates an
array where the elements are taken from the bracketed list of
values. The second will be convenient to set up tests for this lab.
\begin{enumerate}
\item {} 
Complete and test the function with documentation and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Print label and then each element preceeded by a space,}
      \PYG{c+c1}{///  all across one line.  Example:}
      \PYG{c+c1}{///  If a contains \PYGZob{}3, \PYGZhy{}1, 5\PYGZcb{} and label is \PYGZdq{}Nums:\PYGZdq{},}
      \PYG{c+c1}{///  print:   Nums: 3 \PYGZhy{}1 5                   }
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintInts}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{label}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}

      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

This will be handy for labeling later tests.  Note that you end
on the same line, but a later label can start with \code{\textbackslash{}n}
to advance to the next line.

\item {} 
Complete and test the function with documentation and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{///  Prompt the user to enter n integers, and}
      \PYG{c+c1}{///  return an array containing them.}
      \PYG{c+c1}{///  Example:  ReadInts(\PYGZdq{}Enter values\PYGZdq{}, 3) could generate the}
      \PYG{c+c1}{///  Console sequence:}
      \PYG{c+c1}{///      Enter values (3)}
      \PYG{c+c1}{///      1: 5}
      \PYG{c+c1}{///      2: 7}
      \PYG{c+c1}{///      3: \PYGZhy{}1}
      \PYG{c+c1}{///  and the function would return an array containing \PYGZob{}5, 7, \PYGZhy{}1\PYGZcb{}. }
      \PYG{c+c1}{///  Note the format of the prompts for individual elements.}
      \PYG{k}{static} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{ReadInts}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{prompt}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{;} \PYG{c+c1}{// so stub compiles}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

This will allow user tests.  The earlier input utility functions
are included at the end of the class.

\item {} 
Complete and test the function with documentation and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{///  Return the minimum value in a.}
      \PYG{c+c1}{///  Example: If a contains \PYGZob{}5, 7, 4, 9\PYGZcb{}, return 4. }
      \PYG{c+c1}{///  Assume a contains at least one value.}
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{Minimum}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{l+m}{0}\PYG{p}{;} \PYG{c+c1}{// so stub compiles}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
Complete and test the function with documentation and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{///  Return the number of even values in a.}
      \PYG{c+c1}{///  Example: If a contains \PYGZob{}\PYGZhy{}4, 7, 6, 12, 9\PYGZcb{}, return 3. }
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{CountEven}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{l+m}{0}\PYG{p}{;} \PYG{c+c1}{// so stub compiles}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
Complete and test the function with documentation and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{///  Add corresponding elements of a and b and place them in sum.}
      \PYG{c+c1}{///  Assume all arrays have the same Length.}
      \PYG{c+c1}{///  Example: If a contains \PYGZob{}2, 4, 6\PYGZcb{} and b contains \PYGZob{}7, \PYGZhy{}1, 8\PYGZcb{}}
      \PYG{c+c1}{///  then at the end sum should contain \PYGZob{}9, 3, 14\PYGZcb{}. }
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PairwiseAdd}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{b}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{sum}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}

      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

To test this out, you'll need to declare and initialize the arrays
to be added. You'll \emph{also} need to declare a third array to hold the
results. Make sure that the arrays all have the same
dimensionality before proceeding.

This section is a warm-up for the next one.  It is not required
if you do the next one:

\item {} 
Complete and test the function with documentation and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{///  Return a new array whose elements are the sums of the}
      \PYG{c+c1}{///  corresponding elements of a and b.}
      \PYG{c+c1}{///  Assume a and b have the same Length.}
      \PYG{c+c1}{///  Example: If a contains \PYGZob{}2, 4, 6\PYGZcb{} and b contains \PYGZob{}3, \PYGZhy{}1, 5\PYGZcb{}}
      \PYG{c+c1}{///  then return an array containing \PYGZob{}5, 3, 11\PYGZcb{}. }
      \PYG{k}{static} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n+nf}{NewPairwiseAdd}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{b}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{;} \PYG{c+c1}{// so stub compiles}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

See how this is different from the previous part!

\item {} 
Complete and test the function with documentation and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{///  Return true if the numbers are sorted in increasing order,}
      \PYG{c+c1}{///  so that in each pair of consecutive entries,}
      \PYG{c+c1}{///  the second is always at least as large as the first.}
      \PYG{c+c1}{///  Return false otherwise.  Assume an array with fewer than}
      \PYG{c+c1}{///  two elements is ascending.}
      \PYG{c+c1}{///  Examples: If a contains \PYGZob{}2, 5, 5, 8\PYGZcb{}, return true;}
      \PYG{c+c1}{///  if a contains \PYGZob{}2, 5, 3, 8\PYGZcb{}, return false. }
      \PYG{k}{static} \PYG{k+kt}{bool} \PYG{n+nf}{IsAscending}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k}{false}\PYG{p}{;} \PYG{c+c1}{// so stub compiles}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

This has some pitfalls.  You will need more tests that the ones
in the documentation!  You can code this with
a ``short-circuit'' loop.  What do you need to find to be
immediately sure you know the answer?

\item {} 
\textbf{20 \% extra credit:}
Complete and test the function with documentation and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{///  Print an ascending sequence from the elements}
      \PYG{c+c1}{///  of a, starting with the first element and printing}
      \PYG{c+c1}{///  the next number after the previous number}
      \PYG{c+c1}{///  that is at least as large as the previous one printed.}
      \PYG{c+c1}{///  Example: If a contains \PYGZob{}5, 2, 8, 4, 8, 11, 6, 7, 10\PYGZcb{},}
      \PYG{c+c1}{///  print:  5 8 8 11      }
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintAscendingValues}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}

      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
\textbf{20 \% extra credit:}
Complete and test the function with documentation and heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{///  Prints each ascending run in a, one run per line.}
      \PYG{c+c1}{///  Example: If a contains \PYGZob{}2, 5, 8, 3, 9, 9, 8\PYGZcb{}, print}
      \PYG{c+c1}{///  2 5 8}
      \PYG{c+c1}{///  3 9 9}
      \PYG{c+c1}{///  8          }
      \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintRuns}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}

      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
\textbf{20 \% extra credit:}
Given two arrays, \code{a} and \code{b} that represent vectors. Write a
function that computes the vector dot product of these two
floating point arrays. The vector dot product (in mathematics) is defined
as the sum of \code{a{[}i{]} * b{[}i{]}} (for all i). Here's an example of how it
should work:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{double}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{double}\PYG{p}{[}\PYG{p}{]} \PYG{p}{\PYGZob{}} \PYG{l+m}{1.5}\PYG{p}{,} \PYG{l+m}{2.0}\PYG{p}{,} \PYG{l+m}{3.0} \PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{k+kt}{double}\PYG{p}{[}\PYG{p}{]} \PYG{n}{b} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{double}\PYG{p}{[}\PYG{p}{]} \PYG{p}{\PYGZob{}} \PYG{l+m}{4.0}\PYG{p}{,} \PYG{l+m}{2.0}\PYG{p}{,} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1.0} \PYG{p}{\PYGZcb{}}\PYG{p}{;}

\PYG{k+kt}{double} \PYG{n}{dotProduct} \PYG{p}{=} \PYG{n}{VectorDotProduct}\PYG{p}{(}\PYG{n}{a}\PYG{p}{,} \PYG{n}{b}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}The dot product is \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{dotProduct}\PYG{p}{)}\PYG{p}{;}

\PYG{c+c1}{// Should calculate 1.5 * 4.0 + 2.0 * 2.0 + 3.0 * \PYGZhy{}1.0 = 7.0}
\end{Verbatim}

From here on, create your own headings.

\item {} 
\textbf{20 \% extra credit:}
Suppose we have loaded an array with the digits of an integer,
where the digit for the highest power of 10 is kept in position 0,
next highest in
position 1, and so on. The ones position is always at position
array.Length - 1:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{digits} \PYG{p}{=} \PYG{p}{\PYGZob{}} \PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{9}\PYG{p}{,} \PYG{l+m}{6}\PYG{p}{,} \PYG{l+m}{7} \PYG{p}{\PYGZcb{}}\PYG{p}{;}
\end{Verbatim}

representing \(1(10^3)+9(10^2)+6(10^1)+7(10^0)\).

Without showing you the code, here is how you would convert a
number from its digits to an integer efficiently, without
calculating high powers for 10 separately:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{num} \PYG{p}{=} \PYG{l+m}{0}
\PYG{n}{num} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0} \PYG{p}{*} \PYG{l+m}{0} \PYG{p}{+} \PYG{l+m}{1} \PYG{p}{=} \PYG{l+m}{1}
\PYG{n}{num} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0} \PYG{p}{*} \PYG{l+m}{1} \PYG{p}{+} \PYG{l+m}{9} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{9}
\PYG{n}{num} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0} \PYG{p}{*} \PYG{l+m}{1}\PYG{l+m}{9} \PYG{p}{+} \PYG{l+m}{6} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{9}\PYG{l+m}{6}
\PYG{n}{num} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{0} \PYG{p}{*} \PYG{l+m}{1}\PYG{l+m}{9}\PYG{l+m}{6} \PYG{p}{+} \PYG{l+m}{7} \PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{9}\PYG{l+m}{6}\PYG{l+m}{7}
\PYG{n}{done}\PYG{p}{!}
\end{Verbatim}

Write a function that converts the array of digits representing
a base 10 number to its \code{int} value
(or for really long integers, you are encouraged to use
a \code{long} data type). Note that we only allow single digit
numbers to be placed
in the array, so negative numbers are not addressed.

\item {} 
\textbf{20 \% extra credit:}
Each digit represents a multiple of a \emph{power} of the
\emph{base}.  In the previous version the base is 10,
but other bases are important.  Now make the base a parameter.
Here we consider bases no bigger than 10, so we can continue to use
only digits for place value symbols.
Write a function (or revise the
previous solution) to return the int or long represented.
For example if \{1, 0, 0, 1, 1\} represents a base 2 number,
\(1(2^4)+0(2^3)+0(2^2)+1(2^1)+1(2^0)=19\)
is returned. Base 2 is central to computer hardware.

\end{enumerate}


\section{Lab: Performance}
\label{lab-searching-arrays-lists-maps::doc}\label{lab-searching-arrays-lists-maps:lab-search-performance}\label{lab-searching-arrays-lists-maps:lab-performance}
In {\hyperref[sorting:sorting]{\emph{Sorting Algorithms}}} we took advantage of a few ideas
to show how to do basic
benchmarking to compare the various approaches.
\begin{itemize}
\item {} 
using randomly-generated data

\item {} 
making sure each algorithm is working with the same data

\item {} 
making sure that we try a range of sizes to observe the effects of scaling

\item {} 
using a timer with sufficiently high resolution (the \code{Stopwatch} gives
us measurements in milliseconds).

\end{itemize}

In this lab, you get your chance  to learn a bit more about performance
by comparing \emph{searches}.
The art of benchmarking is
something that is easy to learn but takes a lifetime to master (to borrow
a phrase from the famous Othello board game).

Most of the algorithms we cover in introductory courses tend to be \emph{polynomial}
in nature. That is, the execution time can be bounded by a polynomial function
of the data size \(n\). A more accurate measure may also include
a logarithm.  Examples
include but are not limited to:
\begin{itemize}
\item {} 
\(O(1)\) is constant time,
characterized by a calculation with a limited number of steps.

\item {} 
\(O(n)\) is linear time; often characterized by a single loop

\item {} 
\(O(n^2)\) is the time squared; often characterized by a nested loop

\item {} 
\(O(log\ n)\) is logarithmic (base 2) time; often characterized by a loop
that repeatedly divides its work in half. The binary search is a well-known example.

\item {} 
\(O(n\ log\ n)\) is an example of a hybrid. Perhaps there is an outer loop that
is linear and an inner loop that is logarithmic.

\end{itemize}

And there are way more than these shown here. As you progress in computing, you'll
come to know and appreciate these in greater detail.

In this lab, we're going to look at a few different data structures and methods
that perform searches on them and do \emph{empirical} analysis to get an idea of how
well each combination works. Contrasted with other labs where you had to write
a lot of code, we're going to give you some code to do all of the needed work
but ask you to write the code to
do the actual analysis and produce a basic table.


\subsection{The Experiments}
\label{lab-searching-arrays-lists-maps:the-experiments}
We're going to measure the performance of data structures we have been learning
about (and \emph{will} learn about, for lists and sets). For this lab, we'll focus on:
\begin{itemize}
\item {} 
Integer arrays using {\hyperref[searching:searching]{\emph{Linear Searching}}} and {\hyperref[binarysearching:binarysearching]{\emph{Binary Searching}}}

\item {} 
{\hyperref[lists:lists]{\emph{Lists}}} of integers with linear searching

\item {} 
{\hyperref[dictionaryexamples:sets]{\emph{Sets}}} of integers; checking if an item is contained in the set

\end{itemize}

In the interest of fairness, we are only going to look at the time it takes
to perform the various search operations. We're not going to count the time
to randomly-generate the data and actually \emph{build} the data structure. The
reasoning is straightforward. We're interested in the search time, which is
completely independent of other aspects that may be at play. We're not at all
saying that the other aspects are unimportant but want to keep the assignment
focus on search.

The experimental apparatus that we are constructing will do the following
for each of the cases:
\begin{itemize}
\item {} 
create the data structure (e.g. new array, new list, new set)

\item {} 
use a random seed \code{seed}, initialize a random generator that will generate
\code{n} values.

\item {} 
insert the random values into the data structure .
For the case of sets, which eliminate duplicates, it is
entirely possible you will end up with a tiny fraction of a percent
fewer than \code{n} values.

\item {} 
to measure the performance of any given search method, we need to perform a
significant number of lookups (based on numbers in the random sequence) to
ensure that we get an accurate idea of the \emph{average} lookup time in practice.
We'll call this parameter, \code{rep}.  We will spread out the values looked for
by checking data elements that have indices at a regular interval throughout the array.
The separation is \code{m = n/rep} when \code{rep \textless{} n}. The separation is 1, and
we wrap around at the end of the array if \code{rep \textgreater{} n}.

\item {} 
We'll start a Stopwatch just before entering the loop to perform the lookups.

\end{itemize}


\subsection{Starter Project}
\label{lab-searching-arrays-lists-maps:starter-project}
To make your life easier, we have put together a project
that refers to all the code for all of the experiments you need
to run. (That's right, we're giving you the code for the \emph{experiments},
but you're going to write
some code to run the various experiments and then run for varying sizes of \code{n}.)
The stub file is \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/performance\_lab\_stub/performance\_lab.cs}{performance\_lab\_stub/performance\_lab.cs}.

Recreate example project performance\_lab\_stub in your solution as performance\_lab,
so you have your own copy to modify.  You can either
\begin{itemize}
\item {} 
copy into the
lab project the files \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/sorting/sorting.cs}{sorting/sorting.cs},
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/searching/searching.cs}{searching/searching.cs}, and
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/binary\_searching/binary\_searching.cs}{binary\_searching/binary\_searching.cs}.  \emph{If} you copy them into the lab
project, \emph{rename} the unused \code{Main} method from \code{binary\_searching.cs}
to something else (since Xamarin Studio allows only one \code{Main} method in a
project).

\item {} 
An alternative is to recreate their whole projects,
and \emph{reference} them from the lab project.

\end{itemize}

Here is the code for the first experiment, to test the performance of linear
searching on integer arrays:

\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{long} \PYG{n+nf}{ExperimentIntArrayLinearSearch} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{rep}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{seed}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Stopwatch} \PYG{n}{watch} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Stopwatch} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{data} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{n}{n}\PYG{p}{]}\PYG{p}{;}
         \PYG{n}{Sorting}\PYG{p}{.}\PYG{n}{IntArrayGenerate} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{seed}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{m} \PYG{p}{=} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Max}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{n}{n}\PYG{p}{/}\PYG{n}{rep}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{watch}\PYG{p}{.}\PYG{n}{Reset} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}       
         \PYG{n}{watch}\PYG{p}{.}\PYG{n}{Start} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{c+c1}{// perform the rep lookups}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{k}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{,} \PYG{n}{i}\PYG{p}{=}\PYG{l+m}{0}\PYG{p}{;} \PYG{n}{k} \PYG{p}{\PYGZlt{}} \PYG{n}{rep}\PYG{p}{;} \PYG{n}{k}\PYG{p}{+}\PYG{p}{+}\PYG{p}{,} \PYG{n}{i}\PYG{p}{=}\PYG{p}{(}\PYG{n}{i}\PYG{p}{+}\PYG{n}{m}\PYG{p}{)}\PYG{p}{\PYGZpc{}}\PYG{n}{n}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Searching}\PYG{p}{.}\PYG{n}{IntArrayLinearSearch} \PYG{p}{(}\PYG{n}{data}\PYG{p}{,} \PYG{n}{data} \PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{watch}\PYG{p}{.}\PYG{n}{Stop} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{return} \PYG{n}{watch}\PYG{p}{.}\PYG{n}{ElapsedMilliseconds}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Let's take a quick look at how this experiment is constructed. We'll also take a
look at the other experiments but these will likely be presented in a bit
less detail, except to highlight the differences:
\begin{itemize}
\item {} 
On line 3, we create a \code{Stopwatch} instance. We'll be using this to do the timing.

\item {} 
On lines 4-5, we are creating the data to be searched. Because we have already
written this code in our sorting algorithms examples, we can refer to the
Sorting class code in \code{sorting.cs}, as long as you made the lab project
able to reference it.  We use the \code{Sorting} class name
to access the method \code{IntArrayGenerate()} within this class. We also take advantage
of this in the other experiments.

\item {} 
Line 6 converts the number of repetitions into the increment in index values for each
time.

\item {} 
Line 7 resets the stopwatch. It is not technically required; however, we tend to be
in the habit of doing it, because we sometimes reuse the same stopwatch and want
to make sure it is completely zeroed out. A call to \code{Reset()} ensures it is zero.

\item {} 
Line 8 actually starts the stopwatch. We are starting here as opposed to before line
4, because the random data generation has nothing to do with the actual searching of
the array data structure.

\item {} 
Lines 10 through 12 are searching \code{rep} times for an item already known to
be in the array.

\item {} 
Line 13 stops the stopwatch.

\item {} 
Line 14 returns the elapsed time in \emph{milliseconds}
between the \code{Start()} and \code{Stop()} method calls,
which reflects the actual time of the experiment.

\end{itemize}

Each of the other experiments is constructed similarly.
For linear search and binary search
we use the methods created earlier.
For the lists and the set we use the built-in \code{Contains}
method to search.
The list and set are directly initialized in their constructors from the
array data.  (More on that in later chapters.)

You need to fill in the \code{Main} method.
The stub already has code to generate a random value for the \code{seed} for
any run of the program.  \emph{Read} through to the end of the lab before
starting to code.  A step-by-step sequence is suggested at the end.
\begin{itemize}
\item {} 
Your code must parse command line \code{args} for the parameters \code{rep}
and \emph{any number}
of values for \code{n}.  For instance:
\begin{quote}

mono PerformanceLab.exe 50000 1000 10000 100000
\end{quote}

would generate the table shown below for 50000 repetitions
for each of the values of \code{n}: 1000,
10000, and 100000.

\item {} 
In the end you will want to run each experiment
for \code{rep} repetitions and iterate through each different value of \code{n}.

\item {} 
Present the result data in a nice printed right-justified table for
all values of n,
with a title including the number of repetitions.  Print
something like the following, with the number of seconds calculated.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Times in seconds with 50000 repetitions
       n    linear      list  binary     set
    1000  ????.???  ????.???  ??.???  ??.???
   10000  ????.???  ????.???  ??.???  ??.???
  100000  ????.???  ????.???  ??.???  ??.???
\end{Verbatim}

The table would be longer if more values of n were entered on the command line.
Note that the experiments return times in milliseconds, (1/1000 of a second)
while the table should print times in \emph{seconds}.

\item {} 
Your final aim is to
show your TA or instructor the results of
a run with a table with at least three lines of data and with n
being successive powers of 10, and \emph{non-zero entries everywhere}.  \emph{Read on}
for the major catch!

You will need to
\emph{experiment} and adjust the repetitions and \code{n} choices.
In order to \emph{get all perceptible values} (nonzero), you will need a
very large number of repetitions to work for the fastest searches.
Our choice of 50000 in the example is not appropriate with these \code{n} values.
The catch is that without further tweaking, you will only get nonzero
values for all the fastest searches if the slower ones take
\emph{ridiculously long}.

Because the range of speeds is so enormous, make an accommodation with the
slow linear versions:  If \code{rep \textgreater{}= 100} and \code{(long)n*rep \textgreater{}= 100000000},
then, for the linear and list columns \emph{only}, time with \code{rep2 = rep/100}
instead of \code{rep},
and then compensate by multiplying the resulting time by \code{(double)rep/rep2}
to produce the final table value.
(This multiplier is not necessarily just 100, since the integer division creating
\code{rep2} may not be exact.)

\end{itemize}

Before making the modification for large numbers, be sure to test with
small enough values (though some results will be 0).
Once again, you are encouraged to develop this is steps, for example:
\begin{enumerate}
\item {} 
Make sure you can parse the command line parameters.  In a testing version
write code to print out \code{rep},
and \emph{separate} code to print out all \code{n} values, for any number
of \code{n} values.

\item {} 
Print out one \emph{linear} test for \code{rep} and one value of \code{n}.

\item {} 
Print out the results for all tests for \code{rep} and one value of \code{n}.
Keep \code{rep*n} small enough so the linear searches do not take too much time.

\item {} 
Do all values of \code{n}.

\item {} 
Make the printing be formatted as in the sample table.

\item {} 
Add the modification for large \code{rep*n}.

\item {} 
Experiment and get a table to show off!

\end{enumerate}


\section{Multi-dimensional Arrays}
\label{twodim:multi-dimensional-arrays}\label{twodim::doc}\label{twodim:id1}
\index{array!two dimensional}\index{two dimensional array}

\subsection{Rectangular Arrays (Two Dimensional)}
\label{twodim:rectangular-arrays-two-dimensional}\label{twodim:index-0}
You should be familiar with one dimensional arrays. The data in arrays
may be any type. While a one dimensional array
works for a sequence of data,
we need something more for a two dimensional table,
where data values vary over both row and column.

If we have a table of integers, for instance with three
rows and four columns:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+m}{2} \PYG{l+m}{4}  \PYG{l+m}{7} \PYG{l+m}{5}\PYG{l+m}{5}
\PYG{l+m}{3} \PYG{l+m}{1}  \PYG{l+m}{8} \PYG{l+m}{1}\PYG{l+m}{0}
\PYG{l+m}{6} \PYG{l+m}{0} \PYG{l+m}{4}\PYG{l+m}{9} \PYG{l+m}{1}\PYG{l+m}{2}
\end{Verbatim}

We could declare an array variable of the right size as

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{,}\PYG{p}{]} \PYG{n}{table} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{4}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

Multiple indices are separated by commas inside the square brackets.
In declaring an array type, no indices are included so the \code{{[},{]}}
indicates a two dimensional array.  Where the \code{new} object is being created,
the values inside the square brackets give each dimension.

In general the notation for a two dimensional array declaration is:
\begin{quote}

\textbf{type} \code{{[}, {]}} \textbf{variableName}
\end{quote}

and to create a new array with default values:
\begin{quote}

new \textbf{type} \code{{[}} \emph{intExpression1}\code{,} \emph{intExpression2} \code{{]}}
\end{quote}

where the expressions evaluate to integers for the dimensions.

To assign the 8 in the table above, consider that it is in the second
row in normal counting, but we start array indices at 0, so there are
rows 0, 1, and 2, and the 8 has row index 1.
Again starting with index 0 for columns, the 8 is at index
2. We can assign a value to that position with

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{table}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{8}\PYG{p}{;}
\end{Verbatim}

In fact a two dimensional array just needs two indices that could mean
anything.  For instance, it was just the standard convention,
calling the left index the row.  They could have been switched everywhere, and
assume the notation \code{table{[}column, row{]}}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{,}\PYG{p}{]} \PYG{n}{table} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{4}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{]}\PYG{p}{;}
\PYG{n}{table}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{8}\PYG{p}{;}
\end{Verbatim}

but we will \emph{stick with} the original \code{{[}row, column{]}} model.

Data indexed by more than two integer indices can be stored in a higher
dimension array, with more indices between the square braces.  We
will only consider two dimensional arrays in the examples here.

A shorthand for initializing all the data in the table,
analogous to initializing one dimensional arrays is:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{,} \PYG{p}{]} \PYG{n}{table} \PYG{p}{=} \PYG{p}{\PYGZob{}} \PYG{p}{\PYGZob{}}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{4}\PYG{p}{,}  \PYG{l+m}{7}\PYG{p}{,} \PYG{l+m}{5}\PYG{l+m}{5}\PYG{p}{\PYGZcb{}}\PYG{p}{,}
                  \PYG{p}{\PYGZob{}}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,}  \PYG{l+m}{8}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{\PYGZcb{}}\PYG{p}{,}
                  \PYG{p}{\PYGZob{}}\PYG{l+m}{6}\PYG{p}{,} \PYG{l+m}{0}\PYG{p}{,} \PYG{l+m}{4}\PYG{l+m}{9}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{2}\PYG{p}{\PYGZcb{}} \PYG{p}{\PYGZcb{}}\PYG{p}{;}
\end{Verbatim}

All rows must be the same length when using this notation.

Often two dimensional arrays, like one dimensional  arrays, are processed
in loops. Multiple dimension arrays are often processed in nested loops.
We could print out this table using columns 5 spaces wide with the code:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
        \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{r} \PYG{p}{\PYGZlt{}} \PYG{l+m}{3}\PYG{p}{;} \PYG{n}{r}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
           \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{c} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{c} \PYG{p}{\PYGZlt{}} \PYG{l+m}{4}\PYG{p}{;} \PYG{n}{c}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
              \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0, 5\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{table}\PYG{p}{[}\PYG{n}{r}\PYG{p}{,} \PYG{n}{c}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
           \PYG{p}{\PYGZcb{}}
           \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
        \PYG{p}{\PYGZcb{}}
\end{Verbatim}

If we wanted to make a more general function out of that code,
we have a problem:  the number of rows and columns were literal values
that we knew.  We need something more general.  For one dimensional
arrays we had the Length property, but now there are more than one
lengths!

The following csharp sequence illustrates the syntax needed:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{,} \PYG{p}{]} \PYG{n}{table} \PYG{p}{=} \PYG{p}{\PYGZob{}} \PYG{p}{\PYGZob{}}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{4}\PYG{p}{,}  \PYG{l+m}{7}\PYG{p}{,} \PYG{l+m}{5}\PYG{l+m}{5}\PYG{p}{\PYGZcb{}}\PYG{p}{,}
      \PYG{p}{\PYGZgt{}}                   \PYG{p}{\PYGZob{}}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{,}  \PYG{l+m}{8}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{\PYGZcb{}}\PYG{p}{,}
      \PYG{p}{\PYGZgt{}}                   \PYG{p}{\PYGZob{}}\PYG{l+m}{6}\PYG{p}{,} \PYG{l+m}{0}\PYG{p}{,} \PYG{l+m}{4}\PYG{l+m}{9}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{2}\PYG{p}{\PYGZcb{}} \PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{table}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
\PYG{l+m}{1}\PYG{l+m}{2}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{table}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{3}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{n}{table}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;}
\PYG{l+m}{4}
\PYG{n}{csharp}\PYG{p}{\PYGZgt{}} \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n} \PYG{k}{in} \PYG{n}{table}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{p}{\PYGZgt{}}    \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{n}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZgt{}} \PYG{p}{\PYGZcb{}}
\PYG{l+m}{2}
\PYG{l+m}{4}
\PYG{l+m}{7}
\PYG{l+m}{5}\PYG{l+m}{5}
\PYG{l+m}{3}
\PYG{l+m}{1}
\PYG{l+m}{8}
\PYG{l+m}{1}\PYG{l+m}{0}
\PYG{l+m}{6}
\PYG{l+m}{0}
\PYG{l+m}{4}\PYG{l+m}{9}
\PYG{l+m}{1}\PYG{l+m}{2}
\end{Verbatim}

Note:
\begin{itemize}
\item {} 
The meaning for the Length property,
is now the \emph{total} number of elements, (3)(4) = 12.

\item {} 
The separate method \code{GetLength} is needed to find the number of rows and columns.
The entries in the list of array indices in the multi-dimensional array notation
are themselves indexed to provide the \code{GetLength} method parameter for each dimension.
In this case index 0 gives the row length (left index of the array notation),
and 1 gives the column length (right index of the array notation).

\item {} 
The \code{foreach} statement behavior is consistent with the \code{Length} property, giving \emph{all}
the elements, row by row.  More generally, the rightmost indices vary most rapidly
as the \code{foreach} statement iterates through all elements.

\end{itemize}

Just replacing 3 and 4 by \code{table.GetLength(0)} and \code{table.GetLength(1)} in the
table printing code would make it general.

A more elaborate table might include row and column sums:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
  \PYG{l+m}{2}   \PYG{l+m}{4}   \PYG{l+m}{7}  \PYG{l+m}{5}\PYG{l+m}{5} \PYG{p}{\textbar{}}  \PYG{l+m}{6}\PYG{l+m}{8}
  \PYG{l+m}{3}   \PYG{l+m}{1}   \PYG{l+m}{8}  \PYG{l+m}{1}\PYG{l+m}{0} \PYG{p}{\textbar{}}  \PYG{l+m}{2}\PYG{l+m}{2}
  \PYG{l+m}{6}   \PYG{l+m}{0}  \PYG{l+m}{4}\PYG{l+m}{9}  \PYG{l+m}{1}\PYG{l+m}{2} \PYG{p}{\textbar{}}  \PYG{l+m}{6}\PYG{l+m}{7}
\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}
 \PYG{l+m}{1}\PYG{l+m}{1}   \PYG{l+m}{5}  \PYG{l+m}{6}\PYG{l+m}{4}  \PYG{l+m}{7}\PYG{l+m}{7} \PYG{p}{\textbar{}} \PYG{l+m}{1}\PYG{l+m}{5}\PYG{l+m}{7}
\end{Verbatim}

For example, the following function from example file
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/print\_table/print\_table.cs}{print\_table/print\_table.cs},
prints out a table of integers
neatly, including row and column sums.  It illustrates
a number of things.  It shows the interplay between
one and two dimensional arrays, since the row and column sums are
just one dimensional arrays.

Now that we are using arrays,
we can easily look at the same collection of data repeatedly.
It is possible to look at the data one time to just see its maximum
width, and then go through again and print data using a column
width that is just large enough for the longest numbers.
When looking through the data for string lengths, the row and column
structure is not important, so the code illustrates \code{foreach} loops
to chug through all the data.  We use the earlier trick in
{\hyperref[forexamples:modular-mult-table]{\emph{Modular Multiplication Table}}}, creating a custom format string to make columns
the right width.

The code refers once to the earlier \code{StringOfReps} in {\hyperref[lab-nested-loops:lab-loops]{\emph{Lab: Loops}}}
for the row of dashes setting off the column sums:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
	  \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintTableAndSums}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{,}\PYG{p}{]} \PYG{n}{t}\PYG{p}{)}
	  \PYG{p}{\PYGZob{}}
	     \PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{rowSum} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{n}{t}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{]}\PYG{p}{,}
	           \PYG{n}{colSum} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{n}{t}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{]}\PYG{p}{;}
	     \PYG{k+kt}{int} \PYG{n}{sum} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
	     \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{r} \PYG{p}{\PYGZlt{}} \PYG{n}{t}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;} \PYG{n}{r}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
	        \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{c} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{c} \PYG{p}{\PYGZlt{}} \PYG{n}{t}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;} \PYG{n}{c}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
	           \PYG{n}{rowSum}\PYG{p}{[}\PYG{n}{r}\PYG{p}{]} \PYG{p}{+}\PYG{p}{=} \PYG{n}{t}\PYG{p}{[}\PYG{n}{r}\PYG{p}{,} \PYG{n}{c}\PYG{p}{]}\PYG{p}{;}
	           \PYG{n}{colSum}\PYG{p}{[}\PYG{n}{c}\PYG{p}{]} \PYG{p}{+}\PYG{p}{=} \PYG{n}{t}\PYG{p}{[}\PYG{n}{r}\PYG{p}{,} \PYG{n}{c}\PYG{p}{]}\PYG{p}{;}
	        \PYG{p}{\PYGZcb{}}
	        \PYG{n}{sum} \PYG{p}{+}\PYG{p}{=} \PYG{n}{rowSum}\PYG{p}{[}\PYG{n}{r}\PYG{p}{]}\PYG{p}{;}
	     \PYG{p}{\PYGZcb{}}
	     \PYG{k+kt}{int} \PYG{n}{width} \PYG{p}{=} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{+}\PYG{n}{sum}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;}
	     \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n} \PYG{k}{in} \PYG{n}{t}\PYG{p}{)} \PYG{p}{\PYGZob{}}
	        \PYG{n}{width} \PYG{p}{=} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Max}\PYG{p}{(}\PYG{n}{width}\PYG{p}{,} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{+}\PYG{n}{n}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;}
	     \PYG{p}{\PYGZcb{}}
	     \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n} \PYG{k}{in} \PYG{n}{colSum}\PYG{p}{)} \PYG{p}{\PYGZob{}}
	        \PYG{n}{width} \PYG{p}{=} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Max}\PYG{p}{(}\PYG{n}{width}\PYG{p}{,} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{+}\PYG{n}{n}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;}
	     \PYG{p}{\PYGZcb{}}
	     \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n} \PYG{k}{in} \PYG{n}{rowSum}\PYG{p}{)} \PYG{p}{\PYGZob{}}
	        \PYG{n}{width} \PYG{p}{=} \PYG{n}{Math}\PYG{p}{.}\PYG{n}{Max}\PYG{p}{(}\PYG{n}{width}\PYG{p}{,} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{+}\PYG{n}{n}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;}
	     \PYG{p}{\PYGZcb{}}
        \PYG{k+kt}{string} \PYG{n}{format} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZob{}0,\PYGZdq{}} \PYG{p}{+} \PYG{n}{width} \PYG{p}{+} \PYG{l+s}{\PYGZdq{}\PYGZcb{} \PYGZdq{}}\PYG{p}{;}
	       
	     \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{r} \PYG{p}{\PYGZlt{}} \PYG{n}{t}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;} \PYG{n}{r}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
	        \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{c} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{c} \PYG{p}{\PYGZlt{}} \PYG{n}{t}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;} \PYG{n}{c}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
	           \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{format}\PYG{p}{,} \PYG{n}{t}\PYG{p}{[}\PYG{n}{r}\PYG{p}{,} \PYG{n}{c}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
	        \PYG{p}{\PYGZcb{}}
	        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\textbar{} \PYGZdq{}} \PYG{p}{+} \PYG{n}{format}\PYG{p}{,} \PYG{n}{rowSum}\PYG{p}{[}\PYG{n}{r}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
	     \PYG{p}{\PYGZcb{}}   
	     \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{StringOfReps}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZhy{}\PYGZdq{}}\PYG{p}{,}\PYG{p}{(}\PYG{n}{width}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{*}\PYG{p}{(}\PYG{n}{t}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{)} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
	     \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{c} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{c} \PYG{p}{\PYGZlt{}} \PYG{n}{t}\PYG{p}{.}\PYG{n}{GetLength}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;} \PYG{n}{c}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
	        \PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{n}{format}\PYG{p}{,} \PYG{n}{colSum}\PYG{p}{[}\PYG{n}{c}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
	     \PYG{p}{\PYGZcb{}}
	     \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\textbar{} \PYGZdq{}} \PYG{p}{+} \PYG{n}{format}\PYG{p}{,} \PYG{n}{sum}\PYG{p}{)}\PYG{p}{;}
	  \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{exercise!row and column numbering}\index{row and column numbering exercise}

\subsubsection{Row and Column Numbering Exercise}
\label{twodim:row-and-column-numbering-exercise}\label{twodim:row-col-number-exercise}\label{twodim:index-1}
Write a function that sets the values in a given
rectangular array to 10 * (row index +1) + column index + 1, with the
normal row and column indices, starting from 0. For example
an array with two rows
and five columns would end up with values below. Your method should set
the values in the array, not print them out:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+m}{1}\PYG{l+m}{1} \PYG{l+m}{1}\PYG{l+m}{2} \PYG{l+m}{1}\PYG{l+m}{3} \PYG{l+m}{1}\PYG{l+m}{4} \PYG{l+m}{1}\PYG{l+m}{5}
\PYG{l+m}{2}\PYG{l+m}{1} \PYG{l+m}{2}\PYG{l+m}{2} \PYG{l+m}{2}\PYG{l+m}{3} \PYG{l+m}{2}\PYG{l+m}{4} \PYG{l+m}{2}\PYG{l+m}{5}
\end{Verbatim}

If there are no more than 9 rows or columns, this display gives row and
column numbers neatly for the normal human counting system, starting from 1.

\index{exercise!varying column width}\index{varying column width exercise}

\subsubsection{Varying Column Width Exercise}
\label{twodim:varying-width-columns-exercise}\label{twodim:varying-column-width-exercise}\label{twodim:index-2}
Copy the project file \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/print\_table/print\_table.cs}{print\_table/print\_table.cs} to a file
\code{print\_varying\_width\_table.cs} in a projet of yours.
Edit it so that \emph{each} column
is only as wide as it needs to be: the width for the widest entry in
that column.
The earlier data would now print as:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
 \PYG{l+m}{2} \PYG{l+m}{4}  \PYG{l+m}{7} \PYG{l+m}{5}\PYG{l+m}{5} \PYG{p}{\textbar{}}  \PYG{l+m}{6}\PYG{l+m}{8}
 \PYG{l+m}{3} \PYG{l+m}{1}  \PYG{l+m}{8} \PYG{l+m}{1}\PYG{l+m}{0} \PYG{p}{\textbar{}}  \PYG{l+m}{2}\PYG{l+m}{2}
 \PYG{l+m}{6} \PYG{l+m}{0} \PYG{l+m}{4}\PYG{l+m}{9} \PYG{l+m}{1}\PYG{l+m}{2} \PYG{p}{\textbar{}}  \PYG{l+m}{6}\PYG{l+m}{7}
\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}\PYG{p}{\PYGZhy{}}
\PYG{l+m}{1}\PYG{l+m}{1} \PYG{l+m}{5} \PYG{l+m}{6}\PYG{l+m}{4} \PYG{l+m}{7}\PYG{l+m}{7} \PYG{p}{\textbar{}} \PYG{l+m}{1}\PYG{l+m}{5}\PYG{l+m}{7}
\end{Verbatim}

Calculate each of these widths \emph{only once}.
Hint: Create an array of widths and an array of format strings.

\index{array!of arrays}\index{array!two-dimensional, ragged}

\subsection{Advanced topic: Array of Arrays}
\label{twodim:advanced-topic-array-of-arrays}\label{twodim:index-3}
Since you can have an array of any type, it is also possible to have an
\emph{array of arrays}.

You could create a table with shape like the initial example
in {\hyperref[twodim:multi-dimensional-arrays]{\emph{Multi-dimensional Arrays}}}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]}\PYG{p}{[}\PYG{p}{]} \PYG{n}{table2} \PYG{p}{=} \PYG{k}{new} \PYG{n}{array}\PYG{p}{[}\PYG{l+m}{3}\PYG{p}{]}\PYG{p}{[}\PYG{l+m}{4}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

and refer to an element still by row and column index::

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{table2}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{4}\PYG{p}{;}
\end{Verbatim}

The notational difference so far is just that each index in enclosed in
separate square brackets, with no commas.

This takes somewhat more memory and is longer to
access than the multidimensional arrays that we have been talking about
with the comma-separated notation.  For most uses, when you want to
refer to a rectangular table of data, like above,
this new version has little to
offer.

There are a couple of reasons why you might want this format.

First you may have functions that operate on one dimensional arrays,
and individual rows of \code{table2} are one dimensional arrays:
\code{table2{[}1{]}} has type \code{int{[}{]}}.  On the other hand, with the
earlier \code{table} with type  \code{int{[},{]}}, references to part of
the array must always include a comma, so \code{tabel{[}1{]}} would
not refer to a row, but would be a syntax error.

Also in an array of arrays, since each row is an independent array,
their lengths can \emph{vary}.
Here is code to make a doubly indexed ``triangular'' collection
(of 0 values).
Each row must be separately created as a new array:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]}\PYG{p}{[}\PYG{p}{]} \PYG{n}{tri} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{4}\PYG{p}{]}\PYG{p}{[}\PYG{p}{]}\PYG{p}{;} \PYG{c+c1}{//create four null int[] elements}
\PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{tri}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{c+c1}{// Length 4 (rows)}
   \PYG{n}{tri}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{n}{i}\PYG{p}{+}\PYG{l+m}{1}\PYG{p}{]}\PYG{p}{;}  \PYG{c+c1}{// each row has a different length}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

With \code{tri} constructed as above:
\begin{itemize}
\item {} 
\code{tri{[}3, 3{]}} would given a compiler error: no changing \code{{[}{]}{[}{]}} to \code{{[}, {]}}.

\item {} 
\code{tri{[}3{]}{[}3{]}} would refer to an element.

\item {} 
\code{tri{[}1{]}{[}3{]}} would given a run-time out-of-bounds error.
since \code{tri{[}1{]}} is an array of length 2.

\end{itemize}


\section{Chapter Review Questions}
\label{reviewarrays:chapter-review-questions}\label{reviewarrays::doc}\begin{enumerate}
\item {} 
When do you want to use an array rather than just
a bunch of individually named variables?

\item {} 
Before writing a program, must you know the exact size of an array that
you are going to create?

\item {} 
Before creating a new array in a program,
must the program be able to calculate the proper size for the array?

\item {} 
After you have created the array, can you change the size of the original
array object?

\item {} 
If I have the declaration

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{vals} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{5}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}
\begin{enumerate}
\item {} 
What is stored directly in the memory position for variable \code{vals}?

\item {} 
Does \code{vals{[}3{]}} then have a clear value?  If so, what?

\item {} 
Can I later make \code{vals} refer to an array of a different size?

\end{enumerate}

\item {} 
Comment on the comparison between these two snippets:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{char}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+s+sc}{\PYGZsq{}n\PYGZsq{}}\PYG{p}{,} \PYG{l+s+sc}{\PYGZsq{}o\PYGZsq{}}\PYG{p}{,} \PYG{l+s+sc}{\PYGZsq{}w\PYGZsq{}}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{n}{a}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}c\PYGZsq{}}\PYG{p}{;}

\PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}now\PYGZdq{}}\PYG{p}{;}
\PYG{n}{s}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]} \PYG{p}{=} \PYG{l+s+sc}{\PYGZsq{}c\PYGZsq{}}\PYG{p}{;}
\end{Verbatim}

\item {} 
If I want to read or modify the first 100 elements of a 999 element
array, would I use a
\code{foreach} loop or a \code{for} loop? Explain.

\item {} 
If I want to modify all the elements of an array, would I use a
\code{foreach} loop or a \code{for} loop? Explain.

\item {} 
If I want to read all the elements of an array, but not change the array,
and I do not care about the exact position in the array of any member,
would I use a \code{foreach} loop or a \code{for} loop?

\item {} 
Is this legal?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a}\PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{4}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{c+c1}{//...}
\PYG{n}{a} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{p}{[}\PYG{l+m}{7}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

\item {} 
The definition of a program's \code{Main} method may optionally
include a parameter.  What is the type?  How is it used?

\item {} 
What is an alias?  Why is understanding aliases important with arrays?

\item {} 
If I have a function declared

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{f}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{num}\PYG{p}{)}
\PYG{c+c1}{//...}
\end{Verbatim}

and I call it from my \code{Main} function

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{v} \PYG{p}{=} \PYG{l+m}{7}\PYG{p}{;}
\PYG{n}{f}\PYG{p}{(}\PYG{n}{v}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{v}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

Could \code{f} change the value of the variable \code{v}, so 1 is printed
in \code{Main}?
If so, write a one-line body for \code{f} that does it.

\item {} 
If I have a function declared

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{f}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{nums}\PYG{p}{)}
\PYG{c+c1}{//...}
\end{Verbatim}

and I call it from my \code{Main} function

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{v} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+m}{7}\PYG{p}{,} \PYG{l+m}{8}\PYG{p}{,} \PYG{l+m}{9}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{n}{f}\PYG{p}{(}\PYG{n}{v}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{v}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

Could \code{f} change the value of the variable \code{v{[}0{]}}, so 1 is printed
in \code{Main}?
If so, write a one-line body for \code{f} that does it.

\item {} 
What is printed by this snippet?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{b} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+m}{4}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{,} \PYG{l+m}{6}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{n}{b}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{7}\PYG{p}{;}
\PYG{n}{a}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{8}\PYG{p}{;}
\PYG{n}{b}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{9}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}} \PYG{p}{+} \PYG{n}{a}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]} \PYG{p}{+} \PYG{n}{a}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]} \PYG{p}{+} \PYG{n}{a}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
What is printed by this snippet? (Only the second line is changed.)

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{b} \PYG{p}{=} \PYG{n}{a}\PYG{p}{;}
\PYG{n}{b}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{7}\PYG{p}{;}
\PYG{n}{a}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{8}\PYG{p}{;}
\PYG{n}{b}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{9}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}} \PYG{p}{+} \PYG{n}{a}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]} \PYG{p}{+} \PYG{n}{a}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]} \PYG{p}{+} \PYG{n}{a}\PYG{p}{[}\PYG{l+m}{2}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
If my only use for variable \code{temp} is to set up this call to \code{f}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int}\PYG{p}{[}\PYG{p}{]} \PYG{n}{temp} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{n}{f}\PYG{p}{(}\PYG{n}{temp}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

how could I rewrite it with an anonymous array?

\item {} 
After this line, what is the value of \code{a{[}2{]}}?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{bool}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{bool}\PYG{p}{[}\PYG{l+m}{5}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

\item {} 
This will cause a runtime error.  Why?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{a} \PYG{p}{=} \PYG{k}{new} \PYG{k+kt}{string}\PYG{p}{[}\PYG{l+m}{5}\PYG{p}{]}\PYG{p}{;}
\PYG{k}{foreach}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s} \PYG{k}{in} \PYG{n}{a}\PYG{p}{)} \PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
If you get a data sequence from a \code{Random} object,
is it really random?

\item {} 
Explain the significance of a \emph{seed} for a \code{Random} object.

\item {} 
Suppose I create an object \code{table} of type \code{double{[},{]}},
and I think of the first index as referring to a row and the second
index as referring to a column.
\begin{enumerate}
\item {} 
Must each row be the same length?

\item {} 
Does each row have a type \code{double{[}{]}} ?

\end{enumerate}

\item {} 
(Optional) Suppose I create an object \code{table} of type \code{double{[}{]}{[}{]}},
and I think of the first index as referring to a row and the second
index as referring to a column.
\begin{enumerate}
\item {} 
Must each each row be the same length?

\item {} 
Does each row have a type \code{double{[}{]}} ?

\end{enumerate}

\end{enumerate}

\index{list}\index{type!List}

\chapter{Lists}
\label{lists:index-0}\label{lists::doc}\label{lists:lists}\label{lists:id1}
\index{list}

\section{List Syntax}
\label{listsyntax:index-0}\label{listsyntax:listsyntax}\label{listsyntax::doc}\label{listsyntax:list-syntax}
Arrays are fine if you know ahead of time how long your sequence of items is.
Then you create your array with that length, and you are all set.

If you want a variable sized container, you are likely to want a \code{List}.
As with arrays, you might want a collection of any particular type.
Unfortunately, you cannot use the simple notation of arrays to specify
the type of element in a \code{List}.  Array syntax is
\emph{built into} the language.  Lists are handled in the \emph{library} of types
provided by C\# from the .Net framework.  There are all sorts of
situations where you might want a general idea to have a version for each of
many kinds of objects.  There is \emph{not} a new syntax for \emph{each} one.

\index{generics}\index{\textless{} \textgreater{} for generics}

\subsection{Generics}
\label{listsyntax:index-1}\label{listsyntax:generics}
Instead .Net 4.0 introduced one new form of syntax that can apply to all sorts of
classes, \emph{generics}.

The type for a list of strings is

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}}
\end{Verbatim}

The type for an \code{int} list is

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{int}\PYG{p}{\PYGZgt{}}
\end{Verbatim}

In general the new generic syntax allows a type (or several, comma separated) in angle
brackets after a class name.  Lists are an example that depends on just
one included type.  We will see more shortly.

There is a namespace for the generics for collections, including List:
System.Collections.Generic.

We will use several generic library classes, though we will not write the definitions of
new generic classes ourselves.

\index{List!constructor}\index{List!Count}\index{List!Add}\index{List!Remove}\index{List!RemoveAt}\index{List!Contains}

\subsection{List Constructors and Methods}
\label{listsyntax:list-constructors-and-methods}\label{listsyntax:index-2}
We can play with some \code{List} methods in csharp.
Note that csharp informally displays the
value of a \code{List} with a list of elements inside braces.
This is \emph{not} a legal
way to assign values to lists.

The blocks below are all from one csharp session,
with our comments breaking up the sequence.

With the no-parameter constructor, the \code{List} is empty to start:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} List\PYGZlt{}string\PYGZgt{} words = new List\PYGZlt{}string\PYGZgt{}();
csharp\PYGZgt{} words;
\PYGZob{}  \PYGZcb{}
csharp\PYGZgt{} words.Count;
0
\end{Verbatim}

You can add elements, and keep count with the \code{Count} property
as the size changes:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} words.Add(\PYGZdq{}up\PYGZdq{});
csharp\PYGZgt{} words;
\PYGZob{} \PYGZdq{}up\PYGZdq{} \PYGZcb{}
csharp\PYGZgt{} words.Add(\PYGZdq{}down\PYGZdq{});
csharp\PYGZgt{} words;
\PYGZob{} \PYGZdq{}up\PYGZdq{}, \PYGZdq{}down\PYGZdq{} \PYGZcb{}
csharp\PYGZgt{} words.Add(\PYGZdq{}over\PYGZdq{});
csharp\PYGZgt{} words;
\PYGZob{} \PYGZdq{}up\PYGZdq{}, \PYGZdq{}down\PYGZdq{}, \PYGZdq{}over\PYGZdq{} \PYGZcb{}
csharp\PYGZgt{} words.Count;
3
\end{Verbatim}

\index{list!index {[} {]}}\index{{[} {]}!list index}
You can reference and change elements by index, like with arrays:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} words[0];
\PYGZdq{}up\PYGZdq{}
csharp\PYGZgt{} words[2];
\PYGZdq{}over\PYGZdq{}
csharp\PYGZgt{} words[2] = \PYGZdq{}in\PYGZdq{};
csharp\PYGZgt{} words;
\PYGZob{} \PYGZdq{}up\PYGZdq{}, \PYGZdq{}down\PYGZdq{}, \PYGZdq{}in\PYGZdq{} \PYGZcb{}
\end{Verbatim}

You can use \code{foreach} like with arrays or other sequences:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} foreach (string s in words) \PYGZob{}
          \PYGZgt{}    Console.WriteLine(s.ToUpper());
          \PYGZgt{} \PYGZcb{}
UP
DOWN
ON
\end{Verbatim}

\index{List!Console.WriteLine useless}
Note:  Unfortunately C\# is not user-friendly if
you try to use \code{Console.WriteLine} to print a \code{List} \emph{object}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} Console.WriteLine(words)
System.Collections.Generic.List{}`1[System.Int32]
\end{Verbatim}

Next compare \code{Remove}, which finds the first matching element and removes it,
and \code{RemoveAt}, which removes the element at a specified index.
\code{Remove} returns whether the List has been changed:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} words.Remove(\PYGZdq{}down\PYGZdq{});
true
csharp\PYGZgt{} words;
\PYGZob{} \PYGZdq{}up\PYGZdq{}, \PYGZdq{}in\PYGZdq{} \PYGZcb{}
csharp\PYGZgt{} words.Remove(\PYGZdq{}around\PYGZdq{}); // no change
false
csharp\PYGZgt{} words.Add(\PYGZdq{}out\PYGZdq{});
csharp\PYGZgt{} words.Add(\PYGZdq{}on\PYGZdq{});
csharp\PYGZgt{} words;
\PYGZob{} \PYGZdq{}up\PYGZdq{}, \PYGZdq{}in\PYGZdq{}, \PYGZdq{}out\PYGZdq{}, \PYGZdq{}on\PYGZdq{} \PYGZcb{}
csharp\PYGZgt{} words.RemoveAt(2); // \PYGZdq{}out\PYGZdq{} is at index 2
csharp\PYGZgt{} words;
\PYGZob{} \PYGZdq{}up\PYGZdq{}, \PYGZdq{}in\PYGZdq{}, \PYGZdq{}on\PYGZdq{} \PYGZcb{}
\end{Verbatim}

Removing does not leave a ``hole'' in the \code{List}:  The list closes up,
so the index decreases for the elements after the removed one:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} words[2];
\PYGZdq{}on\PYGZdq{}
csharp\PYGZgt{} words.Count;
3
\end{Verbatim}

You can check for membership in a \code{List} with \code{Contains}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} words.Contains(\PYGZdq{}in\PYGZdq{});
true
csharp\PYGZgt{} words.Contains(\PYGZdq{}into\PYGZdq{});
false
\end{Verbatim}

You can also remove all elements at once:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} words.Clear();
csharp\PYGZgt{} words.Count;
0
\end{Verbatim}

\index{List!constructor with sequence}
Here is a List containing \code{int} elements.
Though more verbose than for an array, you can initialize a \code{List}
with another collection, including an anonymous array,
specified with an explicit sequence in braces:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} List\PYGZlt{}int\PYGZgt{} nums = new List\PYGZlt{}int\PYGZgt{}(new[]\PYGZob{}5, 3, 7, 4\PYGZcb{});
csharp\PYGZgt{} nums;
\PYGZob{} 5, 3, 7, 4 \PYGZcb{}
\end{Verbatim}

We have been using the explicit declaration syntax, but generic types tend to get long,
so \code{var} is handy with them:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{var} \PYG{n}{stuff} \PYG{p}{=} \PYG{k}{new} \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

When initializing a generic object, you still need to remember both the angle braces
around the type \emph{and} the parentheses for the parameter list after that.

\index{side effect}
An aside on the \code{Remove} method:  It both causes a side effect,
changing the list,
\emph{and} it returns a value.  If a function returns a value,
we typically use the function call as an
expression in a larger statement.  This is not necessary, as described in
{\hyperref[notusereturn:not-using-ret-val]{\emph{Not using Return Values}}}.  In that section we discussed the \emph{mistake} of not
using return values.  The \code{Remove} method illustrates that this is
not always a mistake:  If you just want the side effect, trying to remove an element,
whether or not it is in the list, then there is no need to check for the return value.
This complete C\# statement is fine:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{someList}\PYG{p}{.}\PYG{n}{Remove}\PYG{p}{(}\PYG{n}{element}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

You should generally think carefully before \emph{defining} a function
that both has a side effect
and a return value.  Most functions that return a value do not have a side effect.
If you see a function used in the normal way as an expression, it is easy to forget that
it was \emph{also} producing some side effect.

\index{example!ReadLines}\index{ReadLines example}\index{List!ReadLines example}

\subsection{Interactive List Example}
\label{listsyntax:index-7}\label{listsyntax:interactive-list-example}
Lists are handy when you do not know how much data there will be.
A simple example would be reading in lines from the user interactively:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{/// Return a List of lines entered by the user in response}
\PYG{c+c1}{/// to the prompt.  Lines in the List will be nonempty, since an}
\PYG{c+c1}{/// empty line terminates the input.}
\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}} \PYG{n}{ReadLines}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{prompt}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}} \PYG{n}{lines} \PYG{p}{=} \PYG{k}{new} \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{prompt}\PYG{p}{)}\PYG{p}{;}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}An empty line terminates input.\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
   \PYG{k+kt}{string} \PYG{n}{line} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
   \PYG{k}{while} \PYG{p}{(}\PYG{n}{line}\PYG{p}{.}\PYG{n}{Length} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
      \PYG{n}{lines}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{n}{line}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{line} \PYG{p}{=} \PYG{n}{Console}\PYG{p}{.}\PYG{n}{ReadLine}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
   \PYG{k}{return} \PYG{n}{lines}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\index{.net api}\index{API for .Net}\index{library!reference for .Net}\index{URL for .Net library reference}\index{msdn.microsoft.com}

\section{.Net Library (API)}
\label{dotnetapi:index-0}\label{dotnetapi:dotnetapi}\label{dotnetapi::doc}\label{dotnetapi:net-library-api}
This book can only introduce so many classes and methods from the C\# library.
You should browse the MSDN .Net Framework Class Library's online documentation.
\begin{quote}

\href{http://msdn.microsoft.com/en-us/library/gg145045.aspx}{http://msdn.microsoft.com/en-us/library/gg145045.aspx}
\end{quote}

We mostly deal with classes in the namespaces System, System.IO,
and System.Collections.Generic, and you can drill down to them.

One complication is that
variations on these classes and methods are included for several Microsoft languages.
Under the Syntax heading, make sure the \textbf{C\# tab} is selected.

For example, you can click in the left column on System.Collections Namespaces, and then
System.Collections.Generic, and then, for example, List(T).  (In C\# that is \code{List\textless{}T\textgreater{}}.)

The summary section separates constructors, properties, and methods.  When you see one of these
with promise, click on it to get the full details.  For example, click on the first method in the
Methods section, \code{Add}, or something new, like \code{IndexOf}, or \code{Reverse}, or \code{Sort}....

Classes also can be classified in several ways for browsing:
\begin{itemize}
\item {} 
Those you will want to be fairly familiar with pretty soon:  string, List, Dictionary

\item {} 
Those that might be useful, that you should be at least aware of.

\item {} 
Those that may be useful eventually, but are not worth your time now.

\end{itemize}

You will also find methods in various categories as you browse:
\begin{itemize}
\item {} 
Methods that make sense and are useful right away

\item {} 
Methods that take a little reading to absorb

\item {} 
Features that we have yet to discuss

\item {} 
Features that are well beyond what we have talked about - ask or wait or read a \emph{lot}.

\end{itemize}


\section{Chapter Review Questions}
\label{reviewlists:chapter-review-questions}\label{reviewlists::doc}\begin{enumerate}
\item {} 
Distinguish the cases when you would want to use a list instead of an array, or
the other way around.

\item {} 
What syntax is consistent between arrays and lists?  What are comparable
features, but with different syntax?

\item {} 
How is the type declaration for a generic type distinctive?

\item {} 
Here is one way to put five particular elements into a list:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{var} \PYG{n}{words} \PYG{p}{=} \PYG{k}{new} \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{temp} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{l+s}{\PYGZdq{}a\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}an\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}the\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}on\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}of\PYGZdq{}}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\PYG{k}{foreach}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s} \PYG{k}{in} \PYG{n}{temp}\PYG{p}{)} \PYG{p}{\PYGZob{}}
    \PYG{n}{words}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{n}{s}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

How can you do this all without a loop, and with only two statements?
How about with a single statement,
assuming you do not need \code{temp} again?

\item {} 
If we continue on from above, with the line:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{var} \PYG{n}{words2} \PYG{p}{=} \PYG{n}{words}\PYG{p}{;}
\end{Verbatim}

Then what would be the difference in effect between these two possible next
lines?

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{words}\PYG{p}{.}\PYG{n}{Clear}\PYG{p}{(}\PYG{p}{)}

\PYG{n}{words} \PYG{p}{=} \PYG{k}{new} \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\item {} 
The constructors for collections like a List are all overloaded.
What forms are allowed in general?

\item {} 
If you delete an element from the middle of a list, what happens to the
spot where you removed the element?

\end{enumerate}

\index{dictionary}\index{type!Dictionary}

\chapter{Dictionaries}
\label{dictionaries:dictionaries}\label{dictionaries:index-0}\label{dictionaries::doc}\label{dictionaries:dictionary}

\section{Dictionary Syntax}
\label{dictionarysyntax:dictionary-syntax}\label{dictionarysyntax::doc}
We have explored several ways of storing a collection of the same type of data:
\begin{itemize}
\item {} 
arrays: built-in syntax, unchanging size of the collection

\item {} 
List: generic class type, allows the size of the collection to grow

\end{itemize}

Both approaches allow reference to data elements using a
numerical index between square brackets, as in \code{words{[}i{]}}.
The index provides an order for the elements,
but there is no meaning to the index beyond the sequence order.

Often, we want to look up data based on a more meaningful key, as in a
dictionary: given a word,
you can look up the definition.

C\# uses the type name \code{Dictionary}, but with greater generality than in
nontechnical use. In a regular dictionary, you start with a word,
and look up the definition.  The generalization is to have some piece of
data that leads you to (or \emph{maps} to) another piece of data.
The computer science jargon is that a \emph{key} leads you to a \emph{value}.
In a normal dictionary, these are both likely to be strings, but in the
C\# generalization, the possible types of key and value are much more extensive.
Hence the generic \code{Dictionary} type requires you to specify
both a type for the key and a type for the value.

We can initialize an English-Spanish dictionary \code{e2sp} with

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{k+kt}{string}\PYG{p}{\PYGZgt{}} \PYG{n}{e2sp} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{k+kt}{string}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

That is quite a mouthful!  The C\# \code{var} syntax is handy to shorten it:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{var} \PYG{n}{e2sp} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{k+kt}{string}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

The general generic type syntax is
\begin{quote}

\code{Dictionary\textless{}} \textbf{keyType}\code{,} \textbf{valueType} \code{\textgreater{}}
\end{quote}

If you are counting the number of repetitions of words in a document, you are likely to want
a \code{Dictionary} mapping each word to its number of repetitions so far:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{var} \PYG{n}{wordCount} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

If your friends all have a personal list of phone numbers, you might look them up
with a dictionary with a string name for the key and a \code{List} of personal phone number
strings for the value.  The type could be \code{Dictionary\textless{}string, List\textless{}string\textgreater{}\textgreater{}}.
This example illustrates how one generic type can be built on another.

There is no restriction on the value type.  There is one important technical
restriction on the key type: it should be immutable. This has to do with the implementation
referenced in {\hyperref[dictionaryefficiency:dictionary-efficiency]{\emph{Dictionary Efficiency}}}.

\index{dictionary!key lookup {[} {]}}\index{{[} {]}!dictionary key lookup}
Similar to an array or \code{List},
you can assign and reference elements of a \code{Dictionary},
using square bracket notation.  The difference is that the reference is through a key,
not a sequential index, as in:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{e2sp}\PYG{p}{[}\PYG{l+s}{\PYGZdq{}one\PYGZdq{}}\PYG{p}{]} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}uno\PYGZdq{}}\PYG{p}{;}
\PYG{n}{e2sp}\PYG{p}{[}\PYG{l+s}{\PYGZdq{}two\PYGZdq{}}\PYG{p}{]} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}dos\PYGZdq{}}\PYG{p}{;}
\end{Verbatim}

Csharp displays dictionaries in its own special form,
as a sequence of pairs \{key, value\}.  Again, this is \emph{special} to csharp.
Here is a longer csharp sequence, broken up with our comments:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} Dictionary\PYGZlt{}string, string\PYGZgt{} e2sp = new Dictionary\PYGZlt{}string, string\PYGZgt{}();
csharp\PYGZgt{} e2sp;
\PYGZob{}\PYGZcb{}
csharp\PYGZgt{} e2sp[\PYGZdq{}one\PYGZdq{}] = \PYGZdq{}uno\PYGZdq{};
csharp\PYGZgt{} e2sp[\PYGZdq{}two\PYGZdq{}] = \PYGZdq{}dos\PYGZdq{};
csharp\PYGZgt{} e2sp[\PYGZdq{}three\PYGZdq{}] = \PYGZdq{}tres\PYGZdq{};
csharp\PYGZgt{} e2sp.Count;
3
csharp\PYGZgt{} e2sp;
\PYGZob{}\PYGZob{} \PYGZdq{}one\PYGZdq{}, \PYGZdq{}uno\PYGZdq{} \PYGZcb{}, \PYGZob{} \PYGZdq{}two\PYGZdq{}, \PYGZdq{}dos\PYGZdq{} \PYGZcb{}, \PYGZob{} \PYGZdq{}three\PYGZdq{}, \PYGZdq{}tres\PYGZdq{} \PYGZcb{}\PYGZcb{}
csharp\PYGZgt{} Console.WriteLine(\PYGZdq{}\PYGZob{}0\PYGZcb{}, \PYGZob{}1\PYGZcb{}, \PYGZob{}2\PYGZcb{}...\PYGZdq{}, e2sp[\PYGZdq{}one\PYGZdq{}],
      \PYGZgt{} e2sp[\PYGZdq{}two\PYGZdq{}], e2sp[\PYGZdq{}three\PYGZdq{}]);
uno, dos, tres...
\end{Verbatim}

\index{dictionary!Keys}\index{Keys property}
If you want to iterate through a whole \code{Dictionary}, you will want the syntax below,
with \code{foreach} and the property \code{Keys}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} foreach (string s in e2sp.Keys) \PYGZob{}
      \PYGZgt{}    Console.WriteLine(s);
      \PYGZgt{} \PYGZcb{}
one
two
three
\end{Verbatim}

The documentation for \code{Dictionary} says
that you cannot depend on the order of processing with \code{foreach}, though the present
implementation remembers the order in which keys were added.

\index{example!ContainsKey}\index{dictionary!ContainsKey example}\index{ContainsKey example}
It is often useful to know if a key is already in a \code{Dictionary}:
Note the method \code{ContainsKey}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} e2sp.ContainsKey(\PYGZdq{}seven\PYGZdq{});
false
csharp\PYGZgt{} e2sp.ContainsKey(\PYGZdq{}three\PYGZdq{});
true
\end{Verbatim}

The method Remove takes a key as parameter.  Like a \code{List} and other
collections, a \code{Dictionary} has a \code{Clear} method:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} e2sp.Count;
3
csharp\PYGZgt{} e2sp.Remove(\PYGZdq{}two\PYGZdq{});
true
csharp\PYGZgt{} e2sp.Count;
2
csharp\PYGZgt{} e2sp.Clear();
csharp\PYGZgt{} e2sp.Count;
0
\end{Verbatim}

\index{big oh}\index{dictionary!big oh}\index{linear order}\index{constant order}

\section{Dictionary Efficiency}
\label{dictionaryefficiency:index-0}\label{dictionaryefficiency:dictionary-efficiency}\label{dictionaryefficiency::doc}\label{dictionaryefficiency:id1}
We could simulate the effect of a Dictionary pretty easily by keeping
a List \code{keys} and a List \code{values}, in the same order.  We could
find the entry with a specified key with:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{n}{keys}\PYG{p}{.}\PYG{n}{IndexOf}\PYG{p}{(}\PYG{n}{key}\PYG{p}{)}\PYG{p}{;}
\PYG{k}{return} \PYG{n}{values}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{;}
\end{Verbatim}

Searching though a \code{List}, however, take time proportional to the
length of the \code{List} in general, \emph{linear order}.  Through a clever implementation
covered in data structures classes, a \code{Dictionary} uses a \emph{hash table}
to make the average lookup time of \emph{constant order}.  A hash table depends on the
keys being immutable.


\section{Dictionary Examples}
\label{dictionaryexamples:dictionary-examples}\label{dictionaryexamples::doc}
\index{generics!HashSet}\index{HashSet}\index{set}\index{type!HashSet}

\subsection{Sets}
\label{dictionaryexamples:id1}\label{dictionaryexamples:index-0}\label{dictionaryexamples:sets}
In the next section we will have an example making central use of a dictionary.
It will also make use of a set.  The generic C\# version is
a \code{HashSet}, which models a mathematical set:  a collection
with no repetitions and no defined order.  We use a \code{HashSet} for the
words to be ignored.  We use a \code{HashSet} rather than a \code{List} because
the \code{Contains} method for a \code{List} has linear order, while the \code{Contains} method for
a \code{HashSet} uses the same trick as in a \code{Dictionary} to be of constant order on average.

Here is a csharp session using the type \code{HashSet} of strings. The \code{Add} method, like
the \code{Remove} method for Lists, returns true or false depending on whether the method
changes the set:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} var set = new HashSet\PYGZlt{}string\PYGZgt{}();
csharp\PYGZgt{} set;
\PYGZob{}  \PYGZcb{}
csharp\PYGZgt{} set.Add(\PYGZdq{}hi\PYGZdq{});
true
csharp\PYGZgt{} set;
\PYGZob{} \PYGZdq{}hi\PYGZdq{} \PYGZcb{}
csharp\PYGZgt{} set.Add(\PYGZdq{}up\PYGZdq{});
true
csharp\PYGZgt{} set;
\PYGZob{} \PYGZdq{}hi\PYGZdq{}, \PYGZdq{}up\PYGZdq{} \PYGZcb{}
csharp\PYGZgt{} set.Add(\PYGZdq{}hi\PYGZdq{});  // already there
false
csharp\PYGZgt{} set;
\PYGZob{} \PYGZdq{}hi\PYGZdq{}, \PYGZdq{}up\PYGZdq{} \PYGZcb{}
csharp\PYGZgt{} set.Contains(\PYGZdq{}hi\PYGZdq{});
true
csharp\PYGZgt{} set.Contains(\PYGZdq{}down\PYGZdq{});
false
csharp\PYGZgt{} var set2 = new HashSet\PYGZlt{}string\PYGZgt{}(new string[]\PYGZob{}\PYGZdq{}a\PYGZdq{}, \PYGZdq{}be\PYGZdq{}, \PYGZdq{}see\PYGZdq{}\PYGZcb{});
csharp\PYGZgt{} set2;
\PYGZob{} \PYGZdq{}a\PYGZdq{}, \PYGZdq{}be\PYGZdq{}, \PYGZdq{}see\PYGZdq{} \PYGZcb{}
\end{Verbatim}

That lack of order for a \code{HashSet} means it cannot
be indexed, but otherwise it has mostly the same methods and constructors
that have been discussed for a \code{List}, including \code{Add} and \code{Contains} and
a constructor that takes a collection as parameter.

\index{example!Word Count}\index{Word Count example}\index{HashSet!example}\index{List!example}

\subsection{Word Count Example}
\label{dictionaryexamples:index-1}\label{dictionaryexamples:word-count-example}
Counting the number of repetitions of words in a text provides a realistic
example of using a \code{Dictionary}.  With each word that you find, you want to associate
a number of repetitions.  A complete program is in the example file
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/count\_words/count\_words.cs}{count\_words/count\_words.cs}.

The central functions are excerpted below, and they also introduce some extra
features from the .Net libraries.

This constructor pattern taking the elements of one collection and creating another
collection, possibly of another type, is used twice: first
to create a \code{HashSet} from an array, and later to create a \code{List} from a \code{HashSet}.
The latter is needed so the \code{List} can be sorted in alphabetical order with its
\code{Sort} method, used here for the first time.  Our table contains the words in
alphabetical order.

Also used for the first time are two string methods: the pretty clearly named \code{ToCharArray} and
another variation on \code{Split}.  An alternative to supplying a single character to split on,
is to use a \code{char} array as parameter, and the string is split at an occurrence of any of the
characters in the array.  This allows a split on all punctuation and special symbol characters,
as well as a blank.

We separate the processing into two functions, one calculating the dictionary, and one printing
a table.  To reduce the amount of clutter in the \code{Dictionary}, the function
\code{GetCounts} takes as a parameter a set of words to ignore.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a Dictionary of word:count pairs from parsing s,}
      \PYG{c+c1}{///  excluding all strings in ignore. }
      \PYG{k}{public} \PYG{k}{static} \PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{\PYGZgt{}} \PYG{n}{GetCounts}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{,}
                                                      \PYG{n}{HashSet}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}} \PYG{n}{ignore}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{char}\PYG{p}{[}\PYG{p}{]} \PYG{n}{sep} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZbs{}n\PYGZbs{}t !@\PYGZsh{}\PYGZdl{}\PYGZpc{}\PYGZca{}\PYGZam{}*()\PYGZus{}+\PYGZob{}\PYGZcb{}\textbar{}[]\PYGZbs{}\PYGZbs{}:\PYGZbs{}\PYGZdq{};\PYGZlt{}\PYGZgt{}?,./\PYGZdq{}}\PYG{p}{.}\PYG{n}{ToCharArray}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{words} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{ToLower}\PYG{p}{(}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Split}\PYG{p}{(}\PYG{n}{sep}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{ignore}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{//generated from consecutive splitting characters}
         \PYG{k+kt}{var} \PYG{n}{wc} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{w} \PYG{k}{in} \PYG{n}{words}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{p}{!}\PYG{n}{ignore}\PYG{p}{.}\PYG{n}{Contains}\PYG{p}{(}\PYG{n}{w}\PYG{p}{)}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{k}{if} \PYG{p}{(}\PYG{n}{wc}\PYG{p}{.}\PYG{n}{ContainsKey}\PYG{p}{(}\PYG{n}{w}\PYG{p}{)}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{c+c1}{//increase count of word already seen}
                  \PYG{n}{wc}\PYG{p}{[}\PYG{n}{w}\PYG{p}{]}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
               \PYG{p}{\PYGZcb{}}
               \PYG{k}{else} \PYG{p}{\PYGZob{}}                   \PYG{c+c1}{// make a first entry}
                  \PYG{n}{wc}\PYG{p}{[}\PYG{n}{w}\PYG{p}{]} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
               \PYG{p}{\PYGZcb{}}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{wc}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// Print each word and its count, if the count is at least minCount. }
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{PrintCounts}\PYG{p}{(}\PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{k+kt}{int}\PYG{p}{\PYGZgt{}} \PYG{n}{wc}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{minCount}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}} \PYG{n}{words} \PYG{p}{=} \PYG{k}{new} \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{n}{wc}\PYG{p}{.}\PYG{n}{Keys}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{words}\PYG{p}{.}\PYG{n}{Sort}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{w} \PYG{k}{in} \PYG{n}{words}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{wc}\PYG{p}{[}\PYG{n}{w}\PYG{p}{]} \PYG{p}{\PYGZgt{}}\PYG{p}{=} \PYG{n}{minCount}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{}: \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{w}\PYG{p}{,} \PYG{n}{wc}\PYG{p}{[}\PYG{n}{w}\PYG{p}{]}\PYG{p}{)}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Look at the code carefully, and look at the whole program that analyses the
Gettysburg Address.


\section{Lab: File Data and Collections}
\label{lab-filedata:lab-file-data-and-collections}\label{lab-filedata::doc}

\subsection{Goals for this lab:}
\label{lab-filedata:goals-for-this-lab}\begin{itemize}
\item {} 
Read a text file.

\item {} 
Work with loops.

\item {} 
Work with a Dictionary and a List.

\item {} 
Retrieve a random entry.

\end{itemize}


\subsubsection{Overview}
\label{lab-filedata:overview}
Copy project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub}{dict\_lab\_stub} to your own project.

This lab provides a replacement file
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/fake\_help.cs}{fake\_help.cs} for an improved
project.  The project still needs some additions in a helper class.

Before we get there, open the comparison program
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/fake\_help\_verbose/fake\_help\_verbose.cs}{fake\_help\_verbose/fake\_help\_verbose.cs} and
look at the methods \code{GetParagraphs()} and \code{GetDictionary()}.
All the strings for the responses are pre-coded for you there, but if
you were writing your own methods, it would be a pain. There is all the
repetitious code to make multiline strings and then to add to the
List and Dictionary. This lab will provide simple versatile methods to
fill a \code{List\textless{}string\textgreater{}} or a \code{Dictionary\textless{}string, string\textgreater{}}: You only need
you to write the string data itself into a text file, with the only
overhead being a few extra newlines. Minor further adaptations could
save time later in a project, too.

Look in your copy of
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/fake\_help.cs}{fake\_help.cs}.
It creates the \code{List} \code{guessList} and the
\code{Dictionary} \code{responses} using more general functions that you need to fill in.
The stubs for these new versions are put in
the class \code{FileUtil} for easy reuse.  \code{Main} calls these functions
and chooses the files to read.
The results will look the same as the original program to the user,
but the second version will be easier
for a programmer to read and generalize:  It will be easier in other situations
where you want lots of canned data
in your program (like in a game you might write soon).

The stub should run as is
(mostly saying things are not implemented).
Test out your work at every stage!

You will need to complete very short versions of functions
\code{GetParagraphs} and \code{GetDictionary} that have been moved to
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/file\_util.cs}{file\_util.cs}
and now
take a \code{StreamReader} as parameter.
The files that they read will contain the basic data.
You can look in the lab project at the first data file:
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/help\_not\_defaults.txt}{help\_not\_defaults.txt},
and the beginning is shown below:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Welcome to We\PYGZhy{}Give\PYGZhy{}Answers!
What do you have to say?

We\PYGZhy{}Give\PYGZhy{}Answers 
thanks you for your patronage.
Call again if we can help you 
with any other problem!

No other customer has ever complained 
about this before.  What is your system 
configuration?

That sounds odd. Could you describe 
that problem in more detail?
\end{Verbatim}

You can see that it includes the data for the welcome
and goodbye strings followed by all the data to go in the \code{List} of random answers.

One complication is that many of these strings take up several lines, in what we call
a \emph{paragraph}.  We follow a standard convention for putting paragraphs into plain text:
Put a blank line after a paragraph to mark its end.  As you can see, that is how
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/help\_not\_defaults.txt}{help\_not\_defaults.txt} is set up.


\subsection{Steps}
\label{lab-filedata:steps}
All of the additions you need to make are in bodies of function
definitions in the class \code{FileUtil}.  Look back to \code{Main} in \code{FakeAdvise} to
see how the functions from \code{FileUtil} are actually used:  The
\code{StreamReader} is set up to read from the right file.  The the \code{FileUtil} functions
\code{ReadParagraph}, \code{GetParagraphs}, and \code{GetDictionary} are used to provide
the text data needed.


\subsubsection{ReadParagraph}
\label{lab-filedata:readparagraph}
The first method to complete in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/file\_util.cs}{file\_util.cs}
is useful by itself and later for use in the
\code{GetParagraphs} and \code{GetDictionary} that you will complete.  See the stub:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a string consisting of a sequence of nonempty lines read}
      \PYG{c+c1}{/// from reader. All the newlines at the ends of these lines are included.}
      \PYG{c+c1}{/// The function ends after reading (but not including) an empty line.}
      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{ReadParagraph}\PYG{p}{(}\PYG{n}{StreamReader} \PYG{n}{reader}\PYG{p}{)}
\end{Verbatim}

The first call to \code{ReadParagraph}, using the file illustrated above, should
return the following (showing the escape codes for the newlines):

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{l+s}{\PYGZdq{}Welcome to We\PYGZhy{}Give\PYGZhy{}Answers!\PYGZbs{}nWhat do you have to say?\PYGZbs{}n\PYGZdq{}}
\end{Verbatim}

and then the reader should be set to read the goodbye paragraph
(the next time \code{ReadParagraph} is called).

To code, you can read lines one at a time, and append them to the part of the
paragraph read so far. There is one thing to watch out for: The
\code{ReadLine} function \emph{throws away} the following newline (\code{"\textbackslash{}n"}) in the input. You
need to preserve it, so be sure to explicitly add a newline, back onto
your paragraph string after each nonempty line is added. The returned
paragraph should end with a single newline.

Throw away the empty line
in the input after the paragraph. Make sure you stop after reading
the empty line.  It is very important that you advance the reader
to the right place, to be ready to read the next paragraph.

Be careful of a pitfall with files:  You can only read a given chunk once:
If you read again, with the exact same syntax,
you get the \emph{next} line of the file.  The \code{ReadLine} method
has the \emph{side effect} of advancing the reading position in the file.

\textbf{Testing}: This first short \code{ReadParagraph} function should actually be most of
the code that you write for the lab!  The program is set up so you can immediately
run the program and test \code{ReadParagraph}:  It is called to read in the welcome string
and the goodbye string for the program, so if those come correctly to the screen, you
can advance to the next two parts.


\subsubsection{GetParagraphs}
\label{lab-filedata:getparagraphs}
Since you have \code{ReadParagraph} at your disposal, you now only need to
insert a \emph{few remaining lines of code} to complete the next method
\code{GetParagraphs}, that reads to the end of the file, and likely
processes more than one paragraph.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Read the remaining empty\PYGZhy{}line terminated paragraphs}
      \PYG{c+c1}{/// from reader into a new list of paragraph strings,}
      \PYG{c+c1}{/// and return the list.}
      \PYG{c+c1}{/// The function reads all the way to the end of}
      \PYG{c+c1}{/// the file attached to reader.}
      \PYG{c+c1}{/// The file must end with two newlines in sequence: one at the}
      \PYG{c+c1}{/// end of the last nonempty line followed by one for the empty line.}
      \PYG{k}{public} \PYG{k}{static} \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}} \PYG{n}{GetParagraphs}\PYG{p}{(}\PYG{n}{StreamReader} \PYG{n}{reader}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}} \PYG{n}{all} \PYG{p}{=} \PYG{k}{new} \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}

         \PYG{c+c1}{// REPLACE the next line with your lines of code to fill all}
         \PYG{n}{all}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}You have not coded GetParagraphs yet!\PYGZbs{}n\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}

         \PYG{k}{return} \PYG{n}{all}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Look again at
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/help\_not\_defaults.txt}{help\_not\_defaults.txt},
to see how the data is set up.

This lab requires very few lines of code. Be sure to read the examples
and instructions carefully (several times). A lot of ideas get packed
into the few lines!

\textbf{Testing}: After writing \code{GetParagraphs}, the random
responses in the lab project program should work as the user enters lines in the program.


\subsubsection{GetDictionary}
\label{lab-filedata:getdictionary}
The last stub to complete in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/file\_util.cs}{file\_util.cs}
is \code{GetDictionary}.  Its
stub also takes a \code{StreamReader} as parameter.  In
\code{Main} this function is called to read from
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/help\_not\_responses.txt}{help\_not\_responses.txt}.
Here are the first few lines:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
crash
Well, it never crashes on our system. 
It must have something to do with your system. 
Tell me more about your configuration.

slow
I think this has to do with your hardware. 
Upgrading your processor should solve all 
performance problems. 
Have you got a problem with our software?

performance
Performance was quite adequate in all our tests. 
Are you running any other processes in the background?
\end{Verbatim}

Here is the stub of the function to complete, reading such data:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a new Dictionary, taking data for it from reader.}
      \PYG{c+c1}{/// Reader contains key\PYGZhy{}value pairs, where each single\PYGZhy{}line key is}
      \PYG{c+c1}{/// followed by a possibly multi\PYGZhy{}line paragraph value that is terminated}
      \PYG{c+c1}{/// by an empty line. The file must end with two newlines in sequence:}
      \PYG{c+c1}{/// one at the end of the last nonempty line followed by one for the}
      \PYG{c+c1}{/// empty line.}
      \PYG{k}{public} \PYG{k}{static} \PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{k+kt}{string}\PYG{p}{\PYGZgt{}} \PYG{n}{GetDictionary}\PYG{p}{(}\PYG{n}{StreamReader} \PYG{n}{reader}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{k+kt}{string}\PYG{p}{\PYGZgt{}} \PYG{n}{d} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{k+kt}{string}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}

         \PYG{c+c1}{// add your lines of code to fill d here!}

         \PYG{k}{return} \PYG{n}{d}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\textbf{Testing}:
When you complete this function, the program should behave
just like the earlier
verbose version with the hard-coded data, using a dictionary value
if it finds the right key,
or choosing a random response if there is no key match.

Be careful to distinguish the data file
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/help\_not\_responses.txt}{help\_not\_responses.txt}
from
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/help\_not\_responses2.txt}{help\_not\_responses2.txt},
used in the extra credit option.

This should also be an extremely short amount of coding!
Think of following through the data file, and get the corresponding
sequence of instructions to handle the data in the exact same sequence.

Show the program output to a TA (after the extra credit if you like).


\subsubsection{Extra credit}
\label{lab-filedata:extra-credit}\begin{enumerate}
\item {} 
(20\%) Modify ReadParagragh so it \emph{also} works if the paragraph ends
at the end of the file, with no blank line after it, or if the line after
the paragraph only has whitespace characters.  Both changes are good to
bullet-proof the code, since
the added or removed whitespace is hard to see in print.

\item {} 
(20\%) The crude word classification scheme would recognize ``crash'', but not
``crashed'' or ``crashes''.  You could make whole file entries
for each key variation, repeating the value paragraph.
A concise approach is to use a data file
like \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/dict\_lab\_stub/help\_not\_responses2.txt}{help\_not\_responses2.txt}.
Here are the first few lines:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
crash crashes crashed
Well, it never crashes on our system. 
It must have something to do with your system. 
Tell me more about your configuration.

slow slowly
I think this has to do with your hardware. 
Upgrading your processor should solve all 
performance problems. 
Have you got a problem with our software?

performance
Performance was quite adequate in all our tests. 
Are you running any other processes in the background?
\end{Verbatim}

The line that used to have one key now may have several blank-separated keys.

Here is how the documentation for \code{GetDictionary} should be changed:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a new Dictionary, taking data for it from reader.}
      \PYG{c+c1}{/// Reader generates key\PYGZhy{}value pairs, where one or more space}
      \PYG{c+c1}{/// separated keys on a line are followed by a possibly multi\PYGZhy{}line}
      \PYG{c+c1}{/// paragraph value that is terminated by an empty line.  Each}
      \PYG{c+c1}{/// key on the line is mapped to the same paragraph that follows.}
      \PYG{c+c1}{/// The file must end with two newlines in sequence:  one at the end}
      \PYG{c+c1}{/// of the last nonempty line followed by one for the empty line.}
\end{Verbatim}

Modify the lab project to use this file effectively:  Find
``help\_not\_responses.txt'' on line 22 in \code{Main}.  Change it to
``help\_not\_responses2.txt'' (inserting `2'), so \code{Main} reads it.

In your test of the program, be sure to use several of the keys that apply to the
same response, and show to your TA.

\end{enumerate}


\section{Chapter Review Questions}
\label{reviewdictionaries:chapter-review-questions}\label{reviewdictionaries::doc}\begin{enumerate}
\item {} 
Which is true for a \code{Dictionary}: is it mutable or immutable?

\item {} 
Though for some collections, like arrays and lists,
you can fairly easily replace a \code{foreach}
loop with a \code{for} loop, that is not the case if you want to iterate
through a \code{Dictionary}.  How do you go through all the keys in
a \code{Dictionary}?

\item {} 
What syntax is there for a \code{Dictionary} that matches that for a \code{List}?

\item {} 
How is a \code{Dictionary} like an array?  How is it different?

\item {} 
\code{Dictionary} values are of arbitrary type. What is the restriction on
key types?

\item {} 
How is a \code{HashSet} different than a \code{List}?

\item {} 
What syntax is shared between a \code{List} and a \code{HashSet}?

\item {} 
Which is more efficient in general:
searching for an element of a list or finding the
value given a key in a dictionary?

\end{enumerate}

\index{class}\index{type!user defined object}

\chapter{Classes and Object-Oriented Programming}
\label{classes:index-0}\label{classes:classes}\label{classes::doc}\label{classes:classes-and-object-oriented-programming}
\index{class!Contact}\index{Contact class}\index{instance of a class}

\section{A First Example of Class Instances: Contact}
\label{a-first-class:a-first-example-of-class-instances-contact}\label{a-first-class:index-0}\label{a-first-class::doc}\label{a-first-class:class}

\subsection{Making a Datatype}
\label{a-first-class:making-a-datatype}
C\# comes with lots of built-in datatypes, but not
everything we might want to use.  We start with a very simple example of
building your own new type of object:  Contact information for a person
involves several pieces of data, and they are all unified by the fact
that they are for one person, so we would like to store them together
as a unit.  For simplicity, let us just consider the contact information to be
name, phone number, and email address.

You could always keep three independent string variables,
but conceptually the main idea is \emph{the} contact.  It just happens
to have parts.

In order to treat a contact as  \emph{one} entity, we create a \code{class},
\code{Contact}.
This way we can have a single
variable refer to a \code{Contact} object.  Such an object is an \emph{instance} of the
class.

It is important to distinguish between a class and an instance of a class:
A class provides a template or instructions to make new instance objects.  A
common comparison is that a class is like a cookie cutter while an
instance of the class is like a cookie.
You might consider constructor parameters as being for different decorations
on different cookies, so not all cookies must end up completely the same.

Later we will see an example for rational
numbers, {\hyperref[rational:rational]{\emph{The Rational Class}}},
where the parts of the class are more tightly integrated, but that is more
complicated, so we defer it.

We have already considered built-in types with internal state, like a \code{List}:
Each \code{List} can contain different data, and the internal data can be changed.

The idea of creating a new type of object opens new ground for managing data.
Thus far we have stored data as local variables, and we have called functions,
with two ways to get information in and out of functions:
\begin{enumerate}
\item {} 
In through parameters and out through returned data.

\item {} 
Directly via the user: in through the keyboard and out to the screen.

\end{enumerate}

We have stored and passed around built-in types of object using this model.

We have alternatives for storing and accessing data in the methods within
a new class that we write.
Now we have the idea of an object that has \emph{internal} state
(like a contact with a name, phone, and email).  We shall see that
this state is \emph{not}
stored in local variables and does \emph{not} need to be passed through parameters for
methods \emph{within} the class.
Pay careful attention as we introduce this new location for data and the new ways
of interacting with it.

This is quite a shift.
\emph{Do not take it lightly.}

\index{OOP!constructor}\index{constructor}\index{new as operator}\index{operator!new}
We can create a new object with the \code{new} syntax.
We can give parameters defining the initial state of the new object.
In our example the obvious thing to do is supply parameters giving
values for the three parts of the object state, so we can plan that

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Contact} \PYG{n}{c} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Contact}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Marie Ortiz\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}773\PYGZhy{}508\PYGZhy{}7890\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}mortiz2@luc.edu\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

would create a new Contact storing the data.  A Contact object, created with
\code{new} is an \emph{instance} of the class Contact.

Like with built-in types, we can have the natural operations on the
type as \emph{methods}.  For instance we can
\begin{itemize}
\item {} 
look up individual pieces of the contact data with methods
\code{GetName}, \code{GetPhone} and \code{GetEmail}

\item {} 
print it all out together, labeled, with method \code{Print}.

\end{itemize}

Thinking ahead to what we would like for our Contact objects, here is
the testing code of \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/contact1/test\_contact1.cs}{contact1/test\_contact1.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{TestContact}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Contact} \PYG{n}{c1} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Contact}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Marie Ortiz\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}773\PYGZhy{}508\PYGZhy{}7890\PYGZdq{}}\PYG{p}{,} 
                                  \PYG{l+s}{\PYGZdq{}mortiz2@luc.edu\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Contact} \PYG{n}{c2} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Contact}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Otto Heinz\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}773\PYGZhy{}508\PYGZhy{}9999\PYGZdq{}}\PYG{p}{,} 
                                  \PYG{l+s}{\PYGZdq{}oheinz@luc.edu\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Marie\PYGZsq{}s full name: \PYGZdq{}} \PYG{p}{+} \PYG{n}{c1}\PYG{p}{.}\PYG{n}{GetName}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Her phone number: \PYGZdq{}} \PYG{p}{+} \PYG{n}{c1}\PYG{p}{.}\PYG{n}{GetPhone}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Her email: \PYGZdq{}} \PYG{p}{+} \PYG{n}{c1}\PYG{p}{.}\PYG{n}{GetEmail}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}         
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZbs{}nFull contact info for Otto:\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{c2}\PYG{p}{.}\PYG{n}{Print}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;} 
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

When running this testing code, we would like the results:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Marie\PYGZsq{}s full name: Marie Ortiz
Her phone number: 773\PYGZhy{}508\PYGZhy{}7890
Her email: mortiz2@luc.edu

Full contact info for Otto:
Name:  Otto Heinz
Phone: 773\PYGZhy{}508\PYGZhy{}9999
Email: oheinz@luc.edu
\end{Verbatim}

We are using the same object oriented notation that we have for many other classes:
\emph{Calls to instance methods are always attached to a specific object.}
That has always been
the part through the \code{.} of
\begin{quote}

\emph{object}\code{.}\emph{method}\code{(}  ... \code{)}
\end{quote}

So far we have been thinking and illustrating how we would like objects in this
Contact class to look like and behave from the \emph{outside}.  We could be
describing another library class.  Now, for the first time,
we start to delve inside,
to the code and concepts needed to make this happen.
We start with the most basic parts.  First we need a \code{class}:


\subsection{Class Syntax}
\label{a-first-class:class-syntax}
Our code is nested inside

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{Contact}
\PYG{p}{\PYGZob{}}

   \PYG{c+c1}{// ... fields, constructor, code for Contact omitted}

\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This is the same sort of wrapper we have used for our Main programs!
\emph{Before}, everything inside was
labeled \code{static}.  Now we see what happens with the \code{static} keyword
\emph{omitted}....

\index{OOP!instance variable}\index{instance variable}\index{variable!instance}\index{private!instance variable}

\subsection{Instance Variables}
\label{a-first-class:index-2}\label{a-first-class:instance-variables}
A Contact has a name, phone number and email address.  We must remember that data.
Each individual Contact that we use will have its own
name, phone number and email address.

We have used some static variables before in classes, with the keyword \code{static},
where there is just one copy for the whole class.  If we omit the \code{static} we get
an \emph{instance variable}, that is the particular data for an \emph{individual} Contact,
for an individual instance of the class.
This is our new place to store data:

We declare these \emph{in} the class and \emph{outside} any method declaration.
(This is in the same place as we would store {\hyperref[staticvariables:static-variables]{\emph{Static Variables}}}).

They are \emph{fields} of the class.  As we will
discuss more in terms of safety and security,
we add the word ``private'' at the beginning:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{Contact}
\PYG{p}{\PYGZob{}}
   \PYG{k}{private} \PYG{k+kt}{string} \PYG{n}{name}\PYG{p}{;}
   \PYG{k}{private} \PYG{k+kt}{string} \PYG{n}{phone}\PYG{p}{;}
   \PYG{k}{private} \PYG{k+kt}{string} \PYG{n}{email}\PYG{p}{;}

   \PYG{c+c1}{// ... constructor, code for Contact omitted}

\PYG{p}{\PYGZcb{}}
\end{Verbatim}

You also see that we are lazy in this example,
and abbreviate the longer descriptions fullName, phoneNumber and
emailAddress.

\index{lifetime}
It is important to distinguish \emph{instance} variables of a class
and \emph{local} variables.
A local variable is only accessible inside the block (surrounded by braces)
where it was declared,
and is destroyed at the end of the execution of that block.
However the class fields  \code{name}, \code{phone} and \code{email} are remembered by C\#
as long as the Contact object is in use.

The \emph{lifetime} of a variable is from when it is first created until it is no
longer accessible by the program.  We repeat:

\begin{notice}{note}{Note:}
\emph{Instance} variable have a completely different lifetime and scope
from \emph{local} variables.
An object and its instance variables,
persist from the time a new object is created
with \code{new} for as long as the object
remains referenced in the program.
\end{notice}

We need to get values into our field variables.
They describe the state of our Contact.

We have \emph{used} constructors for built-in types.
Now for the first time we \emph{create} one.

\index{OOP!constructor}\index{constructor}

\subsection{Constructors}
\label{a-first-class:index-4}\label{a-first-class:constructors}
The constructor is a slight variation on a regular method:
Its name is the same as the
kind of object constructed, so here it is the class name, Contact.
It has \emph{no return type} (and \emph{no} \code{static}).  Implicitly you
are creating the kind of object named, a \textbf{Contact} in this case.
The constructor can have parameters like a regular method.  We will certainly
want to give a state to our new object.
That means giving values to its fields.  Recall we are want to
store this state in instance variables \code{name}, \code{phone} and \code{email}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{n+nf}{Contact}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{fullName}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{phoneNumber}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{emailAddress}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{n}{name} \PYG{p}{=} \PYG{n}{fullName}\PYG{p}{;}
         \PYG{n}{phone} \PYG{p}{=} \PYG{n}{phoneNumber}\PYG{p}{;}
         \PYG{n}{email} \PYG{p}{=} \PYG{n}{emailAddress}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

While the local variables in the formal parameters
disappear after the constructor terminates,
we want the data to live on as the state of the object.
In order to remember state after the constructor terminates,
we must \emph{make sure the information gets into the instance variables}
for the object.
This is the basic operation of most constructors:  Copy desired formal
parameters in to initialize the state in the fields.  That is all our simple
code above does.

Note that \code{name}, \code{phone} and \code{email} are \emph{not} declared as
local variables.  They refer to the \emph{instance} variables, but we are \emph{not} using
full object notation: an object reference and a
dot, followed by the field.

So far always we have always been referring to a built-in type of object
defined in a different class, like \code{arrayObject.Length}.
The constructor is \emph{creating} an object,
and the use of the bare instance variable names is understood to be giving
values to the instance variables in this Contact object
that is being constructed.
Inside a constructor
and also inside an instance method
(discussed below)
C\# allows this shorthand notation without \code{someObject.}.

\index{OOP!instance method}\index{instance method}\index{method}

\subsection{Instance Methods}
\label{a-first-class:index-5}\label{a-first-class:instance-methods}\label{a-first-class:id1}
The instance variable names and method names
used without an object reference and dot refer to the
\emph{current} instance.  Whenever a constructor or non-static method in the class is called,
there is \emph{always} a current object:
\begin{enumerate}
\item {} 
In a constructor, referring to the object being created.  In execution,
a static method like \code{Main} must create the first object.

\item {} 
When some instance method \code{methodName} is called with explicit dot notation,
\code{someObject.methodName()},
then it is acting on the current object \code{someObject}.  In any program's
execution the first call to an instance method must either be in this explicit
form or from within a constructor for a new object.

\item {} 
If that constructor or instance method calls a
further instance method inside the same class, without using dot notation,
then the further method has the \emph{same} current object....
We will see examples of this as we go along.

\end{enumerate}

Again, this means that in execution, whenever an instance method is called,
there \emph{is} a \emph{current specific object}.  This is the object associated
with any instance variable or method referred to in that method,
if there is not an explicit prefix in the \code{someObject.} form.  This will
take practice to get used to.

\index{OOP!getter}\index{getter method}

\subsection{Getters}
\label{a-first-class:index-6}\label{a-first-class:getters}\label{a-first-class:id2}
In instance methods
you have an extra way of getting
data in and out of the method:  Reading or setting instance variables.
(As we have just pointed out, in execution there will always be a current object
with its specific state.)
The simplest methods do nothing but reading or setting instance variables.
We start with those:

The \code{private} in front
of the field declarations was important to keep code outside the
class from messing with the values.  On the other hand we do want
others to be able to \emph{inspect} the name, phone and email,
so how do we do that?  Use \textbf{public methods}.

Since the fields are accessible anywhere \emph{inside} the class's instance methods,
and public methods can be used from \emph{outside} the class, we can simply code

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{k+kt}{string} \PYG{n+nf}{GetName}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{name}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k+kt}{string} \PYG{n+nf}{GetPhone}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{phone}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
                             
      \PYG{k}{public} \PYG{k+kt}{string} \PYG{n+nf}{GetEmail}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{email}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

These methods allow one-way communication of the name, phone and email
values out from the object.
These are examples
of a simple category of methods:  A \emph{getter} simply returns the value of a part
of the object's state, without changing the object at all.

Note again that there is no \code{static} in the method heading.
The field value for the \emph{current} Contact is returned.

A standard convention that we are following:
Have getter methods names start with ``Get'',
followed by the name of the data to be returned.

In this first simple version of Contact we add one further method, to
print all the contact information with labels.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{Print}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{@\PYGZdq{}Name:  \PYGZob{}0\PYGZcb{}}
\PYG{l+s}{Phone: \PYGZob{}1\PYGZcb{}}
\PYG{l+s}{Email: \PYGZob{}2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{name}\PYG{p}{,} \PYG{n}{phone}\PYG{p}{,} \PYG{n}{email}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Again, we use the instance variable names, plugging them into a format string.
Remember the \code{@} syntax
for multiline strings from {\hyperref[data_strings2:strings2]{\emph{String Special Cases}}}.

You can see and see the entire Contact class
in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/contact1/contact1.cs}{contact1/contact1.cs}.

This is our first complete class defining a new type of object.
Look carefully to get used to the features introduced, before we add
more ideas:

\index{example!Contact version 2}
\index{OOP!this}\index{this instance}

\subsection{This Object}
\label{a-first-class:this-object}\label{a-first-class:index-8}
We will be making an elaboration on the Contact class from here on.  We introduce
new parts individually, but the whole code is in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/contact2/contact2.cs}{contact2/contact2.cs}.

The current object is \emph{implicit} inside a constructor or instance method definition,
but it can be referred to \emph{explicitly}.  It is called \code{this}.
In a constructor or instance method, \code{this} is automatically a legal
local variable to reference.
You usually do not need to
use it explicitly, but you could.   For example the current \code{Contact} object's
\code{name} field could be referred to as either \code{this.name} or the shorter plain \code{name}.
In our next version of the Contact class we will see several places where
an explicit \code{this} is useful.

In the first version of the constructor, repeated here,

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{n+nf}{Contact}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{fullName}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{phoneNumber}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{emailAddress}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{n}{name} \PYG{p}{=} \PYG{n}{fullName}\PYG{p}{;}
         \PYG{n}{phone} \PYG{p}{=} \PYG{n}{phoneNumber}\PYG{p}{;}
         \PYG{n}{email} \PYG{p}{=} \PYG{n}{emailAddress}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

we used different names for the instance variables and the formal
parameter names that we used to initialize the instance variables.  We
chose reasonable names, but we are adding extra names that we are not going
to use later, and it can be confusing.  The most obvious names for the formal
parameters that will initialize the instance variables are the \emph{same} names.

If we are not careful, there is a problem with that.  An instance variable,
however named, and a local variable are not the same.  This is
nonsensical:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{n+nf}{Contact}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{name}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{phone}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{email}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{n}{name} \PYG{p}{=} \PYG{n}{name}\PYG{p}{;} \PYG{c+c1}{// ????}
   \PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
\end{Verbatim}

Logically we want this pseudo-code in the constructor:
\begin{quote}

instance variable \code{name}  \code{=} local variable \code{name}
\end{quote}

We have to disambiguate the two uses.  The compiler always looks for
\emph{local} variable identifiers \emph{first}, so plain \code{name} will refer to the local
variable \code{name} declared in the formal parameter list.
This local variable identifier  \emph{hides} the matching instance variable
identifier.  We have to do something else to refer to the instance variable.
The explicit \code{this} object comes to the rescue:  \code{this.name} refers to
a part of this object.  It must refer to the
instance variable, not the local variable.  Our alternate constructor is:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{n+nf}{Contact}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{name}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{phone}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{email}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{this}\PYG{p}{.}\PYG{n}{name} \PYG{p}{=} \PYG{n}{name}\PYG{p}{;}
         \PYG{k}{this}\PYG{p}{.}\PYG{n}{phone} \PYG{p}{=} \PYG{n}{phone}\PYG{p}{;}
         \PYG{k}{this}\PYG{p}{.}\PYG{n}{email} \PYG{p}{=} \PYG{n}{email}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}


\subsection{Setters}
\label{a-first-class:setters}
The original version of Contact makes a Contact object be
\emph{immutable}:  Once it is created with the constructor, there is no way
to change its internal state.  The only assignments to the private
instance variables are the ones in the constructor.  In real life
people can change their email address.  We might like to allow that
with our Contact objects.  Users can read the data in a Contact with the
\emph{getter} methods.  Now we need \emph{setter} methods.  The naming conventions
are similar:  start with ``Set''.  In this case we must supply the new data,
so setter methods need a parameter:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{SetPhone}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{newPhone}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{n}{phone} \PYG{p}{=} \PYG{n}{newPhone}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

In \code{SetPhone}, like in our original constructor, we illustrate using a
\emph{new} name for the parameter that sets the instance variable.  For
comparison we use the alternate identifier matching approach in the
other setter:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{SetEmail}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{email}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{this}\PYG{p}{.}\PYG{n}{email} \PYG{p}{=} \PYG{n}{email}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Now we can alter the contents of a Contact:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Contact} \PYG{n}{c1} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Contact}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Marie Ortiz\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}773\PYGZhy{}508\PYGZhy{}7890\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}mortiz2@luc.edu\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{c1}\PYG{p}{.}\PYG{n}{SetEmail} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}maria.ortiz@gmail.com\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{c1}\PYG{p}{.}\PYG{n}{SetPhone}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}555\PYGZhy{}555\PYGZhy{}5555\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{c1}\PYG{p}{.}\PYG{n}{Print}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

would print

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Name:  Marie Ortiz
Phone: 555\PYGZhy{}555\PYGZhy{}5555
Email: maria.ortiz@gmail.com
\end{Verbatim}

\index{ToString}\index{override}

\subsection{ToString Override}
\label{a-first-class:tostring-override}\label{a-first-class:index-9}
We created the \code{Print} method for a Contact, and it is helpful to
assemble all the data for display \emph{and} print it.   The issue there is that
the method does two \emph{separate} clear things:  combining the string data
and printing it.  You might want the same string but put in a file or
used some other way.  Our \code{Print} method will not help.

A good design decision is to separate the different actions:  the first is
to generate the 3-line string showing the full state of the object.  Once
we have this string, we can easily print it or write it to a file or ....
Hence we want a method to generate a descriptive string.

Think more generally about string representations:
All the built-in types can be concatenated into strings with the `+' operator,
or displayed with \code{Console.Write}.
We would like that behavior with our custom types, too.  How can the compiler
know how to handle types that were \emph{not invented} when the compiler was written?

The answer is to have common features among all objects.
Any object has a \code{ToString}
method, and that method is used implicitly when an object is used with
string concatenation, and also for \code{Write}.
The default version supplied by the system is not very useful for an object
that it knows nothing about!  You need to define your own version,
one that knows how you have defined
your type, with its own specific instance variables.
You need to have that version used \emph{in place of} the default:
You need to \emph{override} the default.  To emphasize the \emph{change}
in meaning, the word \code{override} \emph{must} be in the heading:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{k}{override} \PYG{k+kt}{string} \PYG{n+nf}{ToString}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k+kt}{string}\PYG{p}{.}\PYG{n}{Format} \PYG{p}{(}\PYG{l+s}{@\PYGZdq{}Name:  \PYGZob{}0\PYGZcb{}}
\PYG{l+s}{Phone: \PYGZob{}1\PYGZcb{}}
\PYG{l+s}{Email: \PYGZob{}2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{name}\PYG{p}{,} \PYG{n}{phone}\PYG{p}{,} \PYG{n}{email}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

See what the method does:  it uses the object state to create and
\emph{return} a single string representation of the object.

For any kind of new object that you create and want to be able to implicitly convert to
a string, you need a \code{ToString} method with the \emph{exact} same heading
as the \code{ToString} for a Contact.

A more complete discussion of \code{override}
would lead us into class hierarchies and
inheritance, which we are not emphasizing in this book.

We still might like to have a convenience method \code{Print}.  It now can
be written much more easily, using our latest \code{ToString}.

We want one instance method,
\code{Print} to call another instance method \code{ToString} for the \emph{same} object.
How does this work?  It is like when instance method \code{GetName}
refers to an instance variable
\code{name} without using dot notation.  Then \code{name} is assumed to refer to
this object associated with the call to \code{GetName}.  We can change our
\code{Print} definition to:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{Print}\PYG{p}{(}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{ToString}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Here \code{ToString()} is a method called without dot notation explicitly
attaching it to an object.
As with instance variables, it is implicitly attached to this object, the one
attached to the call to \code{Print}.

Again, the whole code for the elaborated Contact is in example
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/contact2/contact2.cs}{contact2/contact2.cs}.

New testing code is in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/contact2/test\_contact2.cs}{contact2/test\_contact2.cs}.  Run the project
and check that it does what you would expect.  There are several new
features illustrated in the testing code:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Contact} \PYG{n}{c1} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Contact}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Marie Ortiz\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}773\PYGZhy{}508\PYGZhy{}7890\PYGZdq{}}\PYG{p}{,} 
                                  \PYG{l+s}{\PYGZdq{}mortiz2@luc.edu\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Contact} \PYG{n}{c2} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Contact}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Otto Heinz\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}773\PYGZhy{}508\PYGZhy{}9999\PYGZdq{}}\PYG{p}{,} 
                                  \PYG{l+s}{\PYGZdq{}oheinz@luc.edu\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Marie\PYGZsq{}s full name: \PYGZdq{}} \PYG{p}{+} \PYG{n}{c1}\PYG{p}{.}\PYG{n}{GetName}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Her phone number: \PYGZdq{}} \PYG{p}{+} \PYG{n}{c1}\PYG{p}{.}\PYG{n}{GetPhone}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Her email: \PYGZdq{}} \PYG{p}{+} \PYG{n}{c1}\PYG{p}{.}\PYG{n}{GetEmail}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}         
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}All together:\PYGZbs{}n\PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{c1}\PYG{p}{)}\PYG{p}{;} 
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Full contact info for Otto:\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{c2}\PYG{p}{.}\PYG{n}{Print}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;} 
         \PYG{n}{c1}\PYG{p}{.}\PYG{n}{SetEmail}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}maria.ortiz@gmail.com\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{c2}\PYG{p}{.}\PYG{n}{SetPhone}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}123\PYGZhy{}456\PYGZhy{}7890\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}With changes and added contact:\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{var} \PYG{n}{allc} \PYG{p}{=} \PYG{k}{new} \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{n}{Contact}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Contact}\PYG{p}{[}\PYG{p}{]} \PYG{p}{\PYGZob{}}\PYG{n}{c1}\PYG{p}{,} \PYG{n}{c2}\PYG{p}{,} 
            \PYG{k}{new} \PYG{n+nf}{Contact}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Amy Li\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}847\PYGZhy{}111\PYGZhy{}2222\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}amy.li22@yahoo.com\PYGZdq{}}\PYG{p}{)}\PYG{p}{\PYGZcb{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{foreach}\PYG{p}{(}\PYG{n}{Contact} \PYG{n}{c} \PYG{k}{in} \PYG{n}{allc}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZbs{}n\PYGZdq{}}\PYG{p}{+}\PYG{n}{c}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Contact is now a type we can use with other types.  \code{Main} ends creating
a \code{List\textless{}Contact\textgreater{}} and an array of Contacts, and processes Contacts in the
\code{List} with a \code{foreach} loop.

We mentioned that this particular signature in the
\code{ToString} heading means that the system recognizes it in string
concatenation and in substitutions into a \code{Write} or \code{WriteLine}
format string.  Find both in \code{Main}.

The \code{ToString} override also means that the body of our \code{Print}
definition in the Contact class could have been
even shorter, using the object \code{this}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{Print}\PYG{p}{(}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{k}{this}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

When we use \code{Console.WriteLine} on this current object, which is \emph{not}
already a string, there is an automatic call to \code{ToString}.

\index{redeclaring instance variables error}\index{compiler error!before error in text}\index{instance variable!redeclaring error}

\subsection{Local Variables Hiding Instance Variables}
\label{a-first-class:local-variables-hiding-instance-variables}\label{a-first-class:id3}\label{a-first-class:index-10}
A common error is for students to try to declare the instance variables twice,
once in the regular instance variable declarations,
\emph{outside of any constructor or method} and then again \emph{inside} a
constructor, like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{n+nf}{Contact}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{fullName}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{phoneNumber}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{emailAddress}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{k+kt}{string} \PYG{n}{name} \PYG{p}{=} \PYG{n}{fullName}\PYG{p}{;}      \PYG{c+c1}{// LOGICAL ERROR!}
   \PYG{k+kt}{string} \PYG{n}{phone} \PYG{p}{=} \PYG{n}{phoneNumber}\PYG{p}{;}  \PYG{c+c1}{// LOGICAL ERROR!}
   \PYG{k+kt}{string} \PYG{n}{email} \PYG{p}{=} \PYG{n}{emailAddress}\PYG{p}{;} \PYG{c+c1}{// LOGICAL ERROR}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

This is deadly.  It is worse than redeclaring a local variable, which at least will
trigger a compiler error.

\begin{notice}{warning}{Warning:}
Instance variable \emph{only} get declared outside of all
functions and constructors.  Same-name
local variable declarations hide the
instance variables, but \emph{compile just fine}.  The local variables disappear
after the constructor ends, leaving the instance variables
\emph{without} your desired initialization. Instead the hidden instance variables
just get the default initialization, \code{null} for an object
or 0 for a number.
\end{notice}

There is a related strange compiler error.  This is not likely to happen frequently,
but thinking through its logic (or illogic) could be helpful in understanding
local and instance variables:
Generally when you get a compiler error, the error is at or \emph{before} the location the
error is referenced, but with local variables covering instance variables,
the real cause can come later in the text of the method.  Below, when you first
refer to \code{r} in \code{Badnames}, it appears to be correctly referring to the
instance variable \code{r}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{class} \PYG{n+nc}{ForwardError}
\PYG{p}{\PYGZob{}}
    \PYG{k}{private} \PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{l+m}{3}\PYG{p}{;}

    \PYG{c+c1}{// ...}

    \PYG{k}{void} \PYG{n+nf}{BadNames}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{b}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
        \PYG{k+kt}{int} \PYG{n}{n} \PYG{p}{=} \PYG{n}{a}\PYG{p}{*}\PYG{n}{r} \PYG{p}{+} \PYG{n}{b}\PYG{p}{;} \PYG{c+c1}{// legal in text *just* to here; instance field r}
        \PYG{c+c1}{//...}
        \PYG{k+kt}{int} \PYG{n}{r} \PYG{p}{=} \PYG{n}{a} \PYG{p}{\PYGZpc{}} \PYG{n}{b}\PYG{p}{;} \PYG{c+c1}{// r declaration makes *earlier* line wrong}
        \PYG{c+c1}{//...}
    \PYG{p}{\PYGZcb{}}
\end{Verbatim}

The compiler scans through \emph{all} of \code{BadNames}, and sees the \code{r} declared locally
in its scope.
The error may be marked on the earlier line, where the compiler then assumes
\code{r} is the later declared local \code{int} variable, not the instance variable.
The error it sees is a local variable used before declaration.

This is based on a real student example.
This example points to a second issue: using variable names that
that are too short and not descriptive of the variable meaning, and so may
easily be the same name as something unrelated.

\index{lifetime!vs. scope}\index{scope!vs. lifetime}

\subsubsection{Lifetime and Scope Exercise/Example}
\label{a-first-class:lifetime-and-scope-exercise-example}\label{a-first-class:index-11}
Be careful to distinguish lifetime and scope.  Either a local variable or
an instance variable can be temporarily out of scope, but still be alive.
Can you construct an example to illustrate that?  One of ours is
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/lifetime\_scope/lifetime\_scope.cs}{lifetime\_scope/lifetime\_scope.cs}.


\section{Class Instance Examples}
\label{classexamples::doc}\label{classexamples:class-instance-examples}
\index{exercise!getters and setters}

\subsection{More Getters and Setters}
\label{classexamples:more-getters-and-setters}\label{classexamples:index-0}
As an exercise you could write a simple class Example, with
\begin{enumerate}
\item {} 
\code{int} instance variable \code{n} and \code{double} instance variable \code{d}

\item {} 
a simple constructor with parameters to set instance variables
\code{n} and \code{d}

\item {} 
getters and setters for both instance variables (4 methods in all)

\item {} 
a ToString that prints a line with both instance variables labeled.

\end{enumerate}

Compare yours to
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/example\_class/example\_class.cs}{example\_class/example\_class.cs}.

We include a testing class at the end of this file.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{class} \PYG{n+nc}{ExampleTest}
\PYG{p}{\PYGZob{}}
   \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{n}{Example} \PYG{n}{e} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Example}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2.5}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// use constructor}
      \PYG{c+c1}{// this creates the first Example object with reference e}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}e.n = \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{e}\PYG{p}{.}\PYG{n}{GetN}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints 1}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}e.d = \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{e}\PYG{p}{.}\PYG{n}{GetD}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints 2.5}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{e}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints Example: n = 1, d = 2.5}
      
      \PYG{n}{e}\PYG{p}{.}\PYG{n}{SetN}\PYG{p}{(}\PYG{l+m}{2}\PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{e}\PYG{p}{.}\PYG{n}{SetD}\PYG{p}{(}\PYG{l+m}{3.14159}\PYG{p}{)}\PYG{p}{;}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}e.n = \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{e}\PYG{p}{.}\PYG{n}{GetN}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints 25}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}e.d = \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{e}\PYG{p}{.}\PYG{n}{GetD}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints 3.14159}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{e}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints Example: n = 25, d = 3.14159}
      
      \PYG{n}{Example} \PYG{n}{e2} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Example}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0.5}\PYG{p}{)}\PYG{p}{;} 
      \PYG{c+c1}{// this creates the second Example object with reference e2}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{e2}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints Example: n = 3, d = 10.5}
      
      \PYG{n}{e} \PYG{p}{=} \PYG{n}{e2}\PYG{p}{;} \PYG{c+c1}{// now both e and e2 reference the second object}
      \PYG{c+c1}{// the first Example object is now no longer referenced}
      \PYG{c+c1}{// and its memory can be reclaimed at runtime if necessary}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{e}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints Example: n = 3, d = 10.5}

      \PYG{n}{e2}\PYG{p}{.}\PYG{n}{SetN}\PYG{p}{(}\PYG{l+m}{7}\PYG{l+m}{7}\PYG{p}{)}\PYG{p}{;}  \PYG{c+c1}{// symbolism uses e2, not e}
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{e2}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints Example: n = 77, d = 10.5 }
      \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{e}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints Example: n = 77, d = 10.5 }
      \PYG{c+c1}{// but e is the same object \PYGZhy{} so its fields are changed }
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}} \PYG{c+c1}{// end of class ExampleTest}
\end{Verbatim}

Besides the obvious tests, we also use
the fact that an Example object is mutable to play with  {\hyperref[onedim:alias]{\emph{References and Aliases}}}:
In the
last few lines of \code{Main}, after \code{e} becomes an alias for \code{e2},
we change
an object under one name, and it affect the alias the same way.
Check this by running the program!

Make sure you can follow the code and the output from running.

\index{Averager Example}\phantomsection\label{classexamples:beyond-getters-and-setters}\paragraph{Beyond Getters and Setters}

Thus far we have had very simple classes with instance variables and
getter and setter methods, and maybe a ToString method.
These classes were designed to introduce the basic syntax for
classes with instances.  The classes have just been containers for data
that we can read back, and change if there are setter methods - pretty
boring and limited.  Many objects have more extensive behaviors, so we will
take a small step and imagine a somewhat more complicated  \code{Averager} class:
\begin{itemize}
\item {} 
A new \code{Averager} starts with no data acknowledged.

\item {} 
Be able to enter data values one at a time (method \code{AddDatum}).
We will use \code{double} values.

\item {} 
At any point be able to return the average of the numbers entered so far
(method \code{GetAverage}).
The average is the sum of all the values divided by number of values.
With \code{double} values we assume a \code{double} average.
This does not make sense if there
are no values so far, but with double type we can use the value
\code{NaN} (Not a Number) in this case.

\item {} 
Be able to return the number of data elements entered so far
(method \code{GetDataCount})

\item {} 
Be able to clear the \code{Averager}, going back to no data elements
considered yet, like in a new \code{Averager} (method \code{Clear})

\item {} 
It is good to have a \code{ToString} method.  We choose to have
it label the number of data items and the average of the items.

\end{itemize}

The object starts from a fixed
state (no data) so we do not need any constructor parameters.

We can imagine a demonstration class \code{AveragerDemo} with a \code{Main} method
containing

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
         \PYG{n}{Averager} \PYG{n}{a} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Averager}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}New Averager: \PYGZdq{}} \PYG{p}{+} \PYG{n}{a}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{double} \PYG{n}{x} \PYG{k}{in} \PYG{k}{new}\PYG{p}{[}\PYG{p}{]} \PYG{p}{\PYGZob{}}\PYG{l+m}{5.1}\PYG{p}{,} \PYG{p}{\PYGZhy{}}\PYG{l+m}{7.3}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{1.0}\PYG{p}{,} \PYG{l+m}{3.7}\PYG{p}{\PYGZcb{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Next datum \PYGZdq{}} \PYG{p}{+} \PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{a}\PYG{p}{.}\PYG{n}{AddDatum} \PYG{p}{(}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}average \PYGZob{}0\PYGZcb{} with \PYGZob{}1\PYGZcb{} data values\PYGZdq{}}\PYG{p}{,} 
               \PYG{n}{a}\PYG{p}{.}\PYG{n}{GetAverage}\PYG{p}{(}\PYG{p}{)}\PYG{p}{,} \PYG{n}{a}\PYG{p}{.}\PYG{n}{GetDataCount}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{a}\PYG{p}{.}\PYG{n}{Clear}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}After clearing:\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}average \PYGZob{}0\PYGZcb{} with \PYGZob{}1\PYGZcb{} data values\PYGZdq{}}\PYG{p}{,} 
            \PYG{n}{a}\PYG{p}{.}\PYG{n}{GetAverage}\PYG{p}{(}\PYG{p}{)}\PYG{p}{,} \PYG{n}{a}\PYG{p}{.}\PYG{n}{GetDataCount}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

It should print

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
New Averager: items: 0; average: NaN
Next datum 5.1
average 5.1 with 1 data values
Next datum \PYGZhy{}7.3
average \PYGZhy{}1.1 with 2 data values
Next datum 11
average 2.93333333333333 with 3 data values
Next datum 3.7
average 3.125 with 4 data values
After clearing:
average NaN with 0 data values
\end{Verbatim}

Now that we have a clear idea of the proposed outward behavior, we
can consider how to implement the \code{Averager} class.

We could store a list of all the data values entered in any instance,
requiring a large amount of memory for a long list. However, this
functionality was built into early calculators, with very limited memory.
How can we do it without remembering the whole list?
Consider a concrete example:

If I have entered numbers 2.1, 4.5 and 5.4, and want the average, it is
\begin{quote}

\((2.1+4.5+5.4)/3=12.0/3=4.0\)
\end{quote}

If I want to include a further number 5.0, the average becomes
\begin{quote}

\((2.1+4.5+5.4+5.0)/4=17.0/4=4.25\)
\end{quote}

Note the relationship to the previous average expression:
\begin{quote}

\(=((2.1+4.5+5.4)+5.0)/4=(12.0+5.0)/(3+1)\)
\end{quote}

In the numerator we have added the latest value to the previous sum,
and in the denominator the count of data items is increased by one.
All we need to remember to
go on to include the next item is the sum of values so far and the
number of values so far.  We can just have instance variables
\code{sum} and \code{dataCount}.

You might think how to create this class....

The full \code{Averager} code follows:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{c+c1}{/// a class that is more than a container}
   \PYG{k}{class} \PYG{n+nc}{Averager}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{private} \PYG{k+kt}{int} \PYG{n}{dataCount}\PYG{p}{;}
      \PYG{k}{private} \PYG{k+kt}{double} \PYG{n}{sum}\PYG{p}{;}

      \PYG{c+c1}{/// new Averager with no data}
      \PYG{k}{public} \PYG{n+nf}{Averager}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Clear}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{AddDatum}\PYG{p}{(}\PYG{k+kt}{double} \PYG{k}{value}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{sum} \PYG{p}{+}\PYG{p}{=} \PYG{k}{value}\PYG{p}{;}
         \PYG{n}{dataCount}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k+kt}{int} \PYG{n+nf}{GetDataCount}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{dataCount}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// Gets the average of the data}
      \PYG{c+c1}{///   or NaN if no data.}
      \PYG{k}{public} \PYG{k+kt}{double} \PYG{n+nf}{GetAverage}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{sum}\PYG{p}{/}\PYG{n}{dataCount}\PYG{p}{;}  \PYG{c+c1}{// is NaN if dataCount is 0}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{Clear}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{sum} \PYG{p}{=} \PYG{l+m}{0.0}\PYG{p}{;}
         \PYG{n}{dataCount} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k}{override} \PYG{k+kt}{string} \PYG{n+nf}{ToString} \PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k+kt}{string}\PYG{p}{.}\PYG{n}{Format}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}items: \PYGZob{}0\PYGZcb{}; average: \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} 
            \PYG{n}{GetDataCount}\PYG{p}{(}\PYG{p}{)}\PYG{p}{,} \PYG{n}{GetAverage}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}} 
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Several things to note:
\begin{itemize}
\item {} 
We show that a constructor, like an instance method, can include a call
to a further instance method.  Though we illustrate this idea, the
constructor code is
actually unneeded.  See the {\hyperref[classexamples:unneeded-constructor-code-exercise]{\emph{Unneeded Constructor Code Exercise}}} below.

\item {} 
We have methods that are not ToString or mere getters or setters of instance
variables.  The logic of the class requires more.

\item {} 
The \code{GetAverage}
method does return data obtained by reading instance variable, but it does
a calculation using the instance variables first.  See
{\hyperref[classexamples:alternate-internal-state-exercise]{\emph{Alternate Internal State Exercise}}}.

\end{itemize}

The code for both classes is in project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/averager}{averager}.


\subsubsection{Statistics Exercise}
\label{classexamples:statistics-exercise}
Modify the project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/averager}{averager} so the \code{Averager} class is
converted to \code{Statistics}.  Besides having methods to calculate the count
of data items and average, also calculate the standard deviation with
a method \code{StandardDeviation}.
It turns out that the only other instance variable needed is
the sum of the squares of the data items, call it \code{sumOfSqr}.
Before calculating the standard deviation, suppose we
assign the current average to  a local variable \code{avg}.
Then the handiest form of expression for the standard deviation is

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Math}\PYG{p}{.}\PYG{n}{Sqrt}\PYG{p}{(}\PYG{p}{(}\PYG{n}{sumOfSqr} \PYG{p}{\PYGZhy{}} \PYG{n}{avg}\PYG{p}{*}\PYG{n}{avg}\PYG{p}{)}\PYG{p}{/}\PYG{n}{dataCount}\PYG{p}{)}
\end{Verbatim}

Modify the demonstration program to show the standard deviation, too.


\subsubsection{Unneeded Constructor Code Exercise}
\label{classexamples:unneeded-constructor-code-exercise}\label{classexamples:id1}
Recall that objects are always initialized. Each instance variable
has a default value assigned before a constructor is even run.
The default value for numeric instance variables is 0, so the
call to \code{Clear} in the constructor could be left out, leaving the
body of the constructor empty!  Try commenting that line out
and test that the behavior of demo program is the same.

Emphasizing the fact that you are thinking about the
initial values of instance variables is not a bad idea.  Hence
a common practice is to
explicitly assign even the default values in the constructor, as
we did initially with the call to \code{Clear} inside the constructor.

If no constructor definition is explicitly provided at all,
the compiler implicitly creates one with no parameters and an empty body.
This means that the entire constructor in \code{Averager} could be omitted.
Comment the whole constructor out and check.

There is a defensive programming
reason to provide even the do-nothing constructor explicitly:
If you use the implicit constructor and then decide to add a constructor
with parameters, the implicit constructor is no longer defined by the compiler,
so any remaining call to it in your code becomes an error.


\subsubsection{Alternate Internal State Exercise}
\label{classexamples:id2}\label{classexamples:alternate-internal-state-exercise}
The way we represent the internal state for an \code{Averager} is the
best probably, but if it turns out that the \code{GetAverage} method
is called a lot more often than a method that changes the state,
we could avoid repeated division by saving the average as an
instance variable.  We could keep that \emph{instead of} \code{sum}
(and still keep \code{dataCount}).  We can manage to
keep the same public interface to the methods.  With these
alternate instance variables how would you change
the implementation code and not change the method headings or meanings?
If we keep the assumption that the average of 0
items is
\code{double.Nan}, you will need to treat adding the first datum as
a special case.  The code is simpler if we change the outward assumptions
enough to consider the average of 0 items
to be 0.  Try it either way.

In the version with NaN you can avoid testing for NaN,
but if you choose to test for
NaN, you need the boolean \code{Double.IsNaN} function, because the expression
\code{double.NaN == double.NaN} is \emph{false}!

\index{class!convert static game to instance}

\subsection{Converting A Static Game To A Game Instance}
\label{classexamples:index-2}\label{classexamples:converting-a-static-game-to-a-game-instance}
For a comparison of procedural and object-oriented coding,
consider converting {\hyperref[lab-number-game:lab-number-game]{\emph{Number Guessing Game Lab}}} so that a GuessGame
is an object, an instance of the GuessGame class.

While our earlier example, Contact, is a simple but practical
use of object-oriented programming, GuessGame is somewhat more artificial.
We create it hoping that highlighting the differences between procedural
and object-oriented presentation is informative.  Also, we will see
with {\hyperref[interfaces:interface]{\emph{Interfaces}}} that
there are C\# language features that require an
object rather than just a function and data.
In {\hyperref[csproj-revisited:igame-interface-exercise]{\emph{IGame Interface Exercise}}} you can use a Game object.

Here is a procedural game version, example file
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/static\_version/static\_version.cs}{static\_version/static\_version.cs}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
   \PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{Game}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{private} \PYG{k}{static} \PYG{n}{Random} \PYG{n}{r} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Random}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}

      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{big} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Enter a secret number bound: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Play}\PYG{p}{(}\PYG{n}{big}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Play}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{big}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{int} \PYG{n}{secret} \PYG{p}{=} \PYG{n}{r}\PYG{p}{.}\PYG{n}{Next}\PYG{p}{(}\PYG{n}{big}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{guesses} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Guess a number less than \PYGZob{}0\PYGZcb{}.\PYGZdq{}}\PYG{p}{,} \PYG{n}{big}\PYG{p}{)}\PYG{p}{;}
         \PYG{k+kt}{int} \PYG{n}{guess} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Next guess: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{while} \PYG{p}{(}\PYG{n}{secret} \PYG{p}{!}\PYG{p}{=} \PYG{n}{guess}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{guess} \PYG{p}{\PYGZlt{}} \PYG{n}{secret}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Too small!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}} \PYG{k}{else} \PYG{p}{\PYGZob{}}
               \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Too big!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}

            \PYG{p}{\PYGZcb{}}
            \PYG{n}{guess} \PYG{p}{=} \PYG{n}{UI}\PYG{p}{.}\PYG{n}{PromptInt}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Next guess: \PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{guesses}\PYG{p}{+}\PYG{p}{+}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}You won on guess \PYGZob{}0\PYGZcb{}!\PYGZdq{}}\PYG{p}{,} \PYG{n}{guesses}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\end{Verbatim}

The project also refers to the library class UI,
with the functions we use for safe
keyboard input.  It is all static methods.

Is there any reason to make this UI class have its own own instances?

\textbf{No}.  There is no state to remember between UI method calls.
What comes in through
the keyboard goes out through a return value,
and then you are completely done with it.
A simple static function works fine each time.
\emph{Do not get fancy for nothing}.

What state would a game hold?  We might set it up so the user
chooses the size of the range of choices just once, and remember it
for possibly multiple plays of the GuessGame.  The variable was
\code{big} before, we can keep the name.
If we are going to remember it inside our GuessGame instance,
then \code{big} needs to become an instance variable, and it will be something
we can set in a constructor.

What actions/methods will this object have?  Only one - playing a GuessGame.
The GuessGame could be played multiple times, and that action, play,
makes sense as a method, Play, which will look a lot like the current
static function.

In the procedural version there are several other important variables:
\begin{itemize}
\item {} 
Random rand:  That was static before, for good reason:
We only need one Random number generator for the whole
time the program is running, so one static variable makes sense.

\item {} 
The central number in the procedural Game
and our future Play method is \code{secret}.
Should that be an instance variable?  It would work, but it would
be unhelpful and misleading:  Secret is reset every time the game is played,
and it has no meaning after a Play function would be finished.
There is nothing to
remember \emph{between} time you Play.  This is the
perfect place for a local variable \emph{as we have now}.

\end{itemize}

A common newbie error is to make things
into instance variables, just because you can, when an old-fashioned
local variable is all that you need.  It is good to have variables leave the
programmer's consciousness when they are no longer needed,
as a local variable does.
An instance variable lingers on, leaving extra places to make errors.

This introductory discussion could get you going, making a transformation.
Go ahead and make the changes as far as you can:
create project GuessGame inside the current solution.
Have a class GuessGame for the GuessGame instance,
with instance variable \code{big} and method \code{Play}.

You still need a static \code{Main} method to first create the GuessGame object.
You could prompt the user for the value for \code{big} to send to the constructor.
Once you have an object, you can call \emph{instance method} \code{Play}.
What about parameters? What needs to change from the procedural version?

There is also a video for this section that
follows all the way through the steps.
A possible final result is in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/instance\_version/guess\_game.cs}{instance\_version/guess\_game.cs}.


\subsection{Animal Class Lab}
\label{classexamples:animal-lab}\label{classexamples:animal-class-lab}
\textbf{Objectives}:
Complete a simple (silly) class, with constructor and methods,
including a \code{ToString} method, and a separate testing class.

Make an animal\_lab project in your solution,
and copy in the files from the example
project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/animal\_lab\_stub}{animal\_lab\_stub}.
Then modify the two files as discussed below.
\begin{enumerate}
\item {} 
Complete the simple class Animal in your copy of the file
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/animal\_lab\_stub/animal.cs}{animal.cs}.
The bullets below
name and describe the instance variables, constructor,
and methods you need to write:
\begin{itemize}
\item {} 
An Animal has a \code{name} and a \code{gut}.
In our version the \code{gut} is a List of strings
describing the contents, in the order eaten.
A newly created Animal gets a \code{name} from a parameter
passed to the constructor, while the \code{gut} always starts off \emph{empty}.

\item {} 
An Animal has a \code{Greet} method, so an animal named ``Froggy'' would say
(that is, print)
\begin{quote}

Hello, my name is Froggy.
\end{quote}

\item {} 
An Animal can \code{Eat} a string naming the food,
adding the food to the \code{gut}.
If Froggy eats ``worm'' and then ``fly'', its \code{gut} list contains
``worm'' and ``fly''.

\item {} 
An Animal can \code{Excrete}
(removing and printing what was \emph{first} in the gut List).
Recall the method \code{RemoveAt} in {\hyperref[listsyntax:listsyntax]{\emph{List Syntax}}}.  Print the
empty string, ``'', if the \code{gut}
\emph{was already empty}.  Following the
Froggy example above, Froggy could \code{Excrete},
and ``worm'' would be printed.
Then its \code{gut} would contain only ``fly''.

\item {} 
A \code{ToString} method:
Remember the \code{override} keyword.  Make it return a string in the format
shown below for Froggy, including the Animal's name:
\begin{quote}

``Animal: Froggy''
\end{quote}

Try this first, and note the extra credit version below.

\item {} 
All the methods that print should be void.
Which need a parameter, of what type?

\end{itemize}

\item {} 
Complete the file \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/animal\_lab\_stub/test\_animal.cs}{test\_animal.cs}
with its class \code{TestAnimal} containing the
\code{Main} method, testing the class Animal:
Create a couple of Animals and visibly test all the methods,
with enough explanation that someone running the test program,
but \emph{not} looking at the code of either file, can see that everything works.

\item {} 
20\% EXTRA CREDIT:  Elaborate \code{ToString} so if Froggy had ``worm'', ``fly''
and ``bug'' in the gut, the string would be:
\begin{quote}

``Animal: Froggy ate worm, fly and bug''
\end{quote}

with a comma separated list of the gut contents, except use proper English,
so the last separator
is '' and '', not '', ''.
If the gut has nothing in it, list the contents as ``nothing'':
\begin{quote}

``Animal: Froggy ate nothing''
\end{quote}

\end{enumerate}

\index{class!user class as instance}\index{example!clock}

\subsection{Clock Example}
\label{classexamples:clock-example}\label{classexamples:index-3}\label{classexamples:clock}
Consider the logic for a digital 24 hour clock object,
type \code{Clock}, that shows hours and minutes,
so 03:45 would be three forty-five.
Note that there is no AM or PM:  The hours go from 00, starting at midnight,
through hour 23, the 11PM hour, so 23:59 would be a minute before midnight,
and 13:00 would be 1PM.

Assume there is some attached circuit to signal when a new minute starts.

This class could have just a few methods:  \code{Tick},
called when a new minute is signaled,
and \code{GetTimeString} to return the time in the format illustrated above,
and \code{SetTime} specifying new values for the hours and minutes.
We can start
from a constructor that just sets the clock's time to midnight.

We can imagine a demonstration class \code{ClockDemo} with a \code{Main} method
containing

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
         \PYG{n}{Clock} \PYG{n}{c} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Clock}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Midnight \PYGZdq{}} \PYG{p}{+} \PYG{n}{c}\PYG{p}{.}\PYG{n}{GetTimeString}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{c}\PYG{p}{.}\PYG{n}{SetTime}\PYG{p}{(}\PYG{l+m}{2}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{5}\PYG{l+m}{8}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Before midnight \PYGZdq{}} \PYG{p}{+} \PYG{n}{c}\PYG{p}{.}\PYG{n}{GetTimeString}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{l+m}{4}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{c}\PYG{p}{.}\PYG{n}{Tick} \PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine} \PYG{p}{(}\PYG{l+s}{\PYGZdq{}Tick \PYGZdq{}} \PYG{p}{+} \PYG{n}{c}\PYG{p}{.}\PYG{n}{GetTimeString}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
\end{Verbatim}

It should print

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Midnight 00:00
Before midnight 23:58
Tick 23:59
Tick 00:00
Tick 00:01
Tick 00:02
\end{Verbatim}

A \code{Clock} object will need instance variables.
One obvious approach would be to have \code{int}
instance variables for the hours and minutes. Both can be set and can advance
and will need ot be read.

These actions are common to both the hours and minutes,
so we might think how we can avoid writing some things twice.
There is one main difference:  The minutes roll over at 60
while the hours roll over at 24.  Though the limits are different,
they are both numbers, so we can store the limit for each, 60 or 24.
Then the same code could be used to advance each one, just using a different value
for the rollover limit.

How would we neatly code this in a way that reuses code?  The most significant
thing to notice is that dealing with minutes involves data (the current count
and the limit 60) and associated actions:  being set, advanced and read.
The same is true for the hours.
The combination of \emph{data and tightly associated actions}, particularly used
in more than one situation,
suggests a new class of objects, say \code{RolloverCounter}.

Notice the shift in this approach:  The instance variables for hours and minutes
would become instances of the \code{RolloverCounter} class.  A \code{RolloverCounter}
should know how to advance itself.  Hence the logic for advancing a counter,
sometimes rolling it over, would not be directly in the \code{Clock} class,
but in the \code{RolloverCounter} class.

So let's think more about what we would want in the \code{RolloverCounter} class.
What instance variables?  Of course we have the current count,
and since we want the same class to work for both minutes and hours, we
also need to have the rollover limit. They are both integers.

The limit should just be set once for a particular counter,
presumably when the object is created.  For simplicity
we can just assume the count is 0 when a \code{RolloverCounter}
is first created.  Of course we must have a method to let the count
advance, rolling over back to 0 when the limit it reached.

Throw in a getter and a setter for the count and we can have the following
class:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{c+c1}{/// class used twice in Clock}
   \PYG{k}{class} \PYG{n+nc}{RolloverCounter} 
   \PYG{p}{\PYGZob{}}
      \PYG{k}{private} \PYG{k+kt}{int} \PYG{n}{limit}\PYG{p}{,} \PYG{n}{count}\PYG{p}{;}

      \PYG{k}{public} \PYG{n+nf}{RolloverCounter}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{limit}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{this}\PYG{p}{.}\PYG{n}{limit} \PYG{p}{=} \PYG{n}{limit}\PYG{p}{;}
         \PYG{n}{count} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;}  \PYG{c+c1}{//for clarity \PYGZhy{} this is the default value}
      \PYG{p}{\PYGZcb{}}
                               
      \PYG{k}{public} \PYG{k+kt}{int} \PYG{n+nf}{GetCount}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{count}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{SetCount}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{count}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{this}\PYG{p}{.}\PYG{n}{count} \PYG{p}{=} \PYG{n}{count}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
                               
      \PYG{c+c1}{/// advance by one time tick }
      \PYG{c+c1}{/// eventually roll over at limit                        }
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{Advance}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{n}{count} \PYG{p}{=} \PYG{p}{(}\PYG{n}{count} \PYG{p}{+} \PYG{l+m}{1}\PYG{p}{)} \PYG{p}{\PYGZpc{}} \PYG{n}{limit}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}                           
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Note how concise the \code{Advance} method is!  With the remainder operation,
we do not need an \code{if} statement.
Check examples by hand if this seems strange.

\index{format!0-pad}\index{zero pad format}\index{overloading!constructors}
Finally we introduce the \code{Clock} class itself.
We display the entire code first, and follow it with comments about a number
of new features.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{c+c1}{/// class with instance variables of another user class}
   \PYG{k}{class} \PYG{n+nc}{Clock} 
   \PYG{p}{\PYGZob{}}
      \PYG{k}{private} \PYG{n}{RolloverCounter} \PYG{n}{hours}\PYG{p}{,} \PYG{n}{minutes}\PYG{p}{;}

      \PYG{c+c1}{/// new Clock set to midnight}
      \PYG{k}{public} \PYG{n+nf}{Clock}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{n}{hours} \PYG{p}{=} \PYG{k}{new} \PYG{n}{RolloverCounter}\PYG{p}{(}\PYG{l+m}{2}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{minutes} \PYG{p}{=} \PYG{k}{new} \PYG{n}{RolloverCounter}\PYG{p}{(}\PYG{l+m}{6}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{///  new Clock set to specified time}
      \PYG{k}{public} \PYG{n+nf}{Clock}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{nHours}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{nMinutes}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{n}{hours} \PYG{p}{=} \PYG{k}{new} \PYG{n}{RolloverCounter}\PYG{p}{(}\PYG{l+m}{2}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{minutes} \PYG{p}{=} \PYG{k}{new} \PYG{n}{RolloverCounter}\PYG{p}{(}\PYG{l+m}{6}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{SetTime} \PYG{p}{(}\PYG{n}{nHours}\PYG{p}{,} \PYG{n}{nMinutes}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{SetTime}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{nHours}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{nMinutes}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{hours}\PYG{p}{.}\PYG{n}{SetCount}\PYG{p}{(}\PYG{n}{nHours}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{minutes}\PYG{p}{.}\PYG{n}{SetCount}\PYG{p}{(}\PYG{n}{nMinutes}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
         
      \PYG{c+c1}{/// advance by one time tick                         }
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{Tick}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{n}{minutes}\PYG{p}{.}\PYG{n}{Advance}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{minutes}\PYG{p}{.}\PYG{n}{GetCount}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{hours}\PYG{p}{.}\PYG{n}{Advance}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// Always 2 digits for both hours and minute with colon in middle}
      \PYG{k}{public} \PYG{k+kt}{string} \PYG{n+nf}{GetTimeString}\PYG{p}{(}\PYG{p}{)} 
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k+kt}{string}\PYG{p}{.}\PYG{n}{Format}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0:D2\PYGZcb{}:\PYGZob{}1:D2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{hours}\PYG{p}{.}\PYG{n}{GetCount}\PYG{p}{(}\PYG{p}{)}\PYG{p}{,} \PYG{n}{minutes}\PYG{p}{.}\PYG{n}{GetCount}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}  \PYG{c+c1}{// D2 format: always at least 2 digits, padding as needed with leading 0\PYGZsq{}s}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}
\begin{enumerate}
\item {} 
First the principal reason for this example:  We illustrate
writing a class where the instance variables are objects of a different
user-defined type.  Because the instance variables \code{hours} and
\code{minutes} are objects, we must initialize them
using the \code{new} syntax.

\item {} 
Skip over the \emph{second} constructor for now, and see the \code{SetTime} method:
We call the appropriate method to update the individual
\code{RolloverCounter} instances.

\item {} 
Now go back to the second constructor.  This is not really necessary:
With the first constructor the calling code could just have one more
\code{SetTime} line any time you want to
to create a clock with a time other than midnight.
We can make a case for
this being so common, that we want to do it in just one line,
with a constructor that sets a specified time.
However, the main excuse was really to illustrate that
constructors can be \emph{overloaded}, like methods:  You can have separate
constructors with distinct signatures.
In this case versions with no parameters vs. two \code{int} parameters.

\item {} 
The \code{Tick} method has a bit of logic to it:  while the minutes always
advance, the hours only advance when the minutes roll over to 0.

\item {} 
Finally the \code{GetTimeString} method illustrates a new integer string
formatting mode:  The D2 format specifier applies to an integer, and displays it
as a minimum of 2 digits, padding on the left with 0's as necessary.
This is just what we want here.  In general the 2 could be replaced by another
literal integer, so D6 would force at least 6 digits:  With the D6 format
specifier 12 would be formatted as 000012,
and the longer 1234567 would add no extra 0's: still 1234567.

\end{enumerate}

The code for all the classes is in project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/clock}{clock}.

Admittedly, with this exact functionality and such a concise line to
advance a count, it would actually have shorter to have done everything
inside the \code{Clock} class, with no \code{RolloverCounter}, but we were looking
for a simple illustration of combining user-defined types this way,
and a \code{RolloverCounter} is a clear unified
concept that can be used in other situations.  See an upcoming exercise.


\subsubsection{Alternate Clock Constructor Exercise}
\label{classexamples:alternate-clock-constructor-exercise}
Make a small change to \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/clock/clock\_demo.cs}{clock/clock\_demo.cs}, so the second
constructor is tested.


\subsubsection{Clock With Seconds Exercise}
\label{classexamples:clock-with-seconds-exercise}
Modify the project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/clock}{clock}, assuming the Tick is for each second, and
the time also show the seconds, like 55 seconds before midnight would be
23:59:05.

\index{model-view-controller pattern}

\subsubsection{Twelve Hour Time Exercise}
\label{classexamples:index-5}\label{classexamples:twelve-hour-time-exercise}
Modify the project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/clock}{clock} so a \code{GetTimeString12} method returns
the 12 hour time with AM or PM, like 11:05PM or 3:45AM. (The hours do
not have a leading 0 in this format.)
This could be done modifying a lot of things:
keeping the actual hours and minutes that you will display
and remembering AM or PM (with the hours
being more complicated, not starting at 0).  We suggest something else instead:

This is a good place to note a very useful pattern for programming, called
\emph{model-view-controller}.  The \emph{model} is the way chosen to store the state internally.
The \emph{controller} has the logic to modify the model as it needs to evolve.
A \emph{view} of a part of
the model is something shown to the user that
does not need to be in the exact same form as the model itself:
A view just needs to be something that can be \emph{easily calculated}
from the model, and presumably is desired by the user.

In this case a simple (and already coded!) way to store and control
the time model data
is the minutes and up to 23 hours that do happen to directly correspond
to the 24 hour clock view.

The main control is to advance the time,
and with just two 0-based counts we have the
very simple remainder formulas.

So the suggestion is to keep the \emph{internal} data the same way as before.
Just in the method to create the desire 12-hour view have the logic to do the
\emph{conversion} of the internal 24-hour model data.

You could leave in the method to provide the time in the
24 hour format, giving the \code{Clock} class user the option to use either view
of the shared model data.
To be symmetrical in the naming,
you might change the original name \code{GetTimeString} to
\code{GetTimeString24}.

\index{class!Rational}\index{Rational class}

\section{The Rational Class}
\label{rational:the-rational-class}\label{rational:index-0}\label{rational::doc}\label{rational:rational}
Like other numbers, we think of a rational number as a unit,
but all rational numbers can be most easily represented as a fraction,
a ratio of two integers. We can create a class Rational, so

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Rational} \PYG{n}{r} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

would create a new Rational number for the mathematical expression, 2/3.

Our previous simple class examples have mostly been ways of
collecting related data, with limited methods beyond getters and setters.
Rational numbers also have lots of obvious operations defined on them.
Our Rational example we will use most of the concepts for object so far,
and add a few more, to provide a rich practical class
with a variety of methods.

Thinking ahead to what we would like for our rational numbers, here is
some testing code.  Hopefully the method names are clear and reasonable.
in the illustration
we operate on a single rational number, and do calculation with a pair,
and parse string literals.  The code is from
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/test\_rational/test\_rational.cs}{test\_rational/test\_rational.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}

\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{TestRational}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Rational} \PYG{n}{f} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{6}\PYG{p}{,} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}6/(\PYGZhy{}10) simplifies to \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{f}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}reciprocal of \PYGZob{}0\PYGZcb{} is \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{f}\PYG{p}{,} \PYG{n}{f}\PYG{p}{.}\PYG{n}{Reciprocal}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} negated is \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{f}\PYG{p}{,} \PYG{n}{f}\PYG{p}{.}\PYG{n}{Negate}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Rational} \PYG{n}{h} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} + \PYGZob{}1\PYGZcb{} is \PYGZob{}2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{f}\PYG{p}{,} \PYG{n}{h}\PYG{p}{,} \PYG{n}{f}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{n}{h}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} \PYGZhy{} \PYGZob{}1\PYGZcb{} is \PYGZob{}2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{f}\PYG{p}{,} \PYG{n}{h}\PYG{p}{,} \PYG{n}{f}\PYG{p}{.}\PYG{n}{Subtract}\PYG{p}{(}\PYG{n}{h}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} * \PYGZob{}1\PYGZcb{} is \PYGZob{}2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{f}\PYG{p}{,} \PYG{n}{h}\PYG{p}{,} \PYG{n}{f}\PYG{p}{.}\PYG{n}{Multiply}\PYG{p}{(}\PYG{n}{h}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}(\PYGZob{}0\PYGZcb{}) / (\PYGZob{}1\PYGZcb{}) is \PYGZob{}2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{f}\PYG{p}{,} \PYG{n}{h}\PYG{p}{,} \PYG{n}{f}\PYG{p}{.}\PYG{n}{Divide}\PYG{p}{(}\PYG{n}{h}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} \PYGZgt{} \PYGZob{}1\PYGZcb{} ? \PYGZob{}2\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{h}\PYG{p}{,} \PYG{n}{f}\PYG{p}{,} \PYG{p}{(}\PYG{n}{h}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{n}{f}\PYG{p}{)} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} as a double is \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{f}\PYG{p}{,} \PYG{n}{f}\PYG{p}{.}\PYG{n}{ToDouble}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{} as a decimal is \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{h}\PYG{p}{,} \PYG{n}{h}\PYG{p}{.}\PYG{n}{ToDecimal}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{foreach} \PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s} \PYG{k}{in} \PYG{k}{new}\PYG{p}{[}\PYG{p}{]} \PYG{p}{\PYGZob{}}\PYG{l+s}{\PYGZdq{}\PYGZhy{}12/30\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}123\PYGZdq{}}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}1.125\PYGZdq{}}\PYG{p}{\PYGZcb{}}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Parse \PYGZbs{}\PYGZdq{}\PYGZob{}0\PYGZcb{}\PYGZbs{}\PYGZdq{} to Rational: \PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,}
                                        \PYG{n}{s}\PYG{p}{,} \PYG{n}{Rational}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{s}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

One non-obvious method is \code{CompareTo}.  This one method allows
all the usual comparison operators to be used with the result.
We will discuss it more in {\hyperref[fractions-revisited:rationals-revisited]{\emph{Rationals Revisited}}}.

The results we would like when running this testing code:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
6/(\PYGZhy{}10) simplifies to \PYGZhy{}3/5
reciprocal of \PYGZhy{}3/5 is \PYGZhy{}5/3
\PYGZhy{}3/5 negated is 3/5
\PYGZhy{}3/5 + 1/2 is \PYGZhy{}1/10
\PYGZhy{}3/5 \PYGZhy{} 1/2 is \PYGZhy{}11/10
\PYGZhy{}3/5 * 1/2 is \PYGZhy{}3/10
(\PYGZhy{}3/5) / (1/2) is \PYGZhy{}6/5
1/2 \PYGZgt{} \PYGZhy{}3/5 ? true
\PYGZhy{}3/5 as a double is \PYGZhy{}0.6
1/2 as a decimal is 0.5
Parse \PYGZdq{}\PYGZhy{}12/30\PYGZdq{} to Rational: \PYGZhy{}2/5
Parse \PYGZdq{}123\PYGZdq{} to Rational: 123
Parse \PYGZdq{}1.125\PYGZdq{} to Rational: 9/8
\end{Verbatim}

A Rational has a numerator and a denominator.  We must remember that data.
Each individual Rational that we use will have its own numerator and
denominator, which we store as the instance variables
(and which we abbreviate since we are lazy):

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{Rational}
\PYG{p}{\PYGZob{}}
   \PYG{k}{private} \PYG{k+kt}{int} \PYG{n}{num}\PYG{p}{;}
   \PYG{k}{private} \PYG{k+kt}{int} \PYG{n}{denom}\PYG{p}{;}
   \PYG{c+c1}{// ...}
\end{Verbatim}

We could have a very simple constructor that just copies in values for
the numerator and denominator.  However, there is an extra wrinkle with
rational numbers:  They can be represented many ways.  You remember from
grade school being told to ``reduce to lowest terms''.  This will keep
our internal representations unique, and use the smallest numbers.

Intermediate operations and initial constructor parameters
will not always be in lowest terms.  To reduce to lowest terms
we need to divide the original numerator and denominator by their
{\hyperref[gcdexamples:gcd]{\emph{Greatest Common Divisor}}}.    We include a \emph{static} GCD method taken from that section,
and make the adjustment to lowest terms in a helping method, \code{Normalize},
that is called by the constructor:

\index{private!helping method}
\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Force the invarient: in lowest terms with a positive denominator.}
      \PYG{k}{private} \PYG{k}{void} \PYG{n+nf}{Normalize}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}                           
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{denom} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}} \PYG{c+c1}{// We *should* force an Exception, but we won\PYGZsq{}t.}
            \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Zero denominator changed to 1!\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
            \PYG{n}{denom} \PYG{p}{=} \PYG{l+m}{1}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k+kt}{int} \PYG{n}{n} \PYG{p}{=} \PYG{n}{GCD}\PYG{p}{(}\PYG{n}{num}\PYG{p}{,} \PYG{n}{denom}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{num} \PYG{p}{/}\PYG{p}{=} \PYG{n}{n}\PYG{p}{;}         \PYG{c+c1}{// lowest}
         \PYG{n}{denom} \PYG{p}{/}\PYG{p}{=} \PYG{n}{n}\PYG{p}{;}       \PYG{c+c1}{//    terms}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{denom} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)} \PYG{p}{\PYGZob{}}  \PYG{c+c1}{// make denom positive}
            \PYG{n}{denom} \PYG{p}{=} \PYG{p}{\PYGZhy{}}\PYG{n}{denom}\PYG{p}{;}\PYG{c+c1}{//   double negation:}
            \PYG{n}{num} \PYG{p}{=} \PYG{p}{\PYGZhy{}}\PYG{n}{num}\PYG{p}{;}    \PYG{c+c1}{//   same mathematical value}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

There are several things to note about this method:
\begin{itemize}
\item {} 
It is \emph{private}.
It is only used as a helping method, called from inside of Rational.  It
is not a part of the public interface used from other classes.

\item {} 
We need to deal with a 0 denominator somehow.  We should be causing an
\emph{exception}, but that is an advanced topic, so we wimp out and just
change the denominator to 1.

\item {} 
There is one other technical issue in getting a unique representation:  The
denominator could start off being negative.
If that is the case, we change the sign of
both the numerator and denominator, so we always end up with a positive
denominator.  We will use this fact in several places.

\item {} 
It calls a static method of the class, \code{GCD}.  Classes can have both
instance and static methods.  It is fine for an instance method like
\code{Normalize} to call a static method:  The instance variables cannot be
accessed.  Here \code{GCD} is passed all its data explicitly through
its parameters.

\end{itemize}

The complete constructor, using \code{Normalize}, is below.
Note that by the time we
are done constructing a new Rational, it is in this normalized form:  lowest
terms and positive denominator:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Create a fraction given numerator and denominator. }
      \PYG{k}{public} \PYG{n+nf}{Rational}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{numerator}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{denominator}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{num} \PYG{p}{=} \PYG{n}{numerator}\PYG{p}{;}
         \PYG{n}{denom} \PYG{p}{=} \PYG{n}{denominator}\PYG{p}{;}
         \PYG{n}{Normalize}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

The call to the \code{Normalize} method is another place where we have a
call without dot notation, since it
is acting on the same object as for the constructor.

We mentioned that instance method \code{Normalize} calls static method \code{GCD},
and this is fine.  The reverse is not true:

\begin{notice}{warning}{Warning:}
Inside a \code{static} method there
is \emph{no} current object.  A common compiler error is caused when you
try to have a static method call
an instance method without dot notation for a specific object.
The shorthand notation
without an explicit object reference and dot cannot be used, because
there is no
current object to reference implicitly:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{AnInstanceMethod}\PYG{p}{(}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
      \PYG{p}{.}\PYG{p}{.}\PYG{p}{.}
\PYG{p}{\PYGZcb{}}

\PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{AStaticMethod}\PYG{p}{(}\PYG{p}{)}  \PYG{c+c1}{// no current object}
\PYG{p}{\PYGZob{}}
       \PYG{n}{AnInstanceMethod}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}  \PYG{c+c1}{// COMPILER ERROR CAUSED}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

On the other hand, there is no issue when
an instance method calls a static method.  (The instance variables are just
inaccessible inside the static method.)
\end{notice}

The Rational class has the usual getter methods, to access the
obvious parts of its state:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{k}{public} \PYG{k+kt}{int} \PYG{n+nf}{GetNumerator}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{num}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k+kt}{int} \PYG{n+nf}{GetDenominator}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{denom}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

We certainly want to be able to display a Rational as a string version:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a string of the fraction in lowest terms,}
      \PYG{c+c1}{/// omitting the denominator if it is 1.}
      \PYG{k}{public} \PYG{k}{override} \PYG{k+kt}{string} \PYG{n+nf}{ToString}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{denom} \PYG{p}{!}\PYG{p}{=} \PYG{l+m}{1}\PYG{p}{)}
            \PYG{k}{return} \PYG{k+kt}{string}\PYG{p}{.}\PYG{n}{Format}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZob{}0\PYGZcb{}/\PYGZob{}1\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{num}\PYG{p}{,} \PYG{n}{denom}\PYG{p}{)}\PYG{p}{;}
         \PYG{k}{return} \PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{+}\PYG{n}{num}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Note that we simplify so you would see ``3'' rather than ``3/1''.  This is also
a place where the normalization to have a positive denominator comes in:
a negative Rational will always have a leading ``-'' as in ``-5/9'' rather than
``5/-9''

With a Rational, several other conversions make sense:  to \code{double}
and \code{decimal} approximations.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a double approximation to the fraction. }
      \PYG{k}{public} \PYG{k+kt}{double} \PYG{n+nf}{ToDouble}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{p}{(}\PYG{p}{(}\PYG{k+kt}{double}\PYG{p}{)}\PYG{n}{num}\PYG{p}{)}\PYG{p}{/}\PYG{n}{denom}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
                                   
      \PYG{c+c1}{/// Return a decimal approximation to the fraction. }
      \PYG{k}{public} \PYG{k+kt}{decimal} \PYG{n+nf}{ToDecimal}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{p}{(}\PYG{p}{(}\PYG{k+kt}{decimal}\PYG{p}{)}\PYG{n}{num}\PYG{p}{)}\PYG{p}{/}\PYG{n}{denom}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

So far we have returned built-in types.  What if we wanted to generate
the reciprocal of a Rational?  That would be another Rational.  It is
legal to return the type of the class that you are defining!
How do we make a new Rational?
We have a constructor!  We can easily use it.  The reciprocal
swaps the numerator and denominator.  It is also easy to negate
a Rational:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a new Rational which is the reciprocal of this Rational.}
      \PYG{k}{public} \PYG{n}{Rational} \PYG{n+nf}{Reciprocal}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k}{new} \PYG{n+nf}{Rational}\PYG{p}{(}\PYG{n}{denom}\PYG{p}{,} \PYG{n}{num}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// Return a new Rational which is this Rational negated.}
      \PYG{k}{public} \PYG{n}{Rational} \PYG{n+nf}{Negate}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k}{new} \PYG{n+nf}{Rational}\PYG{p}{(}\PYG{p}{\PYGZhy{}}\PYG{n}{num}\PYG{p}{,} \PYG{n}{denom}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Static methods are still useful.
For example, in analogy with the other numeric types
we may want a static \code{Parse} method
to act on a string parameter and return a new Rational.

The most obvious kind of string to parse would be one like \code{"2/3"} or \code{"-10/77"},
which we can split at the \code{'/'}.
Integers are also rational numbers, so we would like to parse \code{"123"}.
Finally decimal strings can be converted to rational numbers,
so we would like to parse \code{"123.45"}.

See how our \code{Parse} method below distinguishes and handles
all the cases.  It constructs integer strings,
\code{parts{[}0{]}} and \code{parts{[}1{]}}, for both the numerator and denominator,
and then parses the integers.  Note that the method \emph{is} \code{static}.
There is no Rational
being referred to when it starts, but in this case the method \emph{returns} one.

That last case is the trickiest.  For example \code{"123.45"} becomes 12345/100
(before being reduced to lowest terms).
Note that there were originally \emph{two} digits after the decimal point
and then the denominator gets \emph{two} zeroes to have the right power of 10:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Parse a string of an integer, fraction (with /) or decimal (with .)}
      \PYG{c+c1}{///  and return the corresponding Rational. }
      \PYG{k}{public} \PYG{k}{static} \PYG{n}{Rational} \PYG{n+nf}{Parse}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{s}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{s} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Trim}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}      \PYG{c+c1}{// will adjust numerator and denominator parts}
         \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{parts} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{n}{s}\PYG{p}{,} \PYG{l+s}{\PYGZdq{}1\PYGZdq{}}\PYG{p}{\PYGZcb{}}\PYG{p}{;} \PYG{c+c1}{// for an int string, this is correct}
         \PYG{k}{if} \PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Contains}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}/\PYGZdq{}}\PYG{p}{)}\PYG{p}{)} \PYG{p}{\PYGZob{}}     \PYG{c+c1}{// otherwise correct num, denom parts}
            \PYG{n}{parts} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Split}\PYG{p}{(}\PYG{l+s+sc}{\PYGZsq{}/\PYGZsq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}} \PYG{k}{else} \PYG{k}{if} \PYG{p}{(}\PYG{n}{s}\PYG{p}{.}\PYG{n}{Contains}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}.\PYGZdq{}}\PYG{p}{)}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{intFrac} \PYG{p}{=} \PYG{n}{s}\PYG{p}{.}\PYG{n}{Split}\PYG{p}{(}\PYG{l+s+sc}{\PYGZsq{}.\PYGZsq{}}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// integer, fractional digits}
            \PYG{n}{parts}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]} \PYG{p}{=} \PYG{n}{intFrac}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{+}\PYG{n}{intFrac}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]}\PYG{p}{;}  \PYG{c+c1}{// \PYGZdq{}shift\PYGZdq{} decimal point}
            \PYG{n}{parts}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}1\PYGZdq{}}\PYG{p}{;}                 \PYG{c+c1}{// denom will have as many 0\PYGZsq{}s }
            \PYG{k}{foreach}\PYG{p}{(} \PYG{k+kt}{char} \PYG{n}{dig} \PYG{k}{in} \PYG{n}{intFrac}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]}\PYG{p}{)} \PYG{p}{\PYGZob{}}  \PYG{c+c1}{//    as digits after \PYGZsq{}.\PYGZsq{}}
               \PYG{n}{parts}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]} \PYG{p}{+}\PYG{p}{=} \PYG{l+s}{\PYGZdq{}0\PYGZdq{}}\PYG{p}{;}                 \PYG{c+c1}{//    to compensate }
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}} 
         \PYG{k}{return} \PYG{k}{new} \PYG{n+nf}{Rational}\PYG{p}{(}\PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{parts}\PYG{p}{[}\PYG{l+m}{0}\PYG{p}{]}\PYG{p}{.}\PYG{n}{Trim}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{,}
                             \PYG{k+kt}{int}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{n}{parts}\PYG{p}{[}\PYG{l+m}{1}\PYG{p}{]}\PYG{p}{.}\PYG{n}{Trim}\PYG{p}{(}\PYG{p}{)}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}


\subsection{Method Parameters of the Same Type}
\label{rational:method-parameters-of-the-same-type}
We can deal with the current object without using dot notation.  What if we are
dealing with \emph{more than one} Rational, the current one \emph{and} another one,
like the parameter in Multiply:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a new Rational which is the product of this Rational and f. }
      \PYG{k}{public} \PYG{n}{Rational} \PYG{n+nf}{Multiply}\PYG{p}{(}\PYG{n}{Rational} \PYG{n}{f}\PYG{p}{)}
\end{Verbatim}

We can mix the shorthand notation for the current object's fields
and dot notation for another
\emph{named} object:  \code{num} and \code{denom} refer to the fields in the \emph{current} object, and
\code{f.num} and \code{f.denom} refer to fields for the other
\code{Rational}, the parameter \code{f}.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a new Rational which is the product of this Rational and f. }
      \PYG{k}{public} \PYG{n}{Rational} \PYG{n+nf}{Multiply}\PYG{p}{(}\PYG{n}{Rational} \PYG{n}{f}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}                           \PYG{c+c1}{// end Multiply heading chunk}
         \PYG{k}{return} \PYG{k}{new} \PYG{n+nf}{Rational}\PYG{p}{(}\PYG{n}{num}\PYG{p}{*}\PYG{n}{f}\PYG{p}{.}\PYG{n}{num}\PYG{p}{,} \PYG{n}{denom}\PYG{p}{*}\PYG{n}{f}\PYG{p}{.}\PYG{n}{denom}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

We do not refer to the fields of \code{f} through the public methods
\code{GetNumerator} and \code{GetDenominator}.
Though \code{f} is not the same \emph{object}, it is the same \emph{type}:

\begin{notice}{note}{Note:}
Private members of \emph{another} object of the \emph{same} type are
accessible from method definitions in the class.
\end{notice}

There are a number of other arithmetic methods in the source code for Rational
that return a new Rational result of the arithmetic operation.  They \emph{do} review
your knowledge of arithmetic! They do \emph{not} add further C\# syntax.

The whole code for Rational is in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/rational\_nunit/rational.cs}{rational\_nunit/rational.cs}.
The testing code we started with, in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/test\_rational/test\_rational.cs}{test\_rational/test\_rational.cs}
uses all the methods.  We will see more advance ways to test Rational
in {\hyperref[testing:testing]{\emph{Testing}}}.

There is also a more convenient version of Rational,
using advanced concepts, in {\hyperref[overload-op:defining-operators]{\emph{Defining Operators (Optional)}}}.


\subsection{Pictorial Playing Computer}
\label{rational:pictorial-playing-computer}
Let us start pictorially playing computer on \code{test\_rational.cs},
as a review of much of the previous sections.  We explicitly show a local variable
\code{this} to identify the current object in an instance method or constructor.

The first line of \code{Main},

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Rational} \PYG{n}{f} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{6}\PYG{p}{,} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

creates a new Rational, so it calls the constructor.  At the very beginning of the
constructor, a prototype \code{Rational} is already created as the current object,
so immediately, there is a \code{this}.
The parameters 6, and -10 are passed, initializing the explicit local
variables \code{numerator} and \code{denominator}.
The figure illustrates the memory state at the beginning of the constructor call:

\includegraphics[width=207pt]{callConstructor.png}

Note the immediate value assigned to the numeric instance variables is zero:  This is
as discussed in {\hyperref[onedim:default-fields]{\emph{Default Initializations}}}.
Of course we do not want to keep those default values:
The constructor finds the value of the local variable \code{numerator}, and needs to
assign the value 6 to a variable \code{num}.  The compiler has looked
first for a local variable \code{num}, and found none.
Then it looked \emph{second} for an instance variable in the object pointed to
by \code{this}.  It found \code{num} there.  Now it copies the 6 into that location.
Similarly for \code{denominator} and \code{denom}:

\includegraphics[width=207pt]{callConstructorCopied.png}

Then the constructor calls \code{Normalize}.
Since \code{Normalize} is also an instance method,
a reference to \code{this} is passed implicitly.
While illustrating the memory state for more than one active method,
we separate each one with a horizontal segment.

\includegraphics{callNormalize.png}

Later \code{Normalize} calls \code{GCD}.  Since \code{GCD} is static, note that the local
variables for \code{GCD} do \emph{not} contain a reference to \code{this}.

\includegraphics[width=207pt]{callGCD.png}

At the end of \code{GCD} the \code{int} 2 is returned and initializes
\code{n} in the calling method \code{Normalize}.
Then \code{Normalize} modifies the instance variable pointed to by \code{this},
and finishes.

\includegraphics[width=207pt]{finishNormalize.png}

That is the same object \code{this} in the constructor.
Just before the constructor completes we have:

\includegraphics[width=207pt]{finishConstructor.png}

Then in \code{Main} the constructor's \code{this} is the reference to the new object
initializing \code{f}.

\includegraphics[width=198pt]{setF.png}

Consider the next line of \code{Main}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}6/(\PYGZhy{}10) simplifies to \PYGZob{}0\PYGZcb{}\PYGZdq{}}\PYG{p}{,} \PYG{n}{f}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

We omit the internals of the WriteLine call, except to note that it must convert
the reference \code{f} to a string.  As with any object,
it does this by calling the \code{ToString} method for \code{f},
so the implicit \code{this} in the call to \code{ToString} refers to the same object as \code{f}:

\includegraphics[width=196.5pt]{callToString.png}

\code{ToString} returns ``-3/5'', and it gets printed as part of the line generated
by \code{WriteLine}....

We skip the similar details through two more \code{WriteLine} statements and the
initialization of \code{h}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Rational} \PYG{n}{h} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,}\PYG{l+m}{2}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

The \code{WriteLine}
statement after that needs to evaluate \code{f.Add(h)}, generating a call to \code{Add}.
The next figure shows the two local variables in \code{Main}, \code{f} and \code{h}, each
pointing to a \code{Rational} object.  The image shows the situation
in the call to \code{Add}, just before the end of the return statement,
when the new Rational is being constructed.

In the local variables for the method \code{Add}
see what the implicit \code{this} refers to, and what the
(local to \code{Add}) variable \code{f} refer to.  As the figure shows,
this use of a local variable
\code{f} is independent of the \code{f} in \code{Main}:

\includegraphics[width=220.5pt]{callAdd.png}

Since the return statement in \code{Add} creates a new object,
the figure shows  a call to the
constructor from inside \code{Add}.  We do not go through the details of another
constructor call, but
\code{this} in the constructor points to the Rational shown and returned by
\code{Add}:

\includegraphics[width=220.5pt]{endAdd.png}

which gets sent to the \code{WriteLine} statement
and gets printed in \code{Main} as in the earlier code.

Make sure you see how the pictures reinforce these important ideas:
\begin{itemize}
\item {} 
Keeping track of the \code{this} with
constructors and instance methods (but not static methods).

\item {} 
The aliasing of \code{Rational} objects used as parameters explicitly or
implicitly (\code{this}).

\end{itemize}

We have played computer before in procedural programming,
following individually explicitly named
variables.  This has allowed us to follow loops clearly after the code is
written.  The pictorial version with multiple object references and method calls
is also useful for checking on code that is written with many object
references.

When first \emph{writing} code with object references that you are manipulating,
a picture of the setup
showing the references in your data is also helpful.
New object-oriented programmers often have a hard time referring to the
data they want to work with.
If you have a picture of the data relationships
you can point with a finger to a part that you want to use.
For example
in the call to \code{Add}, one piece of data you need for your arithmetic is
the \code{num} field in \code{f}.  Then you must be carful to note
that \emph{only local variables can be referenced directly}
(including the implicit \code{this}).   If you want to refer to data that is not a local
variable, you must follow the reference path arrow that leads \emph{from a local variable} to
an instance field that you want to reference.

\includegraphics[width=220.5pt]{pathToNum.png}

Then use the proper object-oriented notation to refer to the path.
In the example, it takes one step,
from local variable \code{f} to its field \code{num}, referred to as \code{f.num}.
Similarly the current object's \code{num} is connected through \code{this}, but C\# shorthand
allows \code{this.} to be omitted.  And so on, for \code{f.denom} and \code{denom}.

Visually following such paths will be even more important later, when we construct
more complex types of objects, and you need to follow
a path through \emph{several} references in sequence.

\index{exercise!ForceMatch}

\subsection{ForceMatch Exercise}
\label{rational:forcematch-exercise}\label{rational:index-2}
Suppose we have a class:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{class} \PYG{n+nc}{Pair}
\PYG{p}{\PYGZob{}}
   \PYG{k}{private} \PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{,}\PYG{n}{y}\PYG{p}{;}

   \PYG{k}{public} \PYG{n+nf}{Pair}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{y}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
       \PYG{k}{this}\PYG{p}{.}\PYG{n}{x} \PYG{p}{=} \PYG{n}{x}\PYG{p}{;} \PYG{k}{this}\PYG{p}{.}\PYG{n}{y} \PYG{p}{=} \PYG{n}{y}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}

   \PYG{c+c1}{///Mutate the parameter so its instance variables match this object}
   \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{ForceMatch}\PYG{p}{(}\PYG{n}{Pair} \PYG{n}{p}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{c+c1}{// need code ...}
   \PYG{p}{\PYGZcb{}}

   \PYG{k}{public} \PYG{k}{override} \PYG{k+kt}{string} \PYG{n+nf}{ToString}\PYG{p}{(}\PYG{p}{)}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{return} \PYG{k+kt}{string}\PYG{p}{.}\PYG{n}{Format}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}(\PYGZob{}0\PYGZcb{}, \PYGZob{}1\PYGZcb{})\PYGZdq{}}\PYG{p}{,} \PYG{n}{x}\PYG{p}{,} \PYG{n}{y}\PYG{p}{)}\PYG{p}{;}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

A test would be code in another class:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Pair} \PYG{n}{first} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Pair}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{7}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Pair} \PYG{n}{second} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Pair}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{9}\PYG{p}{)}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{second}\PYG{p}{)}\PYG{p}{;}  \PYG{c+c1}{// prints (1, 9)}
\PYG{n}{first}\PYG{p}{.}\PYG{n}{ForceMatch}\PYG{p}{(}\PYG{n}{second}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{second}\PYG{p}{)}\PYG{p}{;}  \PYG{c+c1}{// prints (3, 7)}
\end{Verbatim}
\begin{enumerate}
\item {} 
Would this code work?  If not, explain why not:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{ForceMatch}\PYG{p}{(}\PYG{n}{Pair} \PYG{n}{p}\PYG{p}{)}
\PYG{p}{\PYGZob{}}
   \PYG{n}{p} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Pair}\PYG{p}{(}\PYG{n}{x}\PYG{p}{,} \PYG{n}{y}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

If you do not see it,
do a graphical play-computer like in the last section.

\item {} 
Complete the body of \code{ForceMatch} correctly.

\end{enumerate}

\index{class!plan classes and methods}\index{plan problem split into classes}

\section{Planning A Class Structure}
\label{planning_classes:planning-a-class-structure}\label{planning_classes:plan-classes}\label{planning_classes:index-0}\label{planning_classes::doc}
The Console input/output interchange below illustrates
an idea for a skeleton of a text (adventure?) game.
It could be the basis of a later group project. It does not
have much in it yet, but it can be planned in terms of classes.
Classes with instances correspond to nouns you would be using,
particularly nouns used in more than one place with different
state data being remembered.
Verbs associated with nouns you use tend to be methods.
Think how you might break this down, looking at what is happening
in the sequence below.

The parts appearing after the `\textgreater{}' prompt are entries by the user.
Other lines are computer responses:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Welcome to Loyola!
This is a pretty boring game, unless you modify it.
Type \PYGZsq{}help\PYGZsq{} if you need help.

You are outside the main entrance of the university that prepares people for
extraordinary lives.  It would help to be prepared now....
Exits: east south west
\PYGZgt{} help
You are lost. You are alone.
You wander around at the university.

Your command words are:
   help go quit

Enter
        help command
for help on the command.
\PYGZgt{} help go
Enter
        go direction
to exit the current place in the specified direction.
The direction should be in the list of exits for the current place.
\PYGZgt{} go west
You are in the campus pub.
Exits: east
\PYGZgt{} go east
You are outside the main entrance of the university that prepares people for
extraordinary lives.  It would help to be prepared now....
Exits: east south west
\PYGZgt{} go south
You are in a computing lab.
Exits: north east
\PYGZgt{} go east
You are in the computing admin office.
Exits: west
\PYGZgt{} bye
I don\PYGZsq{}t know what you mean...
\PYGZgt{} quit
Do you really want to quit? yes
Thank you for playing.  Good bye.
\end{Verbatim}

Think and discuss how to organize things first....

The different parts of a multi-class project interact through their public methods.
Remember the two roles of writer and consumer.  The consumer needs good documentation
of how to use (not implement) these methods.  These methods that allow the
interaction between classes provide the \emph{interface} between classes.  Unfortunately
``interface'' is used in more than one way.  Here it means publicly specified ways
for different parts to interact.

As you think how to break this game into parts (classes),
also think how the parts interact (public methods).
This is a good place for the start of a class discussion.

If the plan is to discuss it in class, \emph{wait} before looking at
the code that generated the exchange above, in the
project folder \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/cs\_project1}{cs\_project1}.

The code uses many of the topics discussed so far in this book.

We will add some features from another meaning of {\hyperref[interfaces:interface]{\emph{Interfaces}}},
and discuss the revision in project
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/csproject\_stub}{csproject\_stub} (no 1).  You \emph{might} use this version
as a basis of a project.

\index{value type}\index{reference object}\index{struct}

\section{Classes And Structs}
\label{classes-and-structs:index-0}\label{classes-and-structs:classes-and-structs}\label{classes-and-structs::doc}\label{classes-and-structs:structs-and-classes}
C\# has an alternate syntax to a class: a \emph{struct}.
Everything we have said so far about classes such an \code{Rational} applies to
structs also!  In fact you could change \code{class} into \code{struct} in the heading for
Rational, and it would become a \code{struct}, with no further code changes in any of the
code we have written!

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{struct} \PYG{n+nc}{Rational}
\PYG{p}{\PYGZob{}}
   \PYG{c+c1}{// ...}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

So why the distinction?  We have mentioned that new objects created in a class are
accessed indirectly via a reference, as with an array.  As a general category,
they are called \emph{reference objects}.  We distinguished the types \code{int} and
\code{double} and \code{bool}, where the actual value of the data is stored in the space
for a variable of the type.  They are \emph{value types}.  A struct is also a value
type.  In practice this is efficient for small objects of a fixed size.
We made Rational a class because
you have already seen the class construct with
\code{static} entries, and classes are more generally useful.
In fact being a \code{struct} would be a good choice for Rational,
since it only contains two integers.  Its size is no more than one \code{double}.

The behavior of a Rational is the same either way, because it is immutable.  If we
allowed mutating methods, then a class version and a struct version would not behave
the same way, due to the fact the reference types can have aliases,
and value types cannot.

There are some more complicated situations where there are further distinctions between
classes and structs, but we shall not concern ourselves
with those fine advanced points in this book.


\section{Defining Operators (Optional)}
\label{overload-op:defining-operators}\label{overload-op::doc}\label{overload-op:defining-operators-optional}
\index{operator!overload in user class}\index{overloading!operators}

\subsection{Operator Overloading}
\label{overload-op:operator-overloading}\label{overload-op:index-0}\label{overload-op:overloading-operators}
The Rational class is a fine example of a useful utility class.
Still, to an experienced user, it has a striking deficiency:
A Rational is a \emph{number} and we are used to doing arithmetic with
standard operators.  We would like to replace the mouthful
\code{frac1.Multiply(frac2)} by our common symbolism for multiplication,
\code{frac1*frac2}.  This can be coded in C\#, using \emph{operator overloading} to
give new meanings to the operator \code{*}.  The C\# syntax is illustrated in the
variant of the Rational class in
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/rational\_ops\_stub/rational.cs}{rational\_ops\_stub/rational.cs}.  This class also contains code
discussed in the
next section, {\hyperref[overload-op:casts-in-user-classes]{\emph{Casts in User-Defined Classes}}}.
Here are operator overload declarations for \code{*} and others:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// * binary multiplication operator }
      \PYG{k}{public} \PYG{k}{static} \PYG{n}{Rational} \PYG{k}{operator} \PYG{p}{*}\PYG{p}{(}\PYG{n}{Rational} \PYG{n}{f1}\PYG{p}{,} \PYG{n}{Rational} \PYG{n}{f2}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}                          
         \PYG{k}{return} \PYG{k}{new} \PYG{n+nf}{Rational}\PYG{p}{(}\PYG{n}{f1}\PYG{p}{.}\PYG{n}{num}\PYG{p}{*}\PYG{n}{f2}\PYG{p}{.}\PYG{n}{num}\PYG{p}{,} \PYG{n}{f1}\PYG{p}{.}\PYG{n}{denom}\PYG{p}{*}\PYG{n}{f2}\PYG{p}{.}\PYG{n}{denom}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// \PYGZhy{} unary negation operator}
      \PYG{k}{public} \PYG{k}{static} \PYG{n}{Rational} \PYG{k}{operator} \PYG{p}{\PYGZhy{}} \PYG{p}{(}\PYG{n}{Rational} \PYG{n}{r}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k}{new} \PYG{n+nf}{Rational}\PYG{p}{(}\PYG{p}{\PYGZhy{}}\PYG{n}{r}\PYG{p}{.}\PYG{n}{num}\PYG{p}{,} \PYG{n}{r}\PYG{p}{.}\PYG{n}{denom}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// binary == operator}
      \PYG{k}{public} \PYG{k}{static} \PYG{n}{Boolean} \PYG{k}{operator} \PYG{p}{=}\PYG{p}{=}\PYG{p}{(}\PYG{n}{Rational} \PYG{n}{f1}\PYG{p}{,} \PYG{n}{Rational} \PYG{n}{f2}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{f1}\PYG{p}{.}\PYG{n}{num} \PYG{p}{=}\PYG{p}{=} \PYG{n}{f2}\PYG{p}{.}\PYG{n}{num} \PYG{p}{\PYGZam{}}\PYG{p}{\PYGZam{}} \PYG{n}{f1}\PYG{p}{.}\PYG{n}{denom} \PYG{p}{=}\PYG{p}{=} \PYG{n}{f2}\PYG{p}{.}\PYG{n}{denom}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{c+c1}{/// binary != operator}
      \PYG{k}{public} \PYG{k}{static} \PYG{n}{Boolean} \PYG{k}{operator} \PYG{p}{!}\PYG{p}{=}\PYG{p}{(}\PYG{n}{Rational} \PYG{n}{f1}\PYG{p}{,} \PYG{n}{Rational} \PYG{n}{f2}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{f1}\PYG{p}{.}\PYG{n}{num} \PYG{p}{!}\PYG{p}{=} \PYG{n}{f2}\PYG{p}{.}\PYG{n}{num} \PYG{p}{\textbar{}}\PYG{p}{\textbar{}} \PYG{n}{f1}\PYG{p}{.}\PYG{n}{denom} \PYG{p}{!}\PYG{p}{=} \PYG{n}{f2}\PYG{p}{.}\PYG{n}{denom}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}} \PYG{c+c1}{// or extra call, but clearly consistent: return !(f1 == f2)}
\end{Verbatim}

All operator overload headings have the special form
\begin{quote}

\code{public static} \emph{returnType} \code{operator} opSymbol \code{(} \emph{parameters} \code{)}
\end{quote}

Here opSymbol can be any arithmetic or comparison operator, or
some other operators that we have not discussed.  So something like
\code{operator *} or \code{operator -} replaces the method name.
Binary operations like multiplication require two operands, and hence the
method has two parameters.
The method
computes and returns the named return type in the normal fashion.
In general
at least one of the parameters must be of the type of the class being defined.

(We could have directly defined four further overloads of \code{*},
with the first or second parameter
being an \code{int} or a \code{double}, but we will avoid that by also adding methods
to provide implicit {\hyperref[overload-op:casts-in-user-classes]{\emph{Casts in User-Defined Classes}}}.)

The \code{-} symbol is special, since it can be used either as a unary operator for
negation, or as a binary operator for subtraction.  Since we include only
one parameter above, we are defining the unary version.

The operator does not need to produce a result of the same type.  We
included \code{==} and \code{!=} as examples (returning a \code{Boolean}).

(These methods
do not cause compiler errors, but warnings are generated:
We have not added further more advanced
overrides of Equals and HashCode methods, that are ideally in sync with
the meaning of \code{==}.  You should see a discussion of these methods in a
data structures course, like Loyola's Comp 271.)

The class is a stub,
and {\hyperref[overload-op:overloading-operator-exercise]{\emph{Operator Overloading Exercise}}}
invites you to add further operator overloads.

\index{precedence!with operator overloading}\index{operator!precedence with overloading}
\textbf{Precedence}:  Note that the operator overloading method definitions include
nothing about {\hyperref[precedence:precedence]{\emph{Precedence of Operators}}}. That is because the precedence of operators
is fixed across the whole language. Unary \code{-} has higher
precedence than \code{*} ... no matter what the types involved.

An example testing class also uses the new casting syntax of next section:

\index{operator!casts in user class}\index{casts in user-defined classes}\index{implicit casts in user-defined classes}

\subsection{Casts in User-Defined Classes}
\label{overload-op:casts-in-user-defined-classes}\label{overload-op:casts-in-user-classes}\label{overload-op:index-2}
We have discussed casts before.  We know that an \code{int} can also be represented
as a \code{double} with an integer value, and the cast from \code{int} to \code{double}
is done implicitly
when needed:  An expression like \code{3.2 * 2} is processed by the compiler,
\emph{implicitly} casting the
2 to \code{double} 2.0, and then doing a \code{double} multiplication.
The same idea makes sense with an
\code{int} \code{n} and a Rational \code{f}.  We only defined the operator overload \code{*}
for two Rationals, so in our code so far, \code{f * n} does not make sense.
Mathematically an integer is rational, so mathematically, it should make sense.
We bridge this difference by defining an implicit cast of an \code{int} to a Rational,
so  the compiler will take \code{f * n} and see the need to implicitly cast
\code{n} to a Rational.  The definition below will also allow explicit casts
if you choose, like \code{f * (Rational) n}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Code to cast an int to a Rational implicitly when needed. }
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{implicit} \PYG{k}{operator} \PYG{n+nf}{Rational}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{n}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{k}{new} \PYG{n+nf}{Rational}\PYG{p}{(}\PYG{n}{n}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Again it is
the heading that takes a special form, starting with
\code{public static implicit operator} followed by the type being cast to,
like Rational, while the parameter is the starting type, like \code{int}.
This is not like a regular method with its return type and method name.
Here it looks something like a constructor with a type in place of a method
name, but a constructor would not start with \code{static implicit operator}!

Now consider a \code{double} \code{d} and a Rational \code{f}.
We would like to allow an expression like
\code{d * f}.
Again, the operator overload for \code{*} does not allow this directly, so consider
implicit casts:  Since
a \code{double} is only an approximation, in general,
it would not be wise to implicitly convert
a \code{double} to a Rational, but it does make sense to approximate a Rational
by a \code{double} before use with a \code{double}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Code to cast to a double implicitly when needed. }
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{implicit} \PYG{k}{operator} \PYG{n+nf}{double}\PYG{p}{(}\PYG{n}{Rational} \PYG{n}{f}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{p}{(}\PYG{k+kt}{double}\PYG{p}{)}\PYG{n}{f}\PYG{p}{.}\PYG{n}{num}\PYG{p}{/}\PYG{n}{f}\PYG{p}{.}\PYG{n}{denom}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

The general format of such an implicit cast in a user-defined class is:
\begin{quote}

\code{public static implicit operator} \emph{resultType} \code{(} \emph{sourceType} \emph{paramName} \code{)}
\end{quote}

One of the two types should be the type of the containing class.
We have illustrated both combinations.

Finally, you need to be \emph{very careful where you declare implicit casts}, to
make sure you are not being overly general, and maybe allowing
trouble in a form that may be very hard to debug:
It is much harder to foresee and trace implicit actions than explicit actions.
You are
\emph{safe}, but more \emph{verbose}, if you \emph{only allow explicit} casts.  For example,
we have already seen these required for a cast from \code{double} to \code{int}.
To only allow an explicit cast with your type,
replace \code{implicit} by \code{explicit} in the cast method heading.

\index{decimal type}\index{type!decimal}\index{explicit casts in user-defined classes}\phantomsection\label{overload-op:decimal-type}
\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Code to cast to a decimal with an explicit cast. }
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{explicit} \PYG{k}{operator} \PYG{n+nf}{decimal}\PYG{p}{(}\PYG{n}{Rational} \PYG{n}{f}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{p}{(}\PYG{k+kt}{decimal}\PYG{p}{)}\PYG{n}{f}\PYG{p}{.}\PYG{n}{num}\PYG{p}{/}\PYG{n}{f}\PYG{p}{.}\PYG{n}{denom}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

\textbf{The decimal type}:  Though we have not used the
\code{decimal} type before, we use it here for contrast to illustrate a cast
from Rational to \code{decimal} that can only be used explicitly, as in
\code{(decimal) f}:

Example
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/rational\_ops\_stub/test\_ops.cs}{rational\_ops\_stub/test\_ops.cs} tests all of the operator overloads
and casts shown for a Rational.  Look at the source code and run it.
Note where overloaded operators are used and where implicit and explicit casts
to or from a Rational are used.

The example also illustrates a special feature
of the \code{decimal} type.  While a \code{double} is encoded with a power of 2, so
0.1 is \emph{not} stored accurately, a \code{decimal} is encoded with a power of 10, so
exact decimal values with up to 28 digits can be stored and manipulated.
(This is important for \emph{monetary calculations}, so a \code{decimal} literal
has \textbf{m} for money appended, like  \code{5.99m}, representing the mathematical
quantity 5.99 \emph{exactly}.)

\index{exercise!overloading operators}\index{overloading!exercise for operators}

\subsubsection{Operator Overloading Exercise}
\label{overload-op:index-4}\label{overload-op:operator-overloading-exercise}\label{overload-op:overloading-operator-exercise}
The classes discussed above from example project
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/rational\_ops\_stub}{rational\_ops\_stub}
are incomplete.  Add the
overloaded binary operators  /, +, -, \textless{}, \textgreater{}, \textless{}= and \textgreater{}= to the Rational class,
and extend the TestOps class to test them.


\section{Chapter Review Questions}
\label{reviewclasses:chapter-review-questions}\label{reviewclasses::doc}\begin{enumerate}
\item {} 
Where in a class are instance variables declared?

\item {} 
For most instance variables, what is the modifier used that does not
appear at the beginning of a local variable declaration?

\item {} 
What is the lifetime of an instance variable:
When does it come into existence, and how long does it last?

\item {} 
Why do we generally make an instance variable \code{private}?

\item {} 
In what code can an instance variable be seen and used?

\item {} 
Must instance variables and methods always be preceded by
an explicit object reference and \code{.}?

\item {} 
Can we refer to an instance variable in a part of the code
where there is no current object?

\item {} 
In what kind of method in a class definition are instance variables never
accessible?

\item {} 
What is the purpose of a constructor?

\item {} 
How is the heading of a constructor different from a regular method?

\item {} 
How are parameters to a constructor generally used?

\item {} 
If you do not explicitly assign a value to an instance variable in a
constructor, does the instance variable have a value?

\item {} 
If we want users to be able to see the value of a private instance variable
from outside of the class, how do we do it?

\item {} 
What is the general name of the category of methods that return
instance state values?

\item {} 
Instance variables are usually visible from inside instance methods for
the class.  What is the exception?  In the exceptional case, what is
the workaround to allow access to the instance variable?

\item {} 
Sometimes you need to refer explicitly to the current object.  How
do you do it?

\item {} 
Sometimes you want to let users outside the class modify the value
of a private instance variable.  How do you do it?

\item {} 
What is the general name of the category of public methods whose sole purpose
is to set a part of instance state to a new specified value?

\item {} 
If a class has one or more setter methods, is the object type
immutable?

\item {} 
What is the return type for a setter method?

\item {} 
If you want to set an instance variable in a method, should you declare
that instance variable in the method?

\item {} 
A method with what signature allows you to control how the string
concatenation operate (\code{+}) generates a string from the object?

\item {} 
If you write an override the \code{ToString} method in a class, should the method
print the string?   If not, what should it do with the resulting string?

\item {} 
What is \code{this}?

\item {} 
Can aliased objects cause problems when created for an immutable object?
Mutable object?

\item {} 
In a class with instance methods you can always design the class so variables
are instance variables and not local variables.  When should you
use local variables instead?

\item {} 
If an instance method has a formal parameter of the same type as the
class being defined,
can you refer to a private instance variable in the parameter object?
May you change it?
How do you distinguish an instance variable for the current object from the
corresponding instance variable for the parameter object?

\end{enumerate}

\index{testing}

\chapter{Testing}
\label{testing:index-0}\label{testing:testing}\label{testing::doc}\label{testing:id1}
Now that we have learned a bit about classes, we're going to use the same feature
to support \emph{unit testing}. Unit testing is a concept that will become part of just
about everything you do in future programming-focused courses, so we want to make sure
that you understand the idea and begin to make use of it in all of your work.

The notion of unit testing is straightforward in principle. When you write a program
in general, the program comprises what are properly known as units of development.
Each language has its own definition of what units are but most modern programming
languages view the \emph{class} concept as the core unit of testing. Once we have a class,
we can test it and all of the parts associated with it, especially its methods.

We will be introducing parts of file \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/rational\_nunit/rational\_unit\_tests.cs}{rational\_nunit/rational\_unit\_tests.cs}.

\index{testing!assertion}\index{assertion testing}

\section{Assertions}
\label{testing:index-1}\label{testing:assertions}
A key notion of testing is the ability to make a logical assertion about something
that generally must hold \emph{true} if the test is to pass.

Assertions are not a standard language feature in C\#. Instead, there are a number of
classes that provide functions for assertion handling. In the framework we are using for
unit testing (NUnit), a class named Assert supports assertion testing.

In our tests, we make use of an assertion method, \code{Assert.IsTrue()} to determine
whether an assertion is successful. If the variable or expression passed to this
method is \emph{false}, the assertion fails.

Here are some examples of assertions:
\begin{itemize}
\item {} 
\code{Assert.IsTrue(true)}: The assertion is trivially successful,
because the boolean value \code{true} is true.

\item {} 
\code{Assert.IsTrue(false)}: The assertion is not successful, because the boolean value
\code{false} is not true!

\item {} 
\code{Assert.IsFalse(false)}: This assertion is successful, because
\code{false} is, of course, false.

\item {} 
\code{Assert.IsTrue(5 \textgreater{} 0)}: Success

\item {} 
\code{Assert.IsTrue(0 \textgreater{} 5)}: Failure

\end{itemize}

There are many available assertion methods. In our tests, we use \code{Assert.IsTrue()},
which works for everything we want to test. Other assertion methods do their magic
rather similarly, because every assertion method ultimately must determine whether
what is being tested is true or false.

\index{attribute {[} {]}}\index{{[} {]}!attribute}

\section{Attributes}
\label{testing:attributes}\label{testing:index-2}
Besides assertions, a building block of testing (in C\# and beyond) comes in the form
of attributes. Attributes are an additional piece of information that can be attached
to classes, variables, and methods in C\#. There are two attributes of interest to us:
\begin{itemize}
\item {} 
{[}TestFixture{]}: This indicates that a class is being used for testing purposes.

\item {} 
{[}Test{]}: This indicates that a method is one of the methods in a class being used
for testing purposes.

\end{itemize}

Without these annotations, classes and methods will \emph{not} be used for testing purposes.
This allows a class to have some methods that are used for testing while other methods
are ignored.

In the remainder of this section, we're going to take a look at the strategy for testing
the Rational class. In general, your goal is to ensure that the entire class is tested.
It is easier said than done. In later courses (Software Engineering) you would learn about
strategies for \emph{coverage} testing.

Our strategy will be as follows:
\begin{itemize}
\item {} 
Test the constructor and make sure the \emph{representation} of the rational number is
sound. If the constructor isn't initializing an instance properly, it is likely
that little else in the class will work properly.

\item {} 
Then test the rest of the class. Whenever possible, group the tests in some logical
way. In the case of the Rational class, there are three general categories (and one
rather special one): arithmetic operations, comparisons, and conversions. In addition,
there is the parsing test, which ensures that we can convert strings representing
fractions into properly initialized (and reduced) rational numbers.

\end{itemize}

Let's get started.


\section{Testing the Constructor}
\label{testing:testing-the-constructor}
\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{n+na}{      [Test()]}
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{ConstructorTest}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Rational} \PYG{n}{r} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{GetNumerator}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{GetDenominator}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{r} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{,} \PYG{p}{\PYGZhy{}}\PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{GetNumerator}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{p}{\PYGZhy{}}\PYG{l+m}{3}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{GetDenominator}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{r} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{6}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{GetNumerator}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{GetDenominator}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{r} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{5}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{GetNumerator}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{5}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{GetDenominator}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Testing the constructor is fairly straightforward. We essentially test three basic
cases:
\begin{itemize}
\item {} 
Test whether a basic rational number can be constructed. In the above, we test for
3/5, 3/-5, 6/10, and 125. Per the implementation of the Rational class (how we defined
it), these should result in fractions with numerators of 3, -3, 3, and 12; and denominators
of 5, 5, 5, and 1, respectively.

\item {} 
As you can observe from the code, we perform basic assertion testing to ensure that
the numerators and denominators are what we expect. For example:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{GetNumerator}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{3}\PYG{p}{)}
\end{Verbatim}

Tests whether the newly minted rational number, Rational(3, 5), actually has the
expected numerator of 3.

\item {} 
If we are able to get through the entire code of the \code{ConstructorTest()} method,
our constructor test is a success. Otherwise, it is a failure.

\end{itemize}

We'll look at how to actually run our tests in a bit but let's continue taking a look
at how the rest of our testing is done.


\section{Testing Rational Comparisons}
\label{testing:testing-rational-comparisons}
\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{n+na}{      [Test()]}
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{BasicComparisonTests}\PYG{p}{(}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{Rational} \PYG{n}{r1} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{p}{\PYGZhy{}}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{6}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Rational} \PYG{n}{r2} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{4}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Rational} \PYG{n}{r3} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r1}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{)} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{n}{r1}\PYG{p}{)} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{n}{r3}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

It is pretty well established by now that the ability to compare is of fundamental importance
whenever we are talking about data. Everything we do, especially when it comes to searching
(finding a value) and sorting (putting values in order) depends on comparison.

In this test, we construct a few Rational instances (r1, r2, and r3) and perform at least
one test for each of the essential operators (\textgreater{}, \textless{}, and =). Recall from our earlier discussion
of the Rational class that the CompareTo method return a value \code{\textless{} 0}
when one Rational is \emph{less than} another. It returns a number
\code{\textgreater{} 0} for \emph{greater than}, and \code{== 0} for \emph{equal to}.

If any one of these comparisons fails, this means that we cannot rely on the ability to
compare Rational numbers. This will likely prevent other tests from working, such as the
arithmetic tests, which rely on the ability to test whether a \emph{computed result} matches
an \emph{expected result} (e.g. 1/4 + 2/4 == 3/4).


\section{Testing Rational Arithmetic}
\label{testing:testing-rational-arithmetic}
\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{n+na}{      [Test()]}
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{BasicArithmeticTests}\PYG{p}{(}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{Rational} \PYG{n}{r}\PYG{p}{,} \PYG{n}{r1}\PYG{p}{,} \PYG{n}{r2}\PYG{p}{;}
         \PYG{n}{r1} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{4}\PYG{l+m}{7}\PYG{p}{,} \PYG{l+m}{6}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{r2} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{6}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{;}

         \PYG{n}{r} \PYG{p}{=} \PYG{n}{r1}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{3}\PYG{l+m}{6}\PYG{p}{,} \PYG{l+m}{6}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}

         \PYG{n}{r} \PYG{p}{=} \PYG{n}{r1}\PYG{p}{.}\PYG{n}{Subtract}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{5}\PYG{l+m}{8}\PYG{p}{,} \PYG{l+m}{6}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}

         \PYG{n}{r} \PYG{p}{=} \PYG{n}{r1}\PYG{p}{.}\PYG{n}{Multiply}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{4}\PYG{l+m}{7} \PYG{p}{*} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{6}\PYG{l+m}{4} \PYG{p}{*} \PYG{l+m}{6}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}

         \PYG{n}{r} \PYG{p}{=} \PYG{n}{r1}\PYG{p}{.}\PYG{n}{Divide}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{4}\PYG{l+m}{7}\PYG{p}{,} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{l+m}{1}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}

         \PYG{n}{r} \PYG{p}{=} \PYG{n}{r1}\PYG{p}{.}\PYG{n}{Reciprocal}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{6}\PYG{l+m}{4}\PYG{p}{,} \PYG{l+m}{4}\PYG{l+m}{7}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}

         \PYG{n}{r} \PYG{p}{=} \PYG{n}{r1}\PYG{p}{.}\PYG{n}{Negate}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{p}{\PYGZhy{}}\PYG{l+m}{4}\PYG{l+m}{7}\PYG{p}{,} \PYG{l+m}{6}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

Testing of arithmetic is a fairly straightforward idea. For all of these tests, we
create a couple of rational numbers (47/64 and -11/64) and then call the various methods
to perform addition, subtraction, multiplication, division, reciprocal, and negation.

The key to testing arithmetic successfully in the case of a Rational number is to know
know what the result \emph{should be}. As a concrete example, the result of adding these
two rational numbers should be 36/64. So the testing strategy is to use the \code{Add()}
method to add the two rational numbers and then test whether the result of the addition
is equal to the \emph{known} answer of 36/64.

As you can observe by looking at the code, the magic occurs by checking whether the
\emph{computed} result matches the \emph{constructed} result:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{3}\PYG{l+m}{6}\PYG{p}{,} \PYG{l+m}{6}\PYG{l+m}{4}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

Because we have \emph{separately} tested the constructor and comparison methods, we can
assume that it is ok to rely upon comparison methods as part of this arithmetic test.

And it is in this example where we begin to see the \emph{art of testing}. You can write
tests that assume that other tests of features you are using have \emph{already passed}. In the
event that your assumption is wrong, you'd be able to know that this is the case, because
all of the tests you assumed to pass would not have passed.

Again, to be clear, the arithmetic tests we have done here \emph{assume} that we can rely on
the constructor and the comparison operation to determine equality of two rational numbers.
It is entirely possible that this is not true, so we'll be able to determine this when
examining the test output (we'd see that not only the arithmetic test fails but possibly the
constructor and/or comparison tests as well).

The remaining tests are fairly straightforward. We'll more or less present them as is with
minimal explanation as they are in many ways variations on the theme.


\section{Testing Rational Conversions (to other types)}
\label{testing:testing-rational-conversions-to-other-types}
\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{n+na}{      [Test()]}
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{ConversionTests}\PYG{p}{(}\PYG{p}{)} \PYG{p}{\PYGZob{}}
         \PYG{n}{Rational} \PYG{n}{r1} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{6}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Rational} \PYG{n}{r2} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{p}{\PYGZhy{}}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{6}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Rational} \PYG{n}{r3} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{,} \PYG{p}{\PYGZhy{}}\PYG{l+m}{2}\PYG{p}{)}\PYG{p}{;}

         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r1}\PYG{p}{.}\PYG{n}{ToDecimal}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0.5}\PYG{n}{m}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{.}\PYG{n}{ToDecimal}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{p}{\PYGZhy{}}\PYG{l+m}{0.5}\PYG{n}{m}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r1}\PYG{p}{.}\PYG{n}{ToDouble}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0.5}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{//.5 is stored exactly}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{.}\PYG{n}{ToDouble}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{p}{\PYGZhy{}}\PYG{l+m}{0.5}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{.}\PYG{n}{ToString}\PYG{p}{(}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZhy{}1/2\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZdq{}} \PYG{p}{+} \PYG{n}{r3} \PYG{p}{=}\PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZhy{}5\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}  \PYG{c+c1}{//implicit use of ToString}

      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

In this test, we want to make sure that Rational objects can be converted to floating point
and decimal types (the built-in types of the C\# language).

For example, Rational(3/6) is 1/2, which is 0.5 (both in its floating-point and decimal
representations.


\section{Testing the Parsing Feature}
\label{testing:testing-the-parsing-feature}
\begin{Verbatim}[frame=single,commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{n+na}{      [Test()]}
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{ParseTest}\PYG{p}{(}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{Rational} \PYG{n}{r}\PYG{p}{;}
         \PYG{n}{r} \PYG{p}{=} \PYG{n}{Rational}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}\PYGZhy{}12/30\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{r} \PYG{p}{=} \PYG{n}{Rational}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}123\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{2}\PYG{l+m}{3}\PYG{p}{,} \PYG{l+m}{1}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{r} \PYG{p}{=} \PYG{n}{Rational}\PYG{p}{.}\PYG{n}{Parse}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}1.125\PYGZdq{}}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{9}\PYG{p}{,} \PYG{l+m}{8}\PYG{p}{)}\PYG{p}{)} \PYG{p}{=}\PYG{p}{=} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Assert}\PYG{p}{.}\PYG{n}{IsTrue}\PYG{p}{(}\PYG{n}{r}\PYG{p}{.}\PYG{n}{ToString}\PYG{p}{(}\PYG{p}{)}\PYG{p}{.}\PYG{n}{Equals}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}9/8\PYGZdq{}}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

The parsing test tests whether we can convert the string representation of a rational number
into an actual (reduced) rational number. We test three general cases:
\begin{itemize}
\item {} 
The ability to take a fraction and convert it into a rational number. This fraction may
or may not have a ``-'' sign in it. For example -12/30 should be equivalent to constructing
a Rational(-12, 30).

\item {} 
The ability to take a whole number and get a proper Rational, e.g. 123 is equal to
Rational(123)

\item {} 
The ability to take a textual representation (1.125) and get a proper Rational(9, 8)
representation. In this case, we are also getting an extra test to ensure the result
is reduced.

\end{itemize}

\index{Xamarin Studio!running NUnit tests}\index{testing!running in Xamarin Studio}

\section{Running the NUnit Tests}
\label{testing:running-nunit-tests}\label{testing:running-the-nunit-tests}\label{testing:index-3}\begin{enumerate}
\item {} 
In Xamarin Studio, select the rational\_nunit project.

\item {} 
In the main Xamarin Studio menu click ``Run'' and select ``Run Unit Tests''

\end{enumerate}

A test pad should appear and show something like

\includegraphics[width=509.25pt]{NUnitTestXamarinInit.png}

This likely just shows the overall results in the summary line at the bottom.
You can show details by clicking on one or more of headings at the
top of the pad.  In particular, if you click Successful Test, Failed Tests,
and Output (and likely drag the top of the pad to make
it large enough to see everything), you should see something like

\includegraphics[width=490pt]{NUnitTestXamarinDetails.png}

As you can see in the above displays, all of the tests in \code{RationalTests}
get executed, and they all pass.
There are no failed tests to see,
but that part would be the most important details if any were there!
The output just details the sequence of execution.

Xamarin Studio remembers the headings selected, so next time you run tests,
the same details will show.

The testing file is using NUnit.Framework.  There is a little more to this.
If you edit the references, selecting All sources, and entering nunit
in the search box, you see

\includegraphics[width=489.75pt]{NUnitReferencesXamarin.png}

Note there are more than one version of nunit.framework. On a Mac,
the selected version worked directly, but the logical looking one, provided
by Xamarin, did \emph{not} work directly.  Either worked if we select the context
menu in the Solutions pad for the nunit.framework version added to the references,
and make it look like

\includegraphics[width=288pt]{NUnitNotSpecificVersion.png}

with the ``Require Specific Version'' item toggled so it is \emph{not} checked.

We waited until now to discuss unit testing, because the test classes are coded with
\emph{instance} methods,
unlike the static methods that we started out with.

A test can also call \code{Main} of a program, with specified parameters that
would normally come from the command line.  See the small project
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/cmdline\_to\_file}{cmdline\_to\_file}.

\index{String Replace NUnit Exercise}\index{exercise!String Replace NUnit}

\subsection{String Replace NUnit Test Exercise}
\label{testing:index-4}\label{testing:string-replace-nunit-test-exercise}
If you completed the program from the stub
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/string\_manip\_stub/string\_manip.cs}{string\_manip\_stub/string\_manip.cs},
then add a testing class using NUnit that tests \code{ReplaceFirst}
with the same parameters as used in the original file's \code{Main}.
If you did the elaboration of \code{ReplaceFirst} that just returns the original
string when the target is not found, then add tests for that, too.
Remember the necessary library reference and try it out.

\index{Grade File NUnit Exercise'}\index{exercise!Grade File NUnit test}

\subsection{Grade File NUnit Test Exercise}
\label{testing:index-5}\label{testing:grade-file-nunit-test-exercise}
Add a testing class using NUnit to {\hyperref[hw-gradefiles:hw-gradefiles]{\emph{Homework: Grade File}}}.
Remember the necessary library reference.
Sample data files and files for testing the results
are included in the project.  Just test
using command line parameters (so there is no Console input).
Test with both comp170 and comp150.

\index{interface}

\chapter{Interfaces}
\label{interfaces:interface}\label{interfaces:index-0}\label{interfaces:interfaces}\label{interfaces::doc}
\index{IComparable Interface}\index{interface!IComparable}

\section{Rationals Revisited}
\label{fractions-revisited:index-0}\label{fractions-revisited:rationals-revisited}\label{fractions-revisited::doc}\label{fractions-revisited:id1}
C\# has a built-in method to sort a List.  \code{List} is a
generic type, however, so how does C\# know how to do
comparisons for all different types?  Is this
specially programmed in for built-in types, or
can it be extended to user-defined types?

In fact it can be extended to user defined types,
such as our Rational.
To sort objects, you only need to be able to do one
thing: indicate which object comes before another.
We can do that.  The \code{CompareTo} method
already does that.  If Rational r1 is less than
Rational r2, then

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{r1}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{)} \PYG{p}{\PYGZlt{}} \PYG{l+m}{0}
\end{Verbatim}

The single CompareTo method is very versatile:  Just by varying
the comparison with 0, you vary the corresponding
comparison of Rationals:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] \code{r1.CompareTo(r2) \textless{} 0} means r1 \textless{} r2
\item[] \code{r1.CompareTo(r2) \textless{}= 0} means r1 \textless{}= r2
\item[] \code{r1.CompareTo(r2) \textgreater{} 0} means r1  \textgreater{} r2
\item[] \code{r1.CompareTo(r2) \textgreater{}= 0} means r1 \textgreater{}= r2
\item[] \code{r1.CompareTo(r2) == 0} means r1 is equal to r2
\item[] \code{r1.CompareTo(r2) != 0} means r1 is not equal to r2
\end{DUlineblock}
\end{quote}

None of the other methods for Rationals make any difference for
sorting:  Just this one method is needed.  Of course the
comparison of strings or doubles are done with
totally different implementations, but they have methods
with the same name, \code{CompareTo}, and with the same abstract
meaning.  Still C\# is strongly typed and we are talking about
totally different types.

An \emph{interface} allows us to group diverse classes under one
interface type.  An interface just focuses on the commonality of behavior
in one or more methods among the different classes.
Interface types, like classes can also be generic.
For sorting we are only concerned
with one method, \code{CompareTo}.  We want it to be able to compare to another
object of the same type.

C\# defines a generic interface \code{IComparable\textless{}T\textgreater{}}.  A type T can satisfy this interface if
if has a public instance method with signature:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k+kt}{int} \PYG{n+nf}{CompareTo}\PYG{p}{(}\PYG{n}{T} \PYG{n}{other}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

\index{:!in class heading}
There is one more step before we can use a library method to sort:
Although the signature shown above for \code{CompareTo} is the
one that C\# requires to be able to satisfy the \code{Icomparable\textless{}T\textgreater{}} interface,
it does not
automatically assume that this is your \emph{intention}.
You must explicitly say that you \emph{want} your class
to be considered to satisfy this interface.
For instance for Rational, we need to change
the class heading to:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{Rational} \PYG{p}{:} \PYG{n}{IComparable}\PYG{p}{\PYGZlt{}}\PYG{n}{Rational}\PYG{p}{\PYGZgt{}}
\end{Verbatim}

In general one or more interface names can be listed
after the class name and a colon,
and before the opening brace of the class body.
This particular interface is defined in
System.Collections.Generic, so we need to be using that namespace.

The project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/interfaces}{interfaces}
has the modified \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/interfaces/rational.cs}{rational.cs}
and \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/interfaces/test\_rational\_sort.cs}{test\_rational\_sort.cs}
to test this with a list of Rationals:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{using} \PYG{n+nn}{System.Collections.Generic}\PYG{p}{;}

\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{c+c1}{/// Use IComparable\PYGZlt{}Rational\PYGZgt{} interface to sort Rationals. }
   \PYG{k}{class} \PYG{n+nc}{TestRationalSort}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{public} \PYG{k}{static} \PYG{k}{void} \PYG{n+nf}{Main}\PYG{p}{(}\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{args}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{n}{Rational}\PYG{p}{\PYGZgt{}} \PYG{n}{nums} \PYG{p}{=} \PYG{k}{new} \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{n}{Rational}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{nums}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{nums}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{nums}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{nums}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{5}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{nums}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{nums}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{3}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}Before sorting: \PYGZdq{}} \PYG{p}{+} \PYG{n}{ListString}\PYG{p}{(}\PYG{n}{nums}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{nums}\PYG{p}{.}\PYG{n}{Sort}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{l+s}{\PYGZdq{}After sorting:  \PYGZdq{}} \PYG{p}{+} \PYG{n}{ListString}\PYG{p}{(}\PYG{n}{nums}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}

      \PYG{k}{public} \PYG{k}{static} \PYG{k+kt}{string} \PYG{n+nf}{ListString}\PYG{p}{(}\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{n}{Rational}\PYG{p}{\PYGZgt{}} \PYG{n}{list}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k+kt}{string} \PYG{n}{s} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{;}
         \PYG{k}{foreach} \PYG{p}{(}\PYG{n}{Rational} \PYG{n}{r} \PYG{k}{in} \PYG{n}{list}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{s} \PYG{p}{+}\PYG{p}{=} \PYG{n}{r} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{n}{s}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

which prints:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Before sorting: 1/2 11/3 \PYGZhy{}1/10 2/5 2/3 1/3
After sorting:  \PYGZhy{}1/10 1/3 2/5 1/2 2/3 11/3
\end{Verbatim}

\index{interface!hides actual underlying type}
Interfaces are very handy for dealing with the \emph{common} abstract behavior of
different objects and different underlying class, but if an object is
declared to be of interface type the compiler no longer sees the attributes
that are \emph{not} common to the interface.  A silly example, legal as far
as it goes:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{IComparable}\PYG{p}{\PYGZlt{}}\PYG{n}{Rational}\PYG{p}{\PYGZgt{}} \PYG{n}{r1} \PYG{p}{\PYGZhy{}} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{2}\PYG{p}{,}\PYG{l+m}{5}\PYG{p}{)}\PYG{p}{,}
                       \PYG{n}{r2} \PYG{p}{\PYGZhy{}} \PYG{k}{new} \PYG{n}{Rational}\PYG{p}{(}\PYG{l+m}{1}\PYG{p}{,} \PYG{l+m}{2}\PYG{p}{)}\PYG{p}{;}
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{r1}\PYG{p}{.}\PYG{n}{CompareTo}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{)} \PYG{p}{\PYGZgt{}} \PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// prints false}
\end{Verbatim}

The declarations are legal because a Rational does have interface type
\code{IComparable\textless{}Rational\textgreater{}}.  The use of \code{CompareTo} is legal
because that is the one method that this interface type guarantees.

However, if we add this extra line:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{r1}\PYG{p}{.}\PYG{n}{Multiply}\PYG{p}{(}\PYG{n}{r2}\PYG{p}{)}\PYG{p}{)}\PYG{p}{;} \PYG{c+c1}{// compiler error!}
\end{Verbatim}

Even though r1 and r2 are actually Rational underneath, where the
Multiply method is legal, their declaration as only their interface type
\emph{hides} this extra functionality from the compiler. \footnote{
It is possible to deal with the actual underlying class type, but this gets
more complicated.  It is better discussed in a course that more fully
explores \emph{inheritance}.
}


\section{csproject Revisited}
\label{csproj-revisited::doc}\label{csproj-revisited:csproject-revisited}
The \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/cs\_project1}{cs\_project1} project skeleton was set up with the different commands
in different classes, keeping related things together.

On the other hand they had high level structure in common.
Similar names were consciously used for methods:
\begin{itemize}
\item {} 
Each command needed to Execute

\item {} 
Each command needed to have Help for the user.

\end{itemize}

The corresponding names made it somewhat easier to follow
the part of the Game constructor
with the additions to the \code{helpDetails} Dictionary.
Also there is repetitive logic in
the crucial \code{proccessCommand} method.

In a game with more possible commands, the code
would only get more repetitious!
You would like to think of having a loop to replace the
repetitious code.

A major use of a C\# interface will allow this all to work
in neat loops.
For the first time we define our own interface, and
use that interface as a type in a declaration.

While we are at this we can refactor our code further:
classes that give a response to a command all obviously have their
Execute and Help methods.  They also have a command word
to call them.  We can further encapsulate
all data for the response by having the classes themselves
be able to announce the command that calls them.
We add a string property CommandWord to each of them.

We will add an extra convenience feature of C\# here.
Thus far we have used private instance variables and public
getter methods.  We can use a public instance variable declaration
with a similar effect as in:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k+kt}{string} \PYG{n}{CommandName} \PYG{p}{\PYGZob{}}\PYG{k}{get}\PYG{p}{;} \PYG{k}{private} \PYG{k}{set}\PYG{p}{;}\PYG{p}{\PYGZcb{}}
\end{Verbatim}

The extra syntax in braces says that users in a another class
may freely \emph{get} (read) the variable, but setting the variable is
still \emph{private}: it may only be done inside the class.  This is more
concise than using a getter method:  No getter needs to be declared;
referencing the data is shorter too, since it is a property,
no method parentheses are needed.

Note the unusual syntax: the declaration does
not end with a semicolon.  The only semicolons are inside the braces.
You will not be required to code with this notation, but it surely is neater than
using a getter method!

Now we can define our own interface taking all of these common features
together.  Since each is a response to a command, we will call our interface
Response:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   \PYG{c+c1}{/// Object that responds to a command}
   \PYG{k}{public} \PYG{k}{interface} \PYG{n}{Response}
   \PYG{p}{\PYGZob{}}
      \PYG{c+c1}{/// Execute cmd.}
      \PYG{c+c1}{/// Return true if the game is over; false otherwise }
      \PYG{k+kt}{bool} \PYG{n+nf}{Execute}\PYG{p}{(}\PYG{n}{Command} \PYG{n}{cmd}\PYG{p}{)}\PYG{p}{;}

      \PYG{c+c1}{/// Return a Help string for the command }
      \PYG{k+kt}{string} \PYG{n+nf}{Help}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}

      \PYG{k+kt}{string} \PYG{n}{CommandName} \PYG{p}{\PYGZob{}}\PYG{k}{get}\PYG{p}{;}\PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

Things to note:
\begin{itemize}
\item {} 
The heading has the reserved word \code{interface} instead of class.

\item {} 
All the common method headings and the property declaration
are listed.

\item {} 
See what is missing!  In place of each method
body is just a semicolon.

\item {} 
Everything in an interface is public.
The part of the property about private access is merely omitted.

\end{itemize}

We are going to need a collection if we want to simplify the code with
loops.  We could use code like the following, assuming we already declared
the objects helper, goer, and quitter:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Response}\PYG{p}{[}\PYG{p}{]} \PYG{n}{resp} \PYG{p}{=} \PYG{p}{\PYGZob{}}\PYG{n}{helper}\PYG{p}{,} \PYG{n}{goer}\PYG{p}{,} \PYG{n}{quitter}\PYG{p}{\PYGZcb{}}\PYG{p}{;}
\end{Verbatim}

See how we use Response as a declaration type!
Each of the objects in the declaration list \emph{is}
in fact a Response.

Now that we can process
with this collection and \code{foreach} loops,
we do not need the object names we gave at all:
We can just put new objects in the initialization sequence!

Now that we can think of these different objects as being of the same type, we can see
the processCommand logic, with its repetitive \code{if} statement syntax is just trying
to match a command word with the proper Response, so a Dictionary is what makes sense!

In fact all the logic for combining the various Responses is now moved into
CommandMapper, and the the CommandMapper constructor creates the Dictionary
used to look up the Response that goes with each command word.  Here is the whole code for
ResponseMapper, taking advantage of the Dictionary in other methods, too.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{using} \PYG{n+nn}{System}\PYG{p}{;}
\PYG{k}{using} \PYG{n+nn}{System.Collections.Generic}\PYG{p}{;}
\PYG{k}{namespace} \PYG{n+nn}{IntroCS}
\PYG{p}{\PYGZob{}}
   
   \PYG{c+c1}{/// Map commands names to commands.}
   \PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{CommandMapper}
   \PYG{p}{\PYGZob{}}
      \PYG{k}{public} \PYG{k+kt}{string} \PYG{n}{AllCommands} \PYG{p}{\PYGZob{}}\PYG{k}{get}\PYG{p}{;} \PYG{k}{private} \PYG{k}{set}\PYG{p}{;}\PYG{p}{\PYGZcb{}}
      \PYG{k}{private} \PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{n}{Response}\PYG{p}{\PYGZgt{}} \PYG{n}{responses}\PYG{p}{;} \PYG{c+c1}{//responses to commands}
       
      \PYG{c+c1}{/// Initialize the command response mapping}
      \PYG{c+c1}{///  game The game being played.}
      \PYG{k}{public} \PYG{n+nf}{CommandMapper}\PYG{p}{(}\PYG{n}{Game} \PYG{n}{game}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{n}{responses} \PYG{p}{=} \PYG{k}{new} \PYG{n}{Dictionary}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{string}\PYG{p}{,} \PYG{n}{Response}\PYG{p}{\PYGZgt{}}\PYG{p}{(}\PYG{p}{)}\PYG{p}{;}
         \PYG{n}{Response}\PYG{p}{[}\PYG{p}{]} \PYG{n}{resp} \PYG{p}{=} \PYG{p}{\PYGZob{}}
            \PYG{k}{new} \PYG{n+nf}{Quitter}\PYG{p}{(}\PYG{p}{)}\PYG{p}{,}
            \PYG{k}{new} \PYG{n+nf}{Goer}\PYG{p}{(}\PYG{n}{game}\PYG{p}{)}\PYG{p}{,}
            \PYG{k}{new} \PYG{n+nf}{Helper}\PYG{p}{(}\PYG{n}{responses}\PYG{p}{,} \PYG{k}{this}\PYG{p}{)}
            \PYG{c+c1}{// add new Responses here!}
         \PYG{p}{\PYGZcb{}}\PYG{p}{;}
         \PYG{n}{AllCommands} \PYG{p}{=} \PYG{l+s}{\PYGZdq{}\PYGZdq{}}\PYG{p}{;}
         \PYG{k}{foreach} \PYG{p}{(}\PYG{n}{Response} \PYG{n}{r} \PYG{k}{in} \PYG{n}{resp}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{n}{responses}\PYG{p}{[}\PYG{n}{r}\PYG{p}{.}\PYG{n}{CommandName}\PYG{p}{]} \PYG{p}{=} \PYG{n}{r}\PYG{p}{;}
            \PYG{n}{AllCommands} \PYG{p}{+}\PYG{p}{=} \PYG{n}{r}\PYG{p}{.}\PYG{n}{CommandName} \PYG{p}{+} \PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{p}{;}
         \PYG{p}{\PYGZcb{}}
      \PYG{p}{\PYGZcb{}}
   
      \PYG{c+c1}{/// Check whether aString is a valid command word. }
      \PYG{c+c1}{/// Return true if it is, false if it isn\PYGZsq{}t.}
      \PYG{k}{public} \PYG{k+kt}{bool} \PYG{n+nf}{isCommand}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{aString}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{responses}\PYG{p}{.}\PYG{n}{ContainsKey}\PYG{p}{(}\PYG{n}{aString}\PYG{p}{)}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   
      \PYG{c+c1}{/// Return the command associated with a command word.}
      \PYG{c+c1}{///  cmdWord The command word.}
      \PYG{c+c1}{/// Return the Response for the command.}
      \PYG{k}{public} \PYG{n}{Response} \PYG{n+nf}{getResponse}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{cmdWord}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{return} \PYG{n}{responses}\PYG{p}{[}\PYG{n}{cmdWord}\PYG{p}{]}\PYG{p}{;}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

There is even more to recommend this setup:  The old setup had references in multiple places
to various details about the collection of Responses.  That made it harder to follow and
definitely harder to update if you want to add a new command.
Now after writing the new class to respond to a new command,  the \emph{only} thing you
need to do is add a new instance of that class to the array initializer in the
CommandMapper constructor!

\begin{notice}{note}{Note:}
Interfaces never say anything about constructors.  Classes satisfying
an interface can have totally different constructors.
\end{notice}

In the code above,
\code{Quitter} has a very simple constructor.
(A \code{Quitter} has no individualized data,
and only has an instance because an interface can
only work with an instance, not with a static class.)
On the other hand the \code{Goer} and \code{Helper}
objects need to reference more data to work properly, so they have
parameters.

The revised Xamarin Studio project is \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/csproject\_stub}{csproject\_stub} (no 1 this time).

See how the Game class is simplified, too.

Talking about adding commands - these classes could be the basis of a game project for
a small group.  Have any ideas?  See {\hyperref[project:group-project]{\emph{Group Project}}}.

There are further examples of defining and using Interfaces
in the starting code for the exercises at the end of the next section.

\index{cohesion of code units}\index{coupling of classes}\index{separation of concerns among classes}\index{class!choosing what parts fit}

\subsection{Cohesion, Coupling, and Separation of Concerns}
\label{csproj-revisited:index-0}\label{csproj-revisited:cohesion-coupling-and-separation-of-concerns}
This section is motivated by the revisions to the project,
not specifically about Interfaces, though good use of them helps.

There are three important ideas in organizing your code into
classes and methods:

\emph{Cohesion} of code is how focused a portion of code is on a unified purpose.
This applies to both individual methods and to a class.  The higher
the cohesion, the easier it is for you to understand a method or
a class.  Also a cohesive method is easy to reuse in combination
with other cohesive methods.  A method that does several things
is not useful to you if you only want to do one of the things later.

\emph{Separation of concerns} allows most things related to a class to take place in the
class where they are easy to track, separated from other classes.
Data most used by one class should probably reside in that class.
Cohesion is related to separation of concerns:  The data and methods most used
by one class should probably reside in that class, so you do not need to go
looking elsewhere for important parts. Also, if you need to change something,
where concerns are separated into cohesive classes, with the data and
logic in one place, it is easier to see what to change, and the changes are likely
to be able to be kept internal to the class,
affecting only its internal implementation, not its public interface.

Some methods are totally related to the connection between classes, and there may not be
a clear candidate for a class to maximize the separation of concerns.  One thing to
look at is the number of references to different classes.  It is likely that the most
referred to class is the one where the method should reside.

\emph{Coupling} is the connections between classes.  If there were no connections
to a class, no public interface,
it would be useless except all by itself.  The must be some coupling between classes,
where one class uses another, but with increased cohesion and strong
separation of concerns you are likely to be able to have
looser coupling.  Limiting coupling makes it easier to follow
your code.  There is less jumping around. More important, it is easier to
modify the code.  There will be less interfacing between classes, so if
you need to change the public interface of a class, there are fewer places
in other classes that need to be changed to keep in sync.

Aim for strong cohesion, clear separation of concerns, and loose coupling.  Together
they make your code clearer, easier to modify, and easier to debug.

\index{exercise!igame}\index{interface!igame exercise}\index{igame exercise}

\subsubsection{IGame Interface Exercise}
\label{csproj-revisited:igame-interface-exercise}\label{csproj-revisited:index-1}\label{csproj-revisited:id1}
On a much smaller scale than the project, this exercise offers you
experience
writing classes implementing and using an interface.
\begin{enumerate}
\item {} 
Copy project stub \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/igame\_stub}{igame\_stub} to your own project,
and modify it as
discussed below.

\item {} 
Look at the IGame interface in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/igame\_stub/i\_game.cs}{i\_game.cs}.
Then look at \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/igame\_stub/addition\_game.cs}{addition\_game.cs},
that implements the interface. See how a new \code{AdditionGame} can be added to list of
\code{IGame}`s. Run \code{play\_games.cs}. Randomly choosing a game when there is
only one to choose from is pretty silly, but it gives you a start on a
more elaborate list of games.  The \code{PopRandom} method is a good general
model for choosing, removing, and returning a random element.

\item {} 
Write several very simple classes implementing the IGame interface,
and modify Main in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/igame\_stub/play\_games.cs}{play\_games.cs}
to create and add a new game of each
type. (Test adding one at a time.)

One such game to create with little more work would be a variation on
instance based Guessing Game \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/instance\_version/guess\_game.cs}{instance\_version/guess\_game.cs}.
You need to make slight modifications.
You could make Play return the opposite of the number of guesses,
so more guesses does generate a worse score. Note that you could not use the
original static game version:  Only objects can satisfy an interface.

\end{enumerate}


\subsubsection{Bisection With Function Interface Exercise}
\label{csproj-revisited:bisection-exercise}\label{csproj-revisited:bisection-with-function-interface-exercise}
See \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/bisection\_method/bisection\_method.cs}{bisection\_method/bisection\_method.cs}. Identify the interface.
See how two new classes satisfy the interface, while the rest of the
code in these classes is quite different:  One has an instance variable
and an explicit constructor, while the other does not.
See that the \code{Bisection} function
now has a parameter for an object containing the mathematical function to
use for root finding:  \code{Bisection} is now a generally useful method,
not just tied to one hard-coded function that might have a root.

Add a new class satisfying the \code{Function} interface; add a test in \code{Main}.
Try a function with multiple roots in the original interval and see what happens.
Then, using \emph{distinct} intervals in different tests,
find different roots of the same function.


\section{Chapter Review Questions}
\label{reviewinterfaces:chapter-review-questions}\label{reviewinterfaces::doc}
For these review questions, assume \code{Foo} is an interface type that you
have access to.
\begin{enumerate}
\item {} 
Suppose you are writing a new class that you want to satisfy
an existing interface:
\begin{enumerate}
\item {} 
Is matching the signatures required by the interface enough?

\item {} 
What else do you need in the new class heading?

\end{enumerate}

\item {} 
With interface type \code{Foo} can you:
\begin{enumerate}
\item {} 
Declare a formal parameter of type \code{Foo}?

\item {} 
Declare a list of type \code{List\textless{}Foo\textgreater{}}?

\item {} 
Declare an array of type \code{Foo{[}{]}}?

\item {} 
Create a new object with \code{new Foo()}?

\end{enumerate}

\item {} 
If you have an array of type \code{Foo{[}{]}}, then each element is
an object which has an underlying class type.  Must each element
have the \emph{same} underlying class type?

\item {} 
An interface type \code{Foo} has what heading (simplest)?

\item {} 
An interface type definition includes the signatures of all the methods
for that interface.  What is included after each signature?

\item {} 
May an interface definition include a constructor?

\item {} 
May a class satisfying an interface have further methods not listed
in the interface?

\item {} 
Identify the legal interface declarations, and say what is wrong with
any other code.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{interface} \PYG{n}{A}
\PYG{p}{\PYGZob{}}
    \PYG{k}{void} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{int}\PYG{p}{\PYGZgt{}} \PYG{n}{L}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
        \PYG{n}{L}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{l+m}{7}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{interface} \PYG{n}{B}
\PYG{p}{\PYGZob{}}
    \PYG{k}{void} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{int}\PYG{p}{\PYGZgt{}} \PYG{n}{L}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{interface} \PYG{n}{C}
\PYG{p}{\PYGZob{}}
    \PYG{k}{void} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{int}\PYG{p}{\PYGZgt{}} \PYG{n}{L}\PYG{p}{)}\PYG{p}{;}
    \PYG{k+kt}{int} \PYG{n+nf}{g}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{interface} \PYG{n}{D}
\PYG{p}{\PYGZob{}}
    \PYG{n}{D}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{)}\PYG{p}{;}
    \PYG{k}{void} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{int}\PYG{p}{\PYGZgt{}} \PYG{n}{L}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{E}
\PYG{p}{\PYGZob{}}
    \PYG{k+kt}{int} \PYG{n+nf}{g}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\item {} 
Which of these class definitions make the class implement the legal
interface C above?  Explain the problem with any that do not.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{CA}
\PYG{p}{\PYGZob{}}
    \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{int}\PYG{p}{\PYGZgt{}} \PYG{n}{L}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
        \PYG{n}{L}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{l+m}{7}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}

    \PYG{k}{public} \PYG{k+kt}{int} \PYG{n+nf}{g}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
       \PYG{k}{return} \PYG{n}{x}\PYG{p}{*}\PYG{n}{x}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{c+c1}{//  Same as CA, except with heading}
\PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{CB} \PYG{p}{:} \PYG{n}{C}
\PYG{c+c1}{// ...}
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{CC} \PYG{p}{:} \PYG{n}{C}
\PYG{p}{\PYGZob{}}
    \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{int}\PYG{p}{\PYGZgt{}} \PYG{n}{L}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
        \PYG{n}{L}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{l+m}{7}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}

    \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{g}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
       \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{x}\PYG{p}{*}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{CD} \PYG{p}{:} \PYG{n}{C}
\PYG{p}{\PYGZob{}}
    \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{int}\PYG{p}{\PYGZgt{}} \PYG{n}{L}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
        \PYG{n}{L}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{l+m}{7}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{class} \PYG{n+nc}{CE} \PYG{p}{:} \PYG{n}{C}
\PYG{p}{\PYGZob{}}
    \PYG{k}{private} \PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{;}

    \PYG{k}{public} \PYG{n+nf}{CE}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{a}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
       \PYG{k}{this}\PYG{p}{.}\PYG{n}{a} \PYG{p}{=} \PYG{n}{a}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}

    \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{f}\PYG{p}{(}\PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{k+kt}{int}\PYG{p}{\PYGZgt{}} \PYG{n}{L}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
        \PYG{n}{L}\PYG{p}{.}\PYG{n}{Add}\PYG{p}{(}\PYG{n}{a}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}

    \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{h}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
       \PYG{n}{Console}\PYG{p}{.}\PYG{n}{WriteLine}\PYG{p}{(}\PYG{n}{a}\PYG{p}{*}\PYG{n}{x}\PYG{p}{*}\PYG{n}{x}\PYG{p}{)}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}

    \PYG{k}{public} \PYG{k+kt}{int} \PYG{n+nf}{g}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{x}\PYG{p}{)}
    \PYG{p}{\PYGZob{}}
       \PYG{k}{return} \PYG{n}{x}\PYG{p}{*}\PYG{n}{a}\PYG{p}{;}
    \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

\end{enumerate}


\chapter{Recursion}
\label{recursion:recursion}\label{recursion::doc}
We are looking forward to a data structures course.  Recursion is an important topic.
It is not a topic we require in the introductory course.

More later.


\chapter{Data Structures}
\label{datastructures:data-structures}\label{datastructures::doc}
We have discussed some basic data structures that are available in C\#:  Array, List,
Set, Dictionary.  There are many more with many implementations.  Further
study leads you into a data structures course.

We may add some optional, forward looking material here.


\chapter{Appendix}
\label{appendix:appendix}\label{appendix::doc}\label{appendix:id1}
\index{development tools}

\section{Development Tools}
\label{monotools:development-tools}\label{monotools:index-0}\label{monotools::doc}\label{monotools:id1}

\subsection{About Software Development Kits (SDKs)}
\label{monotools:about-software-development-kits-sdks}
A software development kit (SDK) is a set of tools for developing in a
particular programming language (in our class, C\#). Developing in a
language means everything from compiling to running and (when things
go wrong) to debugging programs.

The Microsoft SDK is the proprietary implementation of .Net. It runs
only on Windows and is the primary development framework for all
things Microsoft.

The Mono Project SDK \textless{}\href{http://mono-project.com}{http://mono-project.com}\textgreater{} is the free/open source
equivalent implementation of the Microsoft SDK.
It runs on all major platforms (including Windows) and is needed in situations
where you want to develop .Net applications on non-Windows platforms.

As an interesting aside, the company whose developers lead the work on
the Mono SDK are working on commercial tools that allow you to
develop/run applications written in .Net on Apple iOS and Android
mobile devices (phones and tablets).


\subsection{Editing and Building Tools}
\label{monotools:editing-and-building-tools}
Early programs were written with rudimentary text editors,
more primitive than Windows Notepad.  Gradually tools got better.
Now there are editors that are highly optimized for editing code.

After code is edited, it has to be converted into an executable program.
That may involve several files and libraries and other dependencies.
Streamlining and automating this process was a big deal.  There
are a variety of building tools that can be used with, or built into
an SDK:  make, ant, and now NAnt for .net.

Many developers use an a la carte approach, using their favorite editor along
with their favorite building tool.


\subsection{About Integrated Development Environments (IDE)}
\label{monotools:about-integrated-development-environments-ide}
There are also all-in-one tools that combine an editor and build tools.
These are also used by many developers.

There are two major IDEs for .Net development, which we explain briefly below:
\begin{itemize}
\item {} 
Visual Studio is the Microsoft IDE that interfaces directly to the
Microsoft SDK.

\item {} 
Xamarin Studio is the free/open source IDE for developing applications
using the Mono SDK on Windows and all other platforms (in
particular, Linux and OS X).  The project started as MonoDevelop.
Now Xamarin is both a major contributor to the code and has commercial
versions for iOS development.  \emph{The name on the software is now}
\textbf{Xamarin Studio}, though you may see references to MonoDevelop instead.

\end{itemize}

In addition, there is another Windows-specific IDE, SharpDevelop, that
inspired the creation of Xamarin Studio. It is still actively maintained
and provides a somewhat ``lighter weight'' alternative to Visual Studio
for Windows users. Like Xamarin Studio, it is aimed at developers who
would prefer a more free/open source ``friendly'' version.


\subsection{Our Approach}
\label{monotools:our-approach}
In the interest of providing a consistent experience for our students who use
various operating systems on their own machines,
we will be using the multi-platform Mono (the SDK).

We find the IDE Xamarin Studio convenient to integrate everything for a beginner,
and it is a powerful tool at a more advanced level.  Hence we start off
introducing and using Xamarin Studio.  Later we will look at some of the
underlying tools that are obscured by the use of Xamarin Studio.

Mono has an extra advantage in the tool csharp, for immediate testing of
small snippets of code.  We will use it extensively as we introduce bits of
syntax.

As there is significant evolution of both the Microsoft
and Mono \emph{toolchains}--a fancy word we want you to know and a more
elegant way of saying SDK--we'll issue updates to this book.

Everything is free, but there are a number of steps.  Follow them carefully.

\index{mono installation}

\subsection{Installing Mono and Xamarin Studios}
\label{monotools:installing-mono-and-xamarin-studios}\label{monotools:install-mono}\label{monotools:index-1}
Because the Mono Project web page is known to change frequently, these
instructions are designed to be as generic as possible. If you have
any questions, you should contact the instructors immediately or seek
tutoring help.


\subsection{OS X}
\label{monotools:os-x}
\begin{notice}{warning}{Warning:}
Xamarin Studio needs at least version 10.8 of OSX.
If you have an older version, you can upgrade the operating system, or
possibly use an older version of Xamarin Studio.  In that case, ask for help.
\end{notice}

There are two downloads to get and install in order. Mono first:
\begin{enumerate}
\item {} 
Go to \textless{}\href{http://mono-project.com}{http://mono-project.com}\textgreater{}.

\item {} 
Look for the Mono downloads link. Link on OS-X.
You want to get the latest \emph{stable}
version of Mono for OS X. For this class, you need version 2.10 or
later, though preferably 3.2.4 or later. Choose the MRE version.
It installs directly. Administrative privileges are required to run the
installer, so if you do not know this information, please stop
here.

Do \emph{not} download Xamarin Studio from this site.
This version of Xamararin Studio bugs you with emails.

\end{enumerate}

Here is how to do a quick sanity check of your Mono setup:
\begin{enumerate}
\item {} 
Go to Applications -\textgreater{} Utilities and launch the Terminal
application, or quicker: enter terminal in Spotlight.
(Terminal is how you get to a command-line shell in OS X.)

\item {} 
You'll see a prompt that looks like this
\code{computername:folder user\$}.
This means that Terminal is ready for input.

\item {} 
Type \code{which csharp} and hit enter/return. You should see
\code{/usr/bin/csharp} as output. \code{csharp} is the C\# interpreter.

\item {} 
Type \code{which mcs} and hit enter/return. You should see
\code{/usr/bin/mcs} as output.  \code{mcs} is one of the interfaces to
the C\# compiler.

\end{enumerate}

\index{Xamarin Studio!installation}

\subsubsection{Xamarin Studio Installation - OSX}
\label{monotools:xamarin-studio-installation-osx}\label{monotools:install-md-osx}\label{monotools:index-2}\begin{enumerate}
\item {} 
Make sure Mono is installed first.

\item {} 
Now go to \href{http://monodevelop.com}{http://monodevelop.com}.  \textbf{Note}:  Do \emph{not} use a version
that is linked to the
mono-project.com site.  Getting the suggested open-source version
from \href{http://monodevelop.com}{http://monodevelop.com} should not lead to a prompt for your email address....

\item {} 
As with Mono, we need to look for the downloads link.
You should download the \emph{stable} version.

\item {} 
For OS X, the Xamarin Studio SDK is distributed as a DMG disk image. You'll need
to download this image and double-click it. Open the image and run
the installer. Administrative privileges are required to run the
installer.

\item {} 
This time, you will see an App for Xamarin Studio,
which you can drag and drop into the Applications folder.

\item {} 
If the preceding steps were successful, you can launch
Xamarin Studio by double-clicking the icon in your Applications
folder. (You won't know what to do with it yet, but at least you can
verify that it launches correctly and then use Command-Q to exit.)

\end{enumerate}


\subsection{Windows}
\label{monotools:windows}
There are four packages, so this takes a while.  Mono first:

Dr. Yacobellis has a video showing Windows installation.
\href{https://connect.luc.edu/p4hmzk2kbmt/}{https://connect.luc.edu/p4hmzk2kbmt/}
There may be further changes to the system.
\begin{enumerate}
\item {} 
Go to \textless{}\href{http://mono-project.com}{http://mono-project.com}\textgreater{}.

\item {} 
Look for the Mono downloads link. You want to get the latest
\emph{stable} version of Mono for Windows. For this class, you need version
2.10 or later, preferably 3.2.3 or later.

\item {} 
Choose the link: Mono for Windows, Gtk\#, and XSP, and download the
installation package

\item {} 
It is a
self-extracting executable, so you will need to double click it to
install. For Windows 7 users, you may need to check your taskbar to
see whether the installer is being held up by Microsoft's enhanced
security, UAM, that makes sure you really want to install something
you downloaded from the internet.

\end{enumerate}

Here is how to do a quick sanity check of your Mono setup:

\index{mono command prompt (Windows)}\index{csharp!mono command prompt (Windows)}

\subsubsection{Mono Command Prompt}
\label{monotools:index-3}\label{monotools:id2}\label{monotools:mono-command-prompt}\begin{enumerate}
\item {} 
Open the Windows Start Menu and type ``mono'' in the text field at the bottom.
You should see a short list of places ``mono'' appears.

\item {} 
Click on the choice that says ``Mono ... Command prompt''.
(This is probably faster than going to the Start Menu,
finding the Mono folder, expanding it, and clicking on
the Mono Command Prompt.)

\end{enumerate}

If it comes up, you are all set for an initial installation check. This will be the first
step later, when you want to run the handy csharp program or compile and run your
own programs.  When working, you can just leave this window open,
saving it for later use,
(or close and reopen later....)


\subsubsection{Xamarin Studio Installation - Windows}
\label{monotools:install-md-win}\label{monotools:xamarin-studio-installation-windows}\begin{enumerate}
\item {} 
Have Mono installed first.

\item {} 
Now go to \href{http://monodevelop.com}{http://monodevelop.com}.  \textbf{Note}:  Do \emph{not} use a version
that is linked to the
mono-project.com site.  Getting the suggested open-source version
from \href{http://monodevelop.com}{http://monodevelop.com} should not lead to a prompt for your email address....

\item {} 
As with Mono, we need to look for the downloads link, click on the Windows icon.
You should
click the link for the download of the requirements for the \emph{stable} version.
That should be at least numbered 4.2.2. \textbf{Do not install it yet.}

\textbf{Note however, that you will next}
\textbf{install two support packages}:
\begin{itemize}
\item {} 
.Net Framework 4.0 first.  The link takes you to a Microsoft download site.
Do not click the top Download button - that gives you much more than you need.
Further down in Popular download 01 is
Microsoft .NET Framework 4 (Web Installer).  Click on that and follow
the default sequence.

\item {} 
GKT\#  The GKT@ download directly downloads the GKT installer.  Again follow
the default installation sequence.

\item {} 
install Xamarin Studio \textbf{last}. The Download link gets you the installer
directly.  Install it following the default steps.

\end{itemize}

\item {} 
If the preceding steps were successful, you can launch
Xamarin Studio by double-clicking the icon on the Desktop
or using the Start Menu.
(You won't know what to do with it yet, but at least you can
verify at it launches correctly and then close the window.)

\end{enumerate}


\subsection{Linux}
\label{monotools:linux}
We only provide instructions for Debian-based Linux distributions such
as Ubuntu.
\begin{enumerate}
\item {} 
Using the command-line \code{apt-get} tool, you can install everything
that you need using \code{apt-get install monodevelop}. This should be
run as the \textbf{root} user (using the \code{sudo} command).

\item {} 
You can test the sanity of your setup by following the instructions
under OS X.

\end{enumerate}

Xamarin Studio releases on Linux tend to lag behind the official stable
release.

This page,
\href{https://launchpad.net/~keks9n/+archive/monodevelop-latest}{https://launchpad.net/\textasciitilde{}keks9n/+archive/monodevelop-latest},
describes
how to update your Xamarin Studio setup if it is not version 2.8 or later
as we'll need for this course.

We wish to stress that Linux is recommended for students who already
have a bit of programming experience under their belts. It can take a
significant amount of energy to get a Linux setup up and running and
to tweak it to your liking. While it has gotten ever so much easier
since the 1990s when it first appeared, we encourage you to set it up
perhaps a bit later in the semester or consider running it using
virtualization software (on Mac or Windows) such as VirtualBox or
VMware.

\index{Xamarin Studio!further tools}

\section{Xamarin Studio}
\label{xamarinstudio:index-0}\label{xamarinstudio::doc}\label{xamarinstudio:xamarinstudio}\label{xamarinstudio:xamarin-studio}
Several sections have given documentation for Xamarin Studio:
\begin{itemize}
\item {} 
{\hyperref[monotools:install-md-win]{\emph{Xamarin Studio Installation - Windows}}}

\item {} 
or {\hyperref[monotools:install-md-osx]{\emph{Xamarin Studio Installation - OSX}}}

\item {} 
{\hyperref[data_lab-edit-compile-run:lab-edit-compile-run]{\emph{Lab: Editing, Compiling, and Running with Xamarin Studio}}}

\item {} 
{\hyperref[data_programstructure:indentation-help]{\emph{Indentation Help}}}

\item {} 
{\hyperref[data_io:our-md-projects]{\emph{Running our Xamarin Studio Examples Solution}}}

\item {} 
{\hyperref[data_lab-division-sentences:xamarinstudio-reminders]{\emph{Xamarin Studio Reminders and Fixes}}}

\item {} 
{\hyperref[libraryclass:library-projects-in-xamarinstudio]{\emph{Library Projects in Xamarin Studio (Optional)}}}

\item {} 
{\hyperref[testing:running-nunit-tests]{\emph{Running the NUnit Tests}}}

\end{itemize}

\index{command line}

\section{Command Line Introduction}
\label{cmdline:index-0}\label{cmdline:commandline}\label{cmdline::doc}\label{cmdline:command-line-introduction}
Sometimes we will be directing you to use a command window or terminal to
compile and run
C\# programs. \footnote{
Thanks to Dr. Robert Yacobellis for elaborations to this section.
}

Reasons to use the command line:
\begin{itemize}
\item {} 
The command line precedes the graphical user interface (GUI) used in
modern operating systems and provides a simpler interface for input and output
that is very flexible and powerful for \emph{knowledgeable} users.
\begin{itemize}
\item {} 
Input comes from the keyboard as typed characters (no mouse processing).
Commands are only processed once you press \code{Enter}.

\item {} 
Output goes to the monitor as textual information (no window processing).

\item {} 
In C\# these input/output mechanisms are called Console processing.

\item {} 
Input from and output to files is done in a very similar way, simplifying learning.

\end{itemize}

\item {} 
Many software development organizations use command line processing
to automate creating, compiling (“building”), and running or executing
software programs.
\begin{itemize}
\item {} 
Command line “scripts” can be created to automate routine tasks.

\item {} 
Command line scripts are similar to C\# and other computer programs.

\item {} 
Serious software developers should be familiar with the command line.

\end{itemize}

\end{itemize}

The most direct way to access the command line (often called a \emph{command shell}):
\begin{itemize}
\item {} 
On Windows, to have easy access to Mono tools,
press the Windows key (lower left or lower right on the
keyboard) and type Mono, then select the
Mono Command Prompt and press Enter.

Alternately, if you do \emph{not need Mono tools for sure}, the general way to
get a command window is to press the Windows key
and R (lower or upper case) together, then type \emph{cmd} and
press the Enter or Return key – this brings up the basic command
processing program, cmd.

\item {} 
On a Mac just open a Terminal window – this is fine for the Mono SDK
commands.

\end{itemize}

Mac OSX, Linux and other Unix variants work basically the same once
you get to a terminal, so we will only distinguish Windows and Mac OS-X.

\index{command line!paths}\index{paths on command line}

\subsection{Navigating Directories}
\label{cmdline:navigating-directories}\label{cmdline:id2}\label{cmdline:index-1}
First make sure you are familiar with {\hyperref[paths:path-strings]{\emph{Path Strings}}}.

In a command shell there is always a \emph{current working directory}, usually
shown in the prompt for the next command.
When you open a Mono Command Prompt or Terminal window you will see
a prompt that tells you what folder or directory the command shell has
started in: If you directly open a terminal as in the previous section,
in Windows this is typically C:\textbackslash{}Windows\textbackslash{}System32, and on
a Mac it is typically /Users/\emph{yourLogin}.

Particularly on windows, this is an annoying folder.  There are several ways
to get to a better location.

If you can get to a parent folder of a folder that you want in a Windows Explorer window
(by right clicking on Start) or Mac Finder, there are shortcuts to opening a terminal
with the current directory being one shown in the graphical window:
\begin{description}
\item[{Windows}] \leavevmode\begin{enumerate}
\item {} 
Note: this approach does \emph{not} give your a Mono command prompt.

\item {} 
In Windows explorer navigate to the parent folder,
showing the folder you want as a subfolder.

\item {} 
Hold down the shift key and \emph{right} click on the desired folder.
A popup menu appears.

\item {} 
Click on ``Open a Command Window here''.

\end{enumerate}

\item[{Mac}] \leavevmode\begin{enumerate}
\item {} 
In the Finder navigate to the parent folder,
showing the folder you want as a subfolder.

\item {} 
Hold down the control key and click on the desired folder.
A popup menu appears.

\item {} 
Click on the bottom item Services, to get a submenu.

\item {} 
In the submenu click on ``New Terminal at Folder'' (likely the bottom entry).

\end{enumerate}

\end{description}

\index{command line!dir and ls}\index{dir on Windows command line}\index{ls on Mac command line}
Files in the current working directory can to referred to by their simple names,
e.g., \emph{myfile.txt}.  You can list all the files in the directory with the simple
command \code{dir} (short for directory) in Windows or \code{ls} (short for list) on a Mac.

You need to refer to files not in the current directory via a relative or absolute
path name.

After starting in one folder, you may well want to change the current folder
without opening a new terminal window.  This is particularly true if you
start with a Windows Mono command prompt.
You will see below that you can change the current
directory with the \emph{cd} command.

On a Mac, the file system is unified in
one hierarchy. On Windows there may be several drives, and you need to start a
path reference with a drive, like C:, if it is not the current drive.

When you run cmd or start a Mono command prompt in Windows,
you are likely to want to get to
your home directory (where the Mac users start automatically).

Windows 7 or 8 users enter the command below (substituting your login ID)
to get to your home directory:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
cd C:\PYGZbs{}Users\PYGZbs{}yourLoginId
\end{Verbatim}

The cd is short for ``Change Directory'', changing the current directory.

\index{drive change on Windows}\phantomsection\label{cmdline:drive-change}
\begin{notice}{warning}{Warning:}
Windows only:
The cd command does not work the way you are likely to think about it on
a Windows system with more than one drive (like C: and flash drive E: that you have
plugged in).  Windows remembers a separate current directory for each
separate drive.  It also \emph{separately} remembers a \emph{current drive}.
\emph{You do not change the current drive with the cd command.}
The command to change the current drive is just the name of the
drive with a colon after it.  For example the command

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
E:
\end{Verbatim}

sets the current drive to E:, and the active directory is the
current directory on E:.

However, if the current drive is C:, and you enter the command

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
cd E:\PYGZbs{}comp170
\end{Verbatim}

then you change the current directory on E:, but \emph{the current drive remains C:}.
\end{notice}

We described above how you can use a Windows Explorer/Finder folder to
open a \emph{new} terminal.
If you just want to change
directory in an existing terminal, there is also a shortcut to copy a long
folder name, given a Windows Explorer/Finder folder:

Windows
\begin{itemize}
\item {} 
Depending on the setup of your options, in the address bar you may \emph{not} see a clear
path with a drive and backslashes.  In that case generally clicking to the right of any
directory in the path converts the view to the version we use on the
command line.

\item {} 
When you see a full absolute path, you can just note it and manually copy it,
or else select it all and copy it
and follow the instructions in {\hyperref[cmdline:copypaste]{\emph{Copy and Paste}}} to later
paste in the command window.

\item {} 
In any case click in the terminal window, type \emph{cd} and a space, then
type or paste the path.

\item {} 
Of course, you can also go the other way – if you see the current
directory name in the Windows prompt, type that into an Explorer address
bar to see its contents in a GUI window.

\end{itemize}

On a Mac there is an easier shortcut:
\begin{itemize}
\item {} 
Type \emph{cd} and a space to start the command in the terminal

\item {} 
Locate the directory you want as a subfolder in the Finder
(not opening the directory).

\item {} 
Drag the directory icon to the terminal.  The path gets pasted! Press return.

\end{itemize}


\subsection{Common Commands}
\label{cmdline:common-commands}
The command shell waits for you to type in a \emph{command} (a
short name that the shell recognizes) followed by 0 or more \emph{parameters}
separated by spaces (and Enter).
Note that if a parameter contains spaces you must surround the
parameter value with matching single or double quotes – you’ll see an
example later.

We are going to mention some of the simplest uses of basic commands.  More
advanced documentation would include more options.

Some commands are common between the Windows and Mac shells:
\begin{description}
\item[{dir (Windows) or ls (Mac)}] \leavevmode
to list all the files a in the current directory or a named directory.

\end{description}

\index{command line!cd}\index{cd on command line}\index{change directory on command line}\begin{description}
\item[{cd}] \leavevmode
stands for \emph{Change Directory} – you can use this
command to change the current working directory to a different one.

You can use this command to change to directories where your C\#
program source files are located, if different from the initial
directory.

On Windows, suppose you created a directory C:\textbackslash{}COMP170\textbackslash{}hello; to
change to that, type \emph{cd C:\textbackslash{}COMP170\textbackslash{}hello} and press Enter – the shell
prompt will change to show this new directory location and programs like
\emph{mcs} and \emph{mono} will be able to access files there, directly
by name.  If the Comp170 directory was you current directory, it would
be shorter to use relative paths and just \code{cd hello}.  Remember if
you want a different Windows drive, you must first use a
{\hyperref[cmdline:drive-change]{\emph{drive change command}}}.

On a Mac you can also use either an absolute or a relative path with \code{cd}.

If you included a space in one or more of the directory names, for
example C:\textbackslash{}COMP 170\textbackslash{}hello (a space between COMP and 170) you should
enclose that part(s) in quotes like so: \emph{cd C:\textbackslash{}''COMP 170''\textbackslash{}hello}

Mac Note: if you type just \emph{cd} and press Enter you will change back to
your home directory.  There is also a shorthand name for your home
directory in command paths:  tilde (\textasciitilde{}), often shifted backquote on the
keyboard. Sorry,
no such thing with Windows.

\end{description}

\index{command line!mkdir}\index{mkdir on command line}\begin{description}
\item[{mkdir}] \leavevmode
stands for make directory –
you can use \emph{mkdir} to create a new empty directory in the current
directory.

For example, on a Mac with current directory /Users/\emph{YourLogin},
type \emph{mkdir hello} and press Enter – this will create a new directory
/Users/\emph{yourLogin}/hello if it did not exist before; you can now create
a C\# source file in that directory and enter \emph{cd hello} in the command shell.

An optional Windows abbreviation is \emph{md}.

\end{description}

\index{command line!rmdir}\index{rmdir on command line}\begin{description}
\item[{rmdir}] \leavevmode
removes an \emph{empty} directory that you give as parameter, e.g.,
\begin{quote}

rmdir hello
\end{quote}

\end{description}

With Mono installed (and for Windows, with a Mono command window), the
programs associated with Mono can be used:

\index{command line!mcs}\index{mcs compile on command line}\index{compile on command line mcs}\begin{description}
\item[{mcs}] \leavevmode
compiles one or more listed C\# source files without using Xamarin Studio.

\item[{csharp}] \leavevmode
is the interactive C\# statement testing program.

\end{description}

Other useful commands, with different names for Windows and Mac,
are listed next by generic function,
with general Windows syntax first and Mac second, and then
often examples in the same order:

\index{command line!display text file}\index{type on Windows command line}\index{cat on Mac command line}
Display the contents of a text file in the command window. The Unix/Mac
name origin:  a more complicated
use of cat is to con\textbf{cat}enate files.
\begin{quote}

\begin{DUlineblock}{0em}
\item[] type \emph{textFileName}
\item[] cat \emph{textFileName}
\end{DUlineblock}

\begin{DUlineblock}{0em}
\item[] type my\_program.cs
\item[] cat my\_program.cs
\end{DUlineblock}
\end{quote}

\index{command line!copy file}\index{copy on Windows command line}\index{cp on Mac command line}
Make a copy of a file.  Caution: If the second file already exists,
you wipe out the original contents!
\begin{quote}

\begin{DUlineblock}{0em}
\item[] copy \emph{originalFile}  \emph{copyName}
\item[] cp \emph{originalFile}  \emph{copyName}
\end{DUlineblock}

\begin{DUlineblock}{0em}
\item[] copy prog.cs prog\_bak.cs
\item[] cp prog.cs prog\_bak.cs
\end{DUlineblock}
\end{quote}

\index{command line!delete a file}\index{erase on Windows command line}\index{rm on Mac command line}
Erase or remove a file:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] erase \emph{fileToKill}
\item[] rm \emph{fileToKill}
\end{DUlineblock}

\begin{DUlineblock}{0em}
\item[] erase poorAttempt.cs
\item[] rm poorAttempt.cs
\end{DUlineblock}
\end{quote}

Another Windows equivalent is \code{del} (short for delete).

\index{command line!help}\index{help on command line}\index{man on Mac command line}
Help on a command:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] help \emph{commandName};
\item[] \emph{commandName} --help
\end{DUlineblock}
\end{quote}

Note the double dash above: This
sometimes works for concise help on a Mac while you can generally get
immensely detailed help overload on a Mac from
\begin{quote}

man \emph{commandName}
\end{quote}

\index{command line!script}\index{script on command line}

\subsection{Scripts}
\label{cmdline:index-12}\label{cmdline:scripts}
This is not a subject of this course, but commands can be combined into
script files.

Scripting languages are in fact whole new specialized programming languages,
that include many of the types of
programming statements found in C\#.

\index{command line!copy and paste text}\index{copy text on command line}\index{paste text on command line}

\subsection{Copy and Paste}
\label{cmdline:copypaste}\label{cmdline:copy-and-paste}\label{cmdline:index-13}
Copying or pasting with a Mac is is the same with a terminal as in other editing:
Use the same Apple Command key with C or P, and you can select with the mouse.

In Windows it is more complicated to use a command window:
You can paste into the current command line by \emph{right}
clicking on the Command Window Title bar, and select edit and then paste.

By default
a Windows command window is not sensitive to the mouse.
You can change so that it is sensitive
for select and copy:  Right click in the title bar, select defaults, and make sure
the check boxes under edit options are \emph{all} checked.
(The last two are explained in the next section.)
Click OK.  Then you can select with
mouse and press Enter for the selection to be remembered in the copy buffer.

\index{command line!shortcuts}\index{shortcuts on command line}\index{file completion on command line}\index{history on command line}

\subsection{Command Line Shortcuts}
\label{cmdline:index-14}\label{cmdline:command-line-shortcuts}
Both Windows and Mac (with the right options selected,
like the Windows check boxes in the last section), allow you to reduce typing:

You can bring back a previous command for the history of commands that are automatically
remembered: Use the up and down arrows.  This makes it very easy to run the same command
again, or to make slight edits.

Both Windows and OS-X can see what files are in any directory being referred to.
If you just start to type a file or folder name and then press the Tab key, both
Windows and  OS-X will do \emph{file completion}
to complete the name if there is no ambiguity.  If there is ambiguity,
they work differently:
\begin{itemize}
\item {} 
Windows will cycle through all the options as you keep
pressing Tab.

\item {} 
On the first tab OS-X will do nothing but give a sound if there is
ambiguity, but the second tab will list all the options.  Then you need to type enough
more to disambiguate the meaning.

\end{itemize}

\index{precedence}\index{operator!precedence}

\section{Precedence of Operators}
\label{precedence:index-0}\label{precedence::doc}\label{precedence:precedence-of-operators}\label{precedence:precedence}
Earlier lines have higher precedence.
Only operators used in this book are included:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
obj.field  f(x)  a[i]  n++  n\PYGZhy{}\PYGZhy{}  new
+  \PYGZhy{}  ! (Type)x (Unary operators)
* / \PYGZpc{}
+ \PYGZhy{} (binary)
\PYGZlt{} \PYGZgt{} \PYGZlt{}= \PYGZgt{}=
== !=
\PYGZam{}\PYGZam{}
\textbar{}\textbar{}
=  *=  /=  \PYGZpc{}=  +=  \PYGZhy{}=
\end{Verbatim}

All symbols are listed at the beginning of the index.

Parentheses for grouping are encouraged with less common combinations, even if
not strictly necessary.

\index{homework!grade\_calc I}

\section{Homework: Grade Calculation}
\label{homework-gradecalculation:index-0}\label{homework-gradecalculation:homework-grade-calculation}\label{homework-gradecalculation::doc}\label{homework-gradecalculation:id1}
Create a program file \code{grade\_calc.cs} for this assignment.
You are going to be
putting together your first programming assignment where
you will be taking the various concepts we have learned
thus far from class and to put together your first
meaningful program on your own.

This program will incorporate the following elements:
\begin{itemize}
\item {} 
Prompt a user for input.

\item {} 
Perform some rudimentary calculations.

\item {} 
Make some decisions.

\item {} 
Produce output.

\end{itemize}

As we've mentioned earlier in class, our focus is going
to be on learning how to write computer programs that start
with a Main() function and perhaps use other functions as
needed to \emph{get a particular job done}. Eventually, we will
be incorporating more and more advanced elements, such as
classes and objects. For now, we would like you to organize
your program according to the guidelines set forth here.


\subsection{Program Summary}
\label{homework-gradecalculation:program-summary}
Our first program is based on a common task that every
course professor/instructor needs to do: make grades. In
any given course, there is a \emph{grading scale} and a set of
\emph{categories}.

Here is sample output from two runs of the program.
The only data entered by the user are
show in \textbf{boldface} for illustration here.

One successful run with the data used above:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] Enter weights for each part as an integer
\item[] percentage of the final grade:
\item[] Exams: \textbf{40}
\item[] Labs: \textbf{15}
\item[] Homework: \textbf{15}
\item[] Project: \textbf{20}
\item[] Participation: \textbf{10}
\item[] 
\item[] Enter decimal numbers for the averages in each part:
\item[] Exams: \textbf{50}
\item[] Labs: \textbf{100}
\item[] Homework: \textbf{100}
\item[] Project: \textbf{100}
\item[] Participation: \textbf{5}
\item[] 
\item[] Your grade is 70.5\%
\item[] Your letter grade is C-.
\end{DUlineblock}
\end{quote}

A run with bad weights:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] Enter weights for each part as an integer
\item[] percentage of the final grade:
\item[] Exams: \textbf{30}
\item[] Labs: \textbf{10}
\item[] Homework: \textbf{10}
\item[] Project: \textbf{10}
\item[] Participation: \textbf{10}
\item[] 
\item[] Your weights add to 70, not 100.
\item[] This grading program is ending.
\end{DUlineblock}
\end{quote}


\subsection{Details}
\label{homework-gradecalculation:details}
Make your program file have the name \code{grade\_calc.cs}.

This is based on the idea of Dr. Thiruvathukal's own
legendary course syllabus.
We're going to start
by assuming that there is a fixed set of categories.
As an example we assume Dr. Thiruvathukal's categories.

In the example below we work out for
Dr. Thiruvathukal's weights in each category,
though your program should prompt
the user for these integer percentages:
\begin{itemize}
\item {} 
exams - 40\% (integer weight is 40)

\item {} 
labs - 15\% (weight 15)

\item {} 
homework - 15\% (weight 15)

\item {} 
project - 20\% (weight 20)

\item {} 
participation - 10\% (weight 10)

\end{itemize}

Your program will prompt the user for each the weights
for each of the categories. These weights will be entered
as integers, which must add up to 100.

If the weights do not add up to 100, print a message and
end the program. You can use an \code{if}-\code{else} construction
here.  An alternative is an \code{if} statement to test for a bad sum.
In the block of statements that go with the \code{if} statement,
you can put not only the message to the user, but also a
statement:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{return}\PYG{p}{;}
\end{Verbatim}

Recall that a function ends when a return statement is reached.
You may not have heard that this can also be used
with a \code{void} function.  In a \code{void} function
there is no return value in the \code{return} statement.

Assuming the weights add to 100, then we will use
these weights to compute your
grade as a \code{double}, which gives you the
best precision when it comes to floating-point arithmetic.

We'll talk in class about why we want the weights to be
integers. Because floating-point mathematics is not 100\%
precise, it is important that we have an accurate way
to know that the weights \emph{really add up} to 100. The only
way to be assured of this is to use \emph{integers}. We will
actually use floating-point calculations to compute the
grade, because we have a certain tolerance for errors at
this stage. (This is a fairly advanced topic that is
covered extensively in courses like COMP 264/Systems
Programming and even more advanced courses like Numerical
Analysis, Comp 308.)

We are going to pretend
that we already know our score (as a percentage) for each
one of these categories, so it will be fairly simple to
compute the grade.

For each category, you will define a weight (int) and a
score (double). Then you will sum up the weight * score and
divide by 100.0 (to get a double-precision floating-point
result).

This is best illustrated by example.

George is a student in COMP 170. He has the following
averages for each category to date:
\begin{itemize}
\item {} 
exams: 50\%

\item {} 
labs: 100\%

\item {} 
homework: 100\%

\item {} 
project: 100\%

\item {} 
participation: 5\%

\end{itemize}

The following session with the \code{csharp} interpreter shows
the how you would declare all of the needed variables and
the calculation to be performed:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} int exam\PYGZus{}weight = 40;
csharp\PYGZgt{} int lab\PYGZus{}weight = 15;
csharp\PYGZgt{} int hw\PYGZus{}weight = 15;
csharp\PYGZgt{} int project\PYGZus{}weight = 20;
csharp\PYGZgt{} int participation\PYGZus{}weight = 10;

csharp\PYGZgt{} double exam\PYGZus{}grade = 50.0;
csharp\PYGZgt{} double lab\PYGZus{}grade = 100;
csharp\PYGZgt{} double homework\PYGZus{}grade = 100;
csharp\PYGZgt{} double project\PYGZus{}grade = 100;
csharp\PYGZgt{} double participation\PYGZus{}grade = 5;
\end{Verbatim}

This is intended only to be as an example though. Your
program must ask the user to enter each of these variables.

Once we have all of the weights and scores entered, we
can calculate the grade as follows.  This is a long
expression: It is continued on multiple lines.  Recall all
the \code{\textgreater{}} symbols are csharp prompts are not part of the
expression:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} double grade = (exam\PYGZus{}weight * exam\PYGZus{}grade +
      \PYGZgt{} homework\PYGZus{}weight* homework\PYGZus{}grade +
      \PYGZgt{} lab\PYGZus{}weight * lab\PYGZus{}grade + project\PYGZus{}weight * project\PYGZus{}grade +
      \PYGZgt{} participation\PYGZus{}weight * participation\PYGZus{}grade) / 100.0;
\end{Verbatim}

Then you can display the grade as a percentage:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
csharp\PYGZgt{} Console.WriteLine(\PYGZdq{}Your grade is \PYGZob{}0\PYGZcb{}\PYGZpc{}\PYGZdq{}, grade);
Your grade is 70.5\PYGZpc{}
\end{Verbatim}

Now for the fun part. We will use \code{if} statements to
print the letter grade. You will actually need to use
multiple \code{if} statements to test the conditions. A way
of thinking of how you would write the logic for determining
your grade is similar to how you tend to think of the \emph{best}
grade you can \emph{hope for} in any given class. (We know that
we used to do this as students.)

Here is the thought process:
\begin{itemize}
\item {} 
If my grade is 93 (93.0) or higher, I'm getting an A.

\item {} 
If my grade is 90 or higher (but less than 93), I
am getting an A-.

\item {} 
If my grade is 87 or higher (but less than 90), I
am getting a B+.

\item {} 
And so on...

\item {} 
Finally, if I am less than 60, I am unlikely to pass.

\end{itemize}

We'll come to see how \emph{logic} plays a major role in
computer science--sometimes even more of a role than
other mathematical aspects. In this particular program,
however, we see a bit of the best of both worlds. We're
doing \emph{arithmetic} calculations to \emph{compute} the grade.
But we are using \emph{logic} to determine the grade in the
cold reality that we all know and love: the bottom-line
grade.

This assignment can be started after the data chapter,
because you can do most all of it with tools
learned so far.  Add the parts with \code{if} statements
when you have been introduced to \code{if} statements.
(Initially be sure to use data that makes the
weights actually add up to 100.)

You should be able to write the program more concisely
and readably if you use functions developed
in class for the prompting user input.


\subsection{Grading Rubric}
\label{homework-gradecalculation:grading-rubric}
\begin{notice}{warning}{Warning:}
As a general rule, we expect programs to be complete,
compile correctly, run, and be
thoroughly tested. We are able to grade an incomplete program
but will only give at most 10/25
for effort. Instead of submitting something incomplete,
you are encouraged to complete your program and
submit it per the late policy.  Start early and get help!
\end{notice}

25 point assignment broken down as follows:
\begin{itemize}
\item {} 
Enter weights, with prompts \textbf{{[}3{]}}

\item {} 
End if the weights do not add to 100: \textbf{{[}5{]}}

\item {} 
Enter grades, with prompts: \textbf{{[}3{]}}

\item {} 
Calculate the numerical average and display with a label: \textbf{{[}5{]}}

\item {} 
Calculate the letter grade and display witha label: \textbf{{[}5{]}}

\item {} 
Use formatting standards for indentation: \textbf{{[}4{]}}
\begin{itemize}
\item {} 
Sequential statements at the same level of indentation

\item {} 
Blocks of statements inside of braces indented

\item {} 
Closing brace for a statement block always lining up with the
heading before the start of the block.

\end{itemize}

\end{itemize}


\subsection{Logs and Partners}
\label{homework-gradecalculation:logs-and-partners}
You may work with a partner, following good pair-programming practice,
sharing responsibility for all parts.

Only one of a pair needs to submit the actual programming assignment.
However \emph{both} students, \emph{independently}, should write and
include a log in their
Homework submission.  Students working alone should also submit a log,
with fewer parts.

Each individual's log should indicate each of the following clearly:
\begin{itemize}
\item {} 
Your name and who your partner is (if you have one)

\item {} 
Your approximate total number of hours working on the homework

\item {} 
Some comment about how it went - what was hard ...

\item {} 
An assessment of your contribution (if you have a partner)

\item {} 
An assessment of your partner's contribution (if you have a partner).

\end{itemize}

Just omit the parts about a partner if you do not have one.

\begin{notice}{note}{Note:}
Name the log file with the exact file name:
``log.txt'' and make it a plain text file.
You can create it in a program editor or in a fancy document editor.
If you use a fancy document editor, be sure to a ``Save As...'' dialog,
and select the file format ``plain text'',
usually indicated by the ''.txt'' suffix.
It does not work to save a file in the default word processor format, and
then later just change its name (but not its format) in the file system.
\end{notice}

\index{homework!grade calculation 2}\index{grade calculation 2 homework}

\section{Homework: Grade Calculation from Individual Scores}
\label{homework-gradecalculation2:homework-grade-calculation-from-individual-scores}\label{homework-gradecalculation2:homework-grade-calculation2}\label{homework-gradecalculation2:index-0}\label{homework-gradecalculation2::doc}
In the previous assignment, we calculated grades based on a \emph{memorized}
overall grade within each of the categories below, as in this example:
\begin{itemize}
\item {} 
exams - 40\% (integer weight is 40)

\item {} 
labs - 15\% (weight 15)

\item {} 
homework - 15\% (weight 15)

\item {} 
project - 20\% (weight 20)

\item {} 
participation - 10\% (weight 10)

\end{itemize}

In this assignment, we are going to change the specification slightly
to make the program a bit smarter. Instead of someone having to remember
what their average grade was for each category, we will prompt the user for
the number of items within each category (e.g. number of exams, number
of labs, etc.), have the user enter individual grades, and have the program
calculate the average for the category.

As usual, we will begin by specifying \emph{requirements}.
User responses are shown \textbf{bold faced}.


\subsection{Functional Requirements}
\label{homework-gradecalculation2:functional-requirements}\begin{enumerate}
\item {} 
Instead of bombing out if the weights don't add up to 100, use {\hyperref[do-while:do-while]{\emph{Do-While Loops}}}
to prompt the user again
for all of the weights until they do add up to 100. A \code{do \{ ... \} while}
loop is the right choice here, because you can test all of the weights
at the end of the loop, after each time they have been entered
in the loop.

\item {} 
Write a function, \code{FindAverage},
to do the following.  The example refers to the category exam,
but you will want your code to work for each
category, and hence the category
\emph{name} will need to be a parameter to \code{FindAverage}.)

Prompt the user for the number of items in the category:
\begin{quote}

Please enter the number grades in category exam: \textbf{4}
\end{quote}

Instead of prompting the user for an overall average
exam grade, use a loop  to
read one grade at a time. The grades will be added together (on the fly)
to give the grade for that category. For example, after you have asked
for the number of exams, you'd prompt the user to enter each exam
grade and have the program compute the sum. As soon as a category
sum is calculated, also print out the average as shown in the sample below:
\begin{quote}

\begin{DUlineblock}{0em}
\item[] Please enter the grade for exam 1: \textbf{100}
\item[] Please enter the grade for exam 2: \textbf{90}
\item[] Please enter the grade for exam 3: \textbf{80}
\item[] Please enter the grade for exam 4: \textbf{92}
\item[] Calculated average exam grade = 90.5
\end{DUlineblock}
\end{quote}

Of course you must return the grade to the caller for use in the
overall weighted average grade.

A category may have only a single grade, in which case the
user will just enter the number of grades as 1.

\item {} 
Once you have read in the data for each of the items within a category,
you'll basically be able to \emph{reuse} the code that you developed in the
previous assignment to compute the weighted average and print the
final letter grade.

\item {} 
Print the final numerical average, \emph{this time rounded to one decimal place}.
If the final average was actually 93.125, you would print 93.1.
If the final average was actually 93, you would print 93.0.
If the final average was actually 93.175, you would print 93.2.

\end{enumerate}


\subsection{Style Requirements}
\label{homework-gradecalculation2:style-requirements}\begin{enumerate}
\item {} 
For this assignment, you are expected to start using functions for all
aspects of the assignment. For example, it can become tedious in a hurry
to write code to prompt for each of exams, labs, homework, etc. when
a single function (with parameter named \emph{category}) could be used to
avoid repeating yourself. In particular you should
write your function to take advantage of our \code{UI}
class, from {\hyperref[userinput:ui]{\emph{User Input: UI}}}.

\item {} 
Also beginning with this assignment, it is expected that your work
will be presented neatly. That is, we expect the following:
\begin{itemize}
\item {} 
proper indentation that makes your program more readable by other
humans. Use all spaces, not tabs to indent.  You never know what
default tabs your grader will have set up.

\item {} 
proper naming of classes and functions. In C\#, the convention is to
begin a name with a capital letter. You can have multiple words in a
name, but these should be capitalized using a method known as
CamelCase \phantomsection\label{homework-gradecalculation2:id1}{\hyperref[homework-gradecalculation2:camelcase]{{[}CamelCase{]}}}. We also recommend this same naming convention
for variables but with a lowercase first letter.
For variables, we are also
ok with the use of underscores. For example, in homework 1 we used
names like \emph{exam\_grade}. If you use CamelCase, you can name this
variable \emph{examGrade}.

\item {} 
If you have any questions about the neatness or appearance of your
code, please talk to the instructor or teaching assistant.

\item {} 
This guide from CIS 193 at \phantomsection\label{homework-gradecalculation2:id2}{\hyperref[homework-gradecalculation2:upenncsharp]{{[}UPennCSharp{]}}}
provides a nice set of conventions
to follow. We include this here so you know that other faculty at
other universities also consider neatness/appearance to be important.

\end{itemize}

\end{enumerate}


\subsection{Grading Rubric}
\label{homework-gradecalculation2:grading-rubric}
\begin{notice}{warning}{Warning:}
As a general rule, we expect programs to be complete,
compile correctly, run, and be
thoroughly tested. We are able to grade an incomplete program
but will only give at most 10/25
for effort. Instead of submitting something incomplete,
you are encouraged to complete your program and
submit it per the late policy.  Start early and get help!
\end{notice}

25 point assignment broken down as follows:
\begin{itemize}
\item {} 
Loop until weights add to 100: 5

\item {} 
Average any number of grades in a category: 5

\item {} 
One function that is reused and works for the average in each category: 5

\item {} 
Print final numerical grade rounded to one decimal place: 2

\item {} 
Previous program features still work: 3

\item {} 
Style: 5

\end{itemize}


\subsection{Logs and Partners}
\label{homework-gradecalculation2:logs-and-partners}
You may work with a partner, following good pair-programming practice,
sharing responsibility for all parts.

Only one of a pair needs to submit the actual programming assignment.
However \emph{both} students, \emph{independently}, should write and
include a log in their
Homework submission.  Students working alone should also submit a log,
with fewer parts.

Each individual's log should indicate each of the following clearly:
\begin{itemize}
\item {} 
Your name and who your partner is (if you have one)

\item {} 
Your approximate total number of hours working on the homework

\item {} 
Some comment about how it went - what was hard ...

\item {} 
An assessment of your contribution (if you have a partner)

\item {} 
An assessment of your partner's contribution (if you have a partner).

\end{itemize}

Just omit the parts about a partner if you do not have one.

\begin{notice}{note}{Note:}
Name the log file with the exact file name:
``log.txt'' and make it a plain text file.
You can create it in a program editor or in a fancy document editor.
If you use a fancy document editor, be sure to a ``Save As...'' dialog,
and select the file format ``plain text'',
usually indicated by the ''.txt'' suffix.
It does not work to save a file in the default word processor format, and
then just change its name (but not its format) in the file system.
\end{notice}

\index{homework!grade files}\index{grade files homework}

\section{Homework: Grade File}
\label{hw-gradefiles:homework-grade-file}\label{hw-gradefiles:index-0}\label{hw-gradefiles::doc}\label{hw-gradefiles:hw-gradefiles}
Copy project files in \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/grade\_file\_homework\_stub}{grade\_file\_homework\_stub} to
your own project.  Then you should have copies of the
source file \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/grade\_file\_homework\_stub/grade\_files.cs}{grade\_files.cs}
for you to \emph{complete} for this homework.
The folder also contains sample data files
including the examples discussed below.

In this assignment, we're going to begin taking steps to help you
achieve greater \emph{independence} when it comes to programming. This
means (among other things) that you will be given what is commonly
known as a specification. In software development--and in the business
world in general, it is customary to capture a set of
\emph{business requirements} in what is commonly known as a
\emph{requirements specification} document. While what you read here will be much more
concise, we want you to become familiar with requirements-driven
thinking, without which many real-world software projects fail.

After presenting the set of requirements, we will give you some hints
for how to \emph{implement} the requirements. These hints may or may not
prove completely helpful to you, and you are also invited to come up
with your own solutions. As we inch closer to the semester project,
you're going to want to use your imagination to create a good solution
to a problem.


\subsection{Brief Problem Statement}
\label{hw-gradefiles:brief-problem-statement}
The previous two homework assignments represent a great simplification
of the real-world process of grading. The notion that grade
information must be entered manually is rather tedious, not to mention
error prone. In the real world, grade information would be kept in a
file (a spreadsheet is common), from which various calculations and
summary reports could be generated.

In this assignment, the problem we are trying to solve is to take all
of the \emph{raw} grade data from one or more student files and prepare a
\emph{summary report} file with a line for each student.

Although we could do all of what we're describing here with a
\emph{spreadsheet}, the point is to show how we can use C\# to read in a
simplified form of comma-separated data, process it, and do some
general-purpose calculations on the data.


\subsection{Using C\#}
\label{hw-gradefiles:using-c}
We'll be making use of a number of C\# features (some old, some new) in
this homework:
\begin{itemize}
\item {} 
decisions, loops, strings, and functions

\item {} 
files

\item {} 
arrays

\end{itemize}


\subsection{Requirements}
\label{hw-gradefiles:requirements}\begin{enumerate}
\item {} 
Unlike in previous assignments, this program must accept data from
a collection of input files (that is, it will not be reading most of the
data from the class \code{Console}).

\item {} 
The program needs a course abbreviation from the user.  If there
is a command line argument, use it as the course abbreviation.
Make sure your code can
read a command-line argument using the special form of
\code{Main(string{[}{]} args)} already in the stub
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/grade\_file\_homework\_stub/grade\_files.cs}{grade\_files.cs}.
If the user does not provide at command line argument,
prompt the user for it once the program starts.
An example would be comp170.  All data files will include the course
abbreviation as part of their name.  We will use comp170 in the examples below,
but it could be something else.  The folder also contains sample data files
for a course abbreviation comp150.

Note that these data files are not in the Xamarin Studio execution directory, but
in the project directory, so the {\hyperref[fio:fio]{\emph{FIO Helper Class}}} is useful to provide
flexibility in reading the data files.

\item {} 
There are two master files for any course.
One is ``categories\_'' + the course abbreviation
+ ''.txt''.  For example, \code{categories\_comp170.txt} is a sample data file
provided and used below.

It will contain three lines.
The first line is a comma separated list of category names like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Exam, Lab, Homework, Project, Class Participation
\end{Verbatim}

There may be extra spaces after the commas.
Categories will be chosen so that \emph{each one starts with a different letter}.

The second line contains the integer weights for each category, like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
40, 15, 15, 20, 10
\end{Verbatim}

They do \emph{not} need to add to 100.  If the sum is called totWeights,
get the final grade by summing for each category:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{p}{(}\PYG{n}{category} \PYG{n}{weight}\PYG{p}{)}\PYG{p}{(}\PYG{n}{category} \PYG{n}{grade}\PYG{p}{)}\PYG{p}{/}\PYG{n}{totWeights}
\end{Verbatim}

The third line will contain the number of grades in each category, like

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
2, 5, 3, 1, 2
\end{Verbatim}

The second master file will be ``students\_'' + the course abbreviation + ''.txt''.
For example \code{students\_comp170.txt}.
It will contain a list of student information
records. Each record (one per input line) will have the following
structure:
\begin{quote}

Student ID, Last Name, First Name
\end{quote}

For example, the sample data file \code{students\_comp170.txt} starts:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
P12345678, Doe, John
P00000001, Hernandez, Maria
\end{Verbatim}

\item {} 
There will be a secondary file for each student,
named after the student id and the course abbreviation and ''.data''.
For example,
John's scores would be kept in a file named
\code{P12345678comp170.data}. Maria's scores would be in
\code{P00000001comp170.data}. Each record (one per file line will have the
following structure:
\begin{quote}

Category letter, Item, Points Earned
\end{quote}

where:
\begin{itemize}
\item {} 
category letter is the first letter of the category.  With the categories
given in the example above, they would be E, L, H, P, and C.

\item {} 
item is a number within that category (1, 2, 3, ...) -
only used in part of the extra credit.

\item {} 
points earned is a real number

\item {} 
the lines are in no special order.

\end{itemize}

Sample data file \code{P12345678comp170.data} starts:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
H, 1, 90
C, 1, 100
L, 3, 100
L, 2, 80
H, 2, 80
E, 1, 90
\end{Verbatim}

\item {} 
The program will process the data from each student file and
calculate the average within each category, and then the weighted overall average.
Also display the letter grade for
each student, using code derived from the previous
assignment.

\item {} 
Your program writes the final report file.
It is named with the course abbreviation
+ ``\_summary.txt''.  Example: ``comp170\_summary.txt''.
This file must have a line for each student showing the
student's last name, first name,
weighted average rounded to one decimal place, and letter grade.
File \code{comp170\_summary.txt} would start with lines:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Doe, John 78.9 C+
Hernandez, Maria 88.2 B+
\end{Verbatim}

Write this file to the same directory where you found the input data.  Again
the {\hyperref[fio:fio]{\emph{FIO Helper Class}}} is useful.

\item {} 
The rest of the test data for
course abbreviations comp170 and all the data for comp150 is
in the homework directory.
There are also sample solution files for the
summaries (including some extra credit additions at the ends of lines).
Their names end in \code{\_solution.txt} to distinguish them from the
summary files \emph{you} should generate in tests.

While your program should certainly work for course abbreviations comp170 and comp150,
it should also work in general for any data files your refer to
in the defined formats and place in the same folder.

\item {} 
Turn in materials as in the last homework, including a single copy of
the homework source files and a log.txt file for each student, in the
same form as for the last homework.

\end{enumerate}


\subsection{Hints}
\label{hw-gradefiles:hints}\begin{enumerate}
\item {} 
Read
{\hyperref[files:files]{\emph{Files, Paths, and Directories}}}.
You're still going to need ReadLine() and
WriteLine() in this assignment, the only difference is that we'll
get the input from a file instead
of the Console. The parameter syntax will be the same.

\item {} 
For each file line you'll want to use the {\hyperref[onedim:split]{\emph{String Method Split}}},
and then the \code{Trim}
method from {\hyperref[stringmethods2:more-string-methods]{\emph{More String Methods}}} on each part to
remove surrounding spaces. Then
use indexing to get the field of interest. (More below.)

\item {} 
You'll need an \emph{outer loop} to read the records from the master name
file. You'll need an \emph{inner loop} (or a loop inside of a function)
to read the records for each student.

\item {} 
When processing the records from a student file, you should process
each one separately and not assumed they are grouped in any
particular order.

This means, specifically, that your program simply reads a record,
decides what category it is in, and updates the \emph{running total} for
that category. Once the entire file has been read, you can compute
the average for each category based on the \emph{number of items} that
\emph{should} be in that category, which may be more than the number
of records in the file for items turned in.

\item {} 
There is no need to \emph{keep} a score
after you've read it and immediately used it.
\emph{Do} use an array, however, for the running total
for each category.

\item {} 
In order to deal with a varying number of categories and different
possible first letter codes, you will need to split the category
name line into an array, say

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{categories}\PYG{p}{;}
\end{Verbatim}

To know where to update data for each category, you can use this
function after you read in a code, to determine the proper index.
It is already in the stub of the solution file
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/grade\_file\_homework\_stub/grade\_files.cs}{grade\_files.cs}:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Take the first letter code for a catagory, and }
      \PYG{c+c1}{/// return the index of that category in categories.}
      \PYG{k}{static} \PYG{k+kt}{int} \PYG{n+nf}{codeIndex}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{code}\PYG{p}{,} \PYG{k+kt}{string}\PYG{p}{[}\PYG{p}{]} \PYG{n}{categories}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}
         \PYG{k}{for} \PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{p}{=} \PYG{l+m}{0}\PYG{p}{;} \PYG{n}{i} \PYG{p}{\PYGZlt{}} \PYG{n}{categories}\PYG{p}{.}\PYG{n}{Length}\PYG{p}{;} \PYG{n}{i}\PYG{p}{+}\PYG{p}{+}\PYG{p}{)} \PYG{p}{\PYGZob{}}
            \PYG{k}{if} \PYG{p}{(}\PYG{n}{categories}\PYG{p}{[}\PYG{n}{i}\PYG{p}{]}\PYG{p}{.}\PYG{n}{Trim}\PYG{p}{(}\PYG{p}{)}\PYG{p}{.}\PYG{n}{StartsWith}\PYG{p}{(}\PYG{n}{code}\PYG{p}{)}\PYG{p}{)} \PYG{p}{\PYGZob{}}
               \PYG{k}{return} \PYG{n}{i}\PYG{p}{;}
            \PYG{p}{\PYGZcb{}}
         \PYG{p}{\PYGZcb{}}
         \PYG{k}{return} \PYG{p}{\PYGZhy{}}\PYG{l+m}{1}\PYG{p}{;} \PYG{c+c1}{//required by compiler: shouldn\PYGZsq{}t reach}
      \PYG{p}{\PYGZcb{}}
\end{Verbatim}

You may assume the data is good and the -1 is never returned,
but the compiler requires this last line.

\item {} 
You cannot have one fixed formula to calculate the final weighted grade,
because you do not know the number of categories when writing the code.
You will have to accumulate parts in a loop.

\item {} 
Test thoroughly!  Be sure to test with and without command line parameter and
with multiple data sets.

\end{enumerate}


\subsection{Grading Rubric (25 points)}
\label{hw-gradefiles:grading-rubric-25-points}\begin{enumerate}
\item {} 
Get the abbreviation from the command line if it is there. \textbf{{[}2{]}}

\item {} 
Otherwise get the abbreviation from prompting the user. \textbf{{[}1{]}}

\item {} 
Read the categories file and parse lines. \textbf{{[}2{]}}

\item {} 
Deal with each student. \textbf{{[}3{]}}

\item {} 
Calculate the cumulative grades in each category, reading
a student's file once, using arrays. \textbf{{[}5{]}}

\item {} 
Calculate the overall grade and letter grade. \textbf{{[}3{]}}

\item {} 
Generate summary entries. \textbf{{[}3{]}}

\item {} 
Use functions where there would otherwise be two several-line blocks of code
differing only in the name of the data evaluated and the name of the
result generated. \textbf{{[}2{]}}

\item {} 
Use good style:  formatting, naming conventions,
meaningful names other than for simple array indices, lack of redundant code. \textbf{{[}4{]}}

\end{enumerate}

\textbf{Optional Extra Credit Opportunities!}  You may choose to do
any combination that does not include both of the last two options about missing work.
\begin{enumerate}
\item {} 
Format the summary file in nice columns.  Include the grades for each category,
rounded to one decimal place.  Include a heading line.
For example the summary for the repository example Comp150 could start:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Name: Last, First           Avg Gr     E     H     P
Hopper, Grace             100.0 A  100.0 100.0 100.0
\end{Verbatim}

You may assume the last-first name field fits in 25 columns.
Copy the first three column headings from above.
The column headings for the categories can just be their one letter code.
Names and letter grades should be left-justified (padded on the right, by
using a \emph{negative} field width).
See {\hyperref[forexamples:left-justification]{\emph{Left Justification}}}. \textbf{{[}2{]}}

\item {} 
Change the scheme for calculating letter grades to use a function that calculates
the proper grade, where the only \code{if} statement is one simple one
inside a \emph{loop}.  The \code{if} statement will have a \code{return} statement in its body,
and no \code{else}.  The loop will need to use
corresponding arrays of data for grade cutoffs and grade names. \textbf{{[}3{]}}

\item {} 
For any student who has missed passing in all the required items,
generate extra data on missing work in the summary, at the right end of the
line for the student.  Add this to
whichever version of the earlier parts you use.
Include an addendum starting with ``Missing: ''
only if there are not enough grades in one or more
categories.  For each category where
one or more grades is missing, including a count of the number of grades missing followed
by the category letter.  An example using the example categories is:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Doe, John 68.5 D+ Missing: 2 L 1 H
Smith, Chris 83.2 B Missing: 1 L
Star, Anna 91.2 A\PYGZhy{}
\end{Verbatim}

meaning Doe has 2 labs missing and 1 homework missing.  Smith is missing one lab.  Star
has done all assigned work, since nothing is added. The solution files display this
extra credit addition on the ends of lines.  \textbf{{[}3{]}}

\item {} 
This is a much harder alternate version for handling missing work:
Unlike the previous format, do not count and print the number of missing
entries in each category in a form like ``2 L ''.
Replace such an entry with a list of \emph{each} item
missing, in order, as in ``L:1, 4 '', meaning labs 1 and 4 were missing.
Assume that the expected item numbers for a category
run from 1 through the number of grades in the category.
You may assume no item number for the same category appears twice.
For example, with the sample data files given in the repository for
comp170, the summary line for John Doe would be:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Doe, John 78.9 C+ Missing: L: 1, 4 H: 3
\end{Verbatim}

The most straightforward way to do this requires something
like an array of arrays, array of lists or array of sets.
You may need to read ahead if you want to use one of these approaches. \textbf{{[}5{]}}

\end{enumerate}

\index{homework!booklist}\index{booklist homework}\index{OOP!homework}

\section{Homework: Book List}
\label{hw-booklist:index-0}\label{hw-booklist:booklist}\label{hw-booklist::doc}\label{hw-booklist:homework-book-list}
\textbf{Objectives}:
\begin{itemize}
\item {} 
Complete a simple data storing class (Book), with fields for title, author, and
year of publication.

\item {} 
Complete a class with a Collection (BookList) that uses the public methods
of another class you wrote (Book), and select various data from the list.

\item {} 
Complete a testing program (TestBookList), that creates a
BookList, adds Books to the BookList, and tests BookList
methods clearly and completely for a user looking at the output
of the program and \emph{not} the source code..

\end{itemize}

Copy stub files from the project \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/books\_homework\_stub}{books\_homework\_stub} to your own
project.
Stubs for the assignment files are
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/books\_homework\_stub/book.cs}{book.cs},
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/books\_homework\_stub/book\_list.cs}{book\_list.cs}, and
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/books\_homework\_stub/test\_book\_list.cs}{test\_book\_list.cs},

Some of the method stubs included are only to be fleshed out if you are doing
the corresponding extra credit option.  They include a comment,
just inside the method, \code{// code for extra credit}.
There are also extra files used by the extra credit portion.
They are discussed
in the Extra Credit section at the end of the assignment.

Complete the first line in each file to show your names. At the top of
the Book class include any comments about help in \emph{all} of the classes.

Create methods one at a time, and test them.  Complete \code{book.cs} first,
preferably testing along the way.  (You can write an initial version of the
testing program, so it does not depend on BookList.)  Then add methods to
\code{book\_list.cs}, and concurrently add and run tests in \code{test\_book\_list.cs}.
Testing the Book class first means that when you get to
BookList you can have more confidence that any problems you have are from the latest
part you wrote, not parts written earlier in the class Book.

Remember to have each individual submit a \textbf{log}, \code{log.txt},
in the same format as the last assignment.


\subsection{Book class}
\label{hw-booklist:book-class}
See the stub file provided. It should have instance fields for the
author, title, and year (published).

Complete the constructor:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{n+nf}{Book}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{title}\PYG{p}{,} \PYG{k+kt}{string} \PYG{n}{author}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{year}\PYG{p}{)}
\end{Verbatim}

that initializes the fields.
(Be careful, as we have discussed in class, when using the same names
for these parameters as the instance variables!)

It should have three standard (one line) getter methods:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k+kt}{string} \PYG{n+nf}{GetTitle}\PYG{p}{(}\PYG{p}{)}

\PYG{k}{public} \PYG{k+kt}{string} \PYG{n+nf}{GetAuthor}\PYG{p}{(}\PYG{p}{)}

\PYG{k}{public} \PYG{k+kt}{int} \PYG{n+nf}{GetYear}\PYG{p}{(}\PYG{p}{)}
\end{Verbatim}

and

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{k}{override} \PYG{k+kt}{string} \PYG{n+nf}{ToString}\PYG{p}{(}\PYG{p}{)}
\end{Verbatim}

\code{ToString} should return a \emph{single} string spread across three lines,
with no newline at the end.
For example if the \code{Book} fields were
``C\# Yellow Book'', ``Rob Miles'', and 2011, the string should appear,
when printed, as

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
Title: C\PYGZsh{} Yellow Book
Author: Rob Miles
Year: 2011
\end{Verbatim}

The \code{override} in the heading is important so the compiler knows that this
is the official method for the system to used implicitly to convert the object
to a string.

Remember the use of @ with multi-line string literals.


\subsection{BookList class}
\label{hw-booklist:booklist-class}
It has just one instance variable, already declared:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{private} \PYG{n}{List}\PYG{p}{\PYGZlt{}}\PYG{n}{Book}\PYG{p}{\PYGZgt{}} \PYG{n}{list}\PYG{p}{;}
\end{Verbatim}

It has a constructor (already written - creating an empty List):

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{k}{public} \PYG{n+nf}{BookList}\PYG{p}{(}\PYG{p}{)}
\end{Verbatim}

It should have public methods:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{// Add book to the list.}
      \PYG{c+c1}{// The regular assignment version always returns true. }
      \PYG{k}{public} \PYG{k+kt}{bool} \PYG{n+nf}{Addbook}\PYG{p}{(}\PYG{n}{Book} \PYG{n}{book}\PYG{p}{)}
\end{Verbatim}

The regular version should just leave the final \code{return true;}
The extra credit version is more elaborate.

Further methods:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// List the full descriptions of each book,}
      \PYG{c+c1}{/// with each book separated by a blank line. }
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{PrintList}\PYG{p}{(}\PYG{p}{)} \PYG{c+c1}{// }
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{// List the titles (only!), one per line, of each book }
      \PYG{c+c1}{// in the list that is by the specified author. }
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{PrintTitlesByAuthor}\PYG{p}{(}\PYG{k+kt}{string} \PYG{n}{author}\PYG{p}{)}
\end{Verbatim}

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
     \PYG{c+c1}{// List the full descriptions of each book printed}
      \PYG{c+c1}{// in the range of years specified,}
      \PYG{c+c1}{// with each book separated by a blank line. }
      \PYG{k}{public} \PYG{k}{void} \PYG{n+nf}{PrintBooksInYears}\PYG{p}{(}\PYG{k+kt}{int} \PYG{n}{firstYear}\PYG{p}{,} \PYG{k+kt}{int} \PYG{n}{lastYear}\PYG{p}{)}
\end{Verbatim}

For instance if the list included books published in 1807, 1983, 2004,
1948, 1990, and 2001, the statement

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{PrintBooksInYears}\PYG{p}{(}\PYG{l+m}{1}\PYG{l+m}{9}\PYG{l+m}{4}\PYG{l+m}{0}\PYG{p}{,} \PYG{l+m}{1}\PYG{l+m}{9}\PYG{l+m}{9}\PYG{l+m}{0}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

would list the books from 1983, 1948, and 1990.


\subsection{TestBookList class}
\label{hw-booklist:testbooklist-class}
It should have a \code{Main} program that creates a BookList, adds some books
to it (more than in the skeleton!), and convincingly displays tests of
each of BookList's methods that exercise all paths through your code.
Check for one-off errors in PrintBookYears. With all the methods that
print something, the results are easy to see. \emph{Do print a label}, as in
the skeleton, before printing output from each method test, so that the
user of the program can see the correctness of the test
\emph{without any knowledge of the source code}!


\subsection{Grading Rubric}
\label{hw-booklist:grading-rubric}
Book class
\begin{itemize}
\item {} 
{[}1 point{]} public Book(string title, string author, int year)

\item {} 
{[}1{]} public string GetTitle()

\item {} 
{[}1{]} public string GetAuthor()

\item {} 
{[}1{]} public int GetYear()

\item {} 
{[}2{]} public override string ToString()

\end{itemize}

BookList class
\begin{itemize}
\item {} 
{[}2{]} public bool AddBook(Book book)

\item {} 
{[}2{]} public void PrintList()

\item {} 
{[}2{]} public void PrintTitlesByAuthor(string author)

\item {} 
{[}2{]} public void PrintBooksInYears(int firstYear, int lastYear)

\end{itemize}

TestBookList
\begin{itemize}
\item {} 
{[}2{]} Supply data to screen indicating what test is being done with what
data and what results, so it is clear that each test works without
looking at the source code.

\item {} 
{[}5{]} Convincingly display tests of each of BookList's methods that
exercise all paths through your code.

\end{itemize}

Overall:
\begin{itemize}
\item {} 
{[}4{]} Make your code easy to read - follow indenting standards, use
reasonable identifier names....  Do not duplicate code when
you could call a method already written.

\end{itemize}


\subsection{Extra Credit}
\label{hw-booklist:extra-credit}
You may do any of the numbered options, except that the last one
requires you to do the previous one first.

To get full credit for any particular option, tests for it must be
\emph{fully integrated} into TestBookList!
\begin{enumerate}
\item {} 
{[}2 points{]} Complete

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Return a single string containing the same data as }
      \PYG{c+c1}{/// printed by PrintList, including a final newline.}
      \PYG{k}{public} \PYG{k}{override} \PYG{k+kt}{string} \PYG{n+nf}{ToString}\PYG{p}{(}\PYG{p}{)}
\end{Verbatim}

Also \emph{change} the \code{PrintList} method body to the one line:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Console}\PYG{p}{.}\PYG{n}{Write}\PYG{p}{(}\PYG{k}{this}\PYG{p}{)}\PYG{p}{;}
\end{Verbatim}

(The \code{Write} and \code{WriteLine} methods print objects by using their
\code{ToString} methods.)

Be sure to make this addition to TestBookList:
Test the \code{ToString} method by converting the
resulting BookList description string to upper case before printing it
(which should produce a different result than the regular mixed case of
the \code{PrintList} method test).

\item {} 
{[}4 points{]}

In the Book class, a new constructor:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{/// Construct a Book, taking data from reader.}
      \PYG{c+c1}{/// Read through three lines that contain the}
      \PYG{c+c1}{/// title, author, and year of publication, respectively.}
      \PYG{c+c1}{/// There may be an extra blank line at the beginning.}
      \PYG{c+c1}{/// If so ignore it.}
      \PYG{c+c1}{/// Nothing beyond the line with the year is read. }
      \PYG{k}{public} \PYG{n+nf}{Book}\PYG{p}{(}\PYG{n}{StreamReader} \PYG{n}{reader}\PYG{p}{)}
\end{Verbatim}

In class BookList, a new constructor:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{// Construct a new BookList using Book data read from}
      \PYG{c+c1}{// reader.  The data coming from reader will contain groups}
      \PYG{c+c1}{// of three line descriptions useful for the Book constructor}
      \PYG{c+c1}{// that reads from a stream.  Each three\PYGZhy{}line book description}
      \PYG{c+c1}{// *may or may not* be preceded by an empty line. }
      \PYG{k}{public} \PYG{n+nf}{BookList}\PYG{p}{(}\PYG{n}{StreamReader} \PYG{n}{reader}\PYG{p}{)}
\end{Verbatim}

For testing we included special files in the right format:
\href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/books\_homework\_stub/books.txt}{books\_homework\_stub/books.txt} and \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/books\_homework\_stub/morebooks.txt}{books\_homework\_stub/morebooks.txt}.

You will also want to include a reference to \href{https://github.com/LoyolaChicagoBooks/introcs-csharp-examples/blob/master/fio/fio.cs}{fio/fio.cs}, so the text files are
easy to find.

\item {} 
{[}4 points{]}

In class Book:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
     \PYG{c+c1}{// Return true if all the corresponding fields in this Book}
      \PYG{c+c1}{// and in aBook are equal.  Return false otherwise.  }
      \PYG{k}{public} \PYG{k+kt}{bool} \PYG{n+nf}{IsEqual}\PYG{p}{(}\PYG{n}{Book} \PYG{n}{aBook}\PYG{p}{)}
      \PYG{p}{\PYGZob{}}\PYG{c+c1}{// code for extra credit}

         \PYG{k}{return} \PYG{k}{true}\PYG{p}{;} \PYG{c+c1}{//so skeleton compiles}
      \PYG{p}{\PYGZcb{}}
   \PYG{p}{\PYGZcb{}}
\PYG{p}{\PYGZcb{}}
\end{Verbatim}

It is essential to have the \code{IsEqual} method working in Book before any of
the new code in BookList, which all depends on the definition of \code{IsEqual}
for a Book.

NOTE: We chose the name \code{IsEqual} to distinguish it from the
more general \code{Equals} override that you could write.
The \code{Equals} override allows for a parameter of any object type. With
skills from Comp 271 you you be able to write the \code{Equals} override.

In class BookList:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{// Test if aBook is contained in this BookList.}
      \PYG{c+c1}{// Return true if book IsEqual to a Book in the list,}
      \PYG{c+c1}{// false otherwise. }
      \PYG{k}{public} \PYG{k+kt}{bool} \PYG{n+nf}{Contains}\PYG{p}{(}\PYG{n}{Book} \PYG{n}{book}\PYG{p}{)}
\end{Verbatim}

Caution: Do NOT try to use the \code{List} method \code{Contains}: Because we
did \emph{not} override the \code{Equals} method to specialize it for Books, the \code{List}
method \code{Contains} will \emph{fail}. You need to do a litle bit more
work and write your own version with a loop.

Change the \code{AddBook} method from the regular assignment, so it
satisfies this documentation:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
     
     \PYG{c+c1}{/// Adds aBook to the list if aBook is}
     \PYG{c+c1}{/// not already in the list.}
     \PYG{c+c1}{/// Return true if aBook is added,}
     \PYG{c+c1}{/// and false if it was already in the list. }
\end{Verbatim}

In TestBookList you need to react to the return value, too.

\item {} 
{[}2 points{]} This one requires the previous elaboration of \code{AddBook}.
In BookList:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
      \PYG{c+c1}{// Add each Book in books to this BookList.}
      \PYG{c+c1}{// if it is not already contained in this BookList.}
      \PYG{c+c1}{// Return true if the current list was changed.}
      \PYG{c+c1}{// Return false if each Book in books is a}
      \PYG{c+c1}{// duplicate of a Book in the current list. }
      \PYG{k}{public} \PYG{k+kt}{bool} \PYG{n+nf}{AddAll}\PYG{p}{(}\PYG{n}{BookList} \PYG{n}{books}\PYG{p}{)}
\end{Verbatim}

You might want to code it first without worrying about the correct
return value; then do the complete version. There are multiple
approach to determining the return value, some much easier than
others!

To fully test in TestBookList, you need to react to the return value, too.

\end{enumerate}


\section{Group Project}
\label{project:group-project}\label{project::doc}\label{project:id1}

\subsection{Objectives}
\label{project:objectives}\begin{itemize}
\item {} 
Being creative, imagining and describing a program, and working it
through to completion

\item {} 
Working in a team:
\begin{itemize}
\item {} 
Communicating to each other

\item {} 
Dividing responsibilities

\item {} 
Helping each other

\item {} 
Finding consensus

\item {} 
Dealing with conflict

\item {} 
Providing process feedback

\item {} 
Integrating parts created by several people

\end{itemize}

\item {} 
Developing new classes to fit your needs

\item {} 
Using the .Net API library

\item {} 
Designing a program for refinement

\item {} 
Testing

\item {} 
Evolving a program

\item {} 
Creating documentation for user and implementers

\item {} 
Programming in the large -- not a small predefined problem

\item {} 
Make something that is fun

\end{itemize}

See the project \code{csproject\_stub}, already discussed in class.

\textbf{What to turn in:}
\begin{itemize}
\item {} 
Periodic reports

\item {} 
intermediate implementation

\item {} 
a final presentation

\item {} 
a final implementation
including user and programmer documentation and process documentation

\item {} 
individual evaluations

\end{itemize}


\subsection{Overview}
\label{project:overview}
You will be assigned to groups of 3-4 people to work on a project that
will extend until the end of the semester, with only a little other work
introduced in class, and of course your last exam. This leaves a month
of course time (in a regular semester)
for the project (classes, labs, dedicated homework time),
ending with presentations in final exam period. Your group will be
designing and implementing a project of your choosing.  You could
choose to make a text based game, starting from our game skeleton or not,
or something completely different, started from scratch.
The project should have some clear focus or aim,
For instance a game should be able to be won.

Start by brainstorming and listing ideas -- do not criticize ideas at
this point. That is what is meant by brainstorming - having your internal critic
going inhibits creativity. After you have a large list from
brainstorming, it is time to think more practically and settle on one
basic situation, and think of a considerable list of features you would
like it to have. Order the features, considering importance, apparent ease of
development, and what depends on what else. Get something simple
working, and then add a few features at a time, testing the pieces added
and the whole project so far. Test, debug, and make sure the program
works completely before using your past experience to decide what to add
next. This may different than what you imagined before the work on your
first stage! Like the provided project, early stages do not need
to be full featured, but make sure that you are building up to a version
with an aim, and which includes interesting features. You should
end with a program that has enough instructions provided for the user, so
someone who knows \emph{nothing} of your implementation process or intentions
can use the program successfully. Your implementation should also be
documented, imagining that a new team of programmers is about to take
over after your departure, looking to create yet another version.


\subsection{Your Team}
\label{project:your-team}
Your instructor will tell you about team makeup.

There are a number of roles
that must be filled by team members. Some will be shared between all
members, like coder, but for each role there should be a lead person who
makes sure all the contributions come together. Each person will have
more than one role. All members are expected to pull their own weight,
though not all in exactly the same roles. Everyone should make sustained
contributions, every week, documented in the weekly reports. Understand
that this project will be the major course commitment for the rest of
the semester.  These roles vary from rather small to central.
Not all are important immediately.


\subsection{Roles}
\label{project:roles}\begin{enumerate}
\item {} 
Leader: Makes sure the team is coordinated, encourage consensus on
the overall plan, oversee that the agreements are carried through, be
available as contact person for the team and the TA and your instructor.

\item {} 
Lead programmer: Keep track of different people's parts to make sure
they fit together.

\item {} 
Coder/unit tester: \emph{Everyone} must have a significant but not
necessarily equal part in this job. Each person should have primary
responsibility for one or more cohesive substantive units, and code
and test and be particularly familiar with those parts. Do your best
to make individual parts be cohesive and loosely coupled with other
people's work, to save a lot of pain in the testing and debugging
phase. When coding you are still encouraged to do pair programming,
though what pair from the team is working together at different times
may be fluid. The lead programmer might be involved in pairs more
often than others, but be sure the other coders get to drive often.

\item {} 
Librarian/version coordinator: The default should be for you to have a
box.com folder shared with your whole team and me and your TA, with all
as editors.  Your folder should have the name of your team.
You should always have a folder that contains the latest working version
of the project.  You should also keep old versions, for instance copied into
numbered version folders.
Box does not handle successive versions automatically.
You can choose
to use the more capable professional combination of
Bitbucket and {\hyperref[hgteamwork:hg-and-teamwork]{\emph{Mercurial and Teamwork}}}.
The latter will have a learning curve, and in that case this person
should be the best informed on Mercurial, and help
the other team members.

\item {} 
Report coordinator: Gather the contributions for reports from team
members and make sure the whole reports get to posted on schedule.
Your instructor needs
a clear idea of the contributions of each member each week. If a team
member is not clear on this to the report writer,
\emph{the report writer needs to be insistent}.

\item {} 
Instruction coordinator: Make sure there are clear written documents
and help within the program for the user, who you assume is not a
C\# programmer and knows nothing about your program at the start.

\item {} 
Documentation coordinator: Make sure the documentation
is clear for method users/consumers.
This includes the documentation for programmers
before the headings of methods and classes.
This is for any time someone wants to use (not rewrite) a class or
method you wrote.
Also have implementer documentation, for someone who will
want to modify or debug your code and needs to understand the
details of your internal implementations.  The extent of this
can be greatly minimized by good naming.

\item {} 
Quality manager: Take charge of integrated tests of the whole program
(following coder's unit tests). Make sure deficiencies are addressed.

\end{enumerate}

Conflict resolution: You will certainly have disagreements and possibly
conflicts. Try to resolve them within the team. When that is not
working, anyone can go to the instructor with a problem.  Do not delay
coming to me if things are clearly not working with the team.


\subsection{The process}
\label{project:the-process}
Initial:
\begin{enumerate}
\item {} 
Agree on roles. These roles can change if necessary, but you are
encouraged to stick with them for simplicity and consistency.

\item {} 
Agree on a team name and a short no-space abbreviation if necessary,
and let me know it.

\item {} 
Brainstorm about the project. Distill the ideas into a direction and
overall goals.

\end{enumerate}

On individual versions (Two formal versions will be required):
\begin{enumerate}
\item {} 
Break out specific goals for the version. How are you heading for
your overall goals? Are you biting off a significant and manageable
amount? You are expected to check in with me on this part and 2 and 3
before moving very far. This will be new for most of you.

\item {} 
Plan and organize the necessary parts and the interfaces between the
parts.

\item {} 
Write the interface documentation for consumers of the code
for the parts you plan to write.
Agree on them. You need to do this eventually anyway. Agreement up
front can save you an enormous amount of time! Do not let the gung-ho
hackers take off before you agree on documented interfaces.
We have seen it happen:  If you do not put your foot down,
you are stuck with a bad plan that will complicate things.  Otherwise lots
of code needs to be rethought and rewritten.

\item {} 
If more than one person is working on the same class, plan the names,
meanings, and restrictions on the private instance variables -- all
coders should be assuming the same things about the instance
variables! Also agree on documentation for any private helping methods you
share.

\item {} 
Code to match the agreed consumer interface and class implementation
designs.

\item {} 
Check each other's code.

\item {} 
Do unit tests on your own work, and fix them and test again...

\item {} 
Do overall tests of everything together, and fix and test again...

\item {} 
Look back at what you did, how it went, what you could do better, and
what to change in your process for the next version.

\end{enumerate}

You are strongly encouraged to follow modern programming practice which
involves splitting each of these formal versions into much smaller steps
that can be completed and tested following a similar process. Order
pieces so you only need to code a little bit more before testing and
combining with pieces that already work. This is enormously helpful in
isolating bugs! This is really important. If you thought you spent a
long while fighting bugs in your small homework assignment, that is
nothing compared to the time you can spend with a large project,
particularly if you make a lot of haphazard changes all at once.


\subsection{Splitting Up The Coding}
\label{project:splitting-up-the-coding}
Make good use of the
separation of public interface and detailed implementation.
If your project has loosely coupled class, the main part of the
public interface should be limited and easy to comprehend.

Ideally have one individual
(or pair) assigned a whole class. One useful feature for allowing
compiling is to first generate a stub file like we have given you for
homework, that includes the public interface documentation,
headings, and dummy return values
and compiles but does nothing.
\emph{Post this under a box folder for the current version number.}
You will then provide your team members
with something that tells them what they can use and allows them to
compile their own part. Then later substitute more functional classes.

Your instructor and you will want to review your code. We do not want to have to
reread almost the same thing over and over: Use the editor copy command
with extreme caution. If you are considering making an exact copy,
clearly use a common method instead. If you copy and then make
substitutions in the same places, you are likely better off
with a method with the common parts and with parameters inserted where there
are differences.  You can make a quick test with a
couple of copied portions, but then
\emph{convert to using a method with parameters for the substitutions}.
Besides being a waste of effort to define seven methods each
defining a tool, with just a few strings differing from one method to
the next, we will require you to rewrite it, with one method with
parameters, and just seven different calls to the method with different
parameters. Save yourself trouble and do it that way the first time, or
at least after you code a second method and see how much it is like the
first one you coded....

If you are making many substitutions
of static textual data, put the data into a resource file in a variation
of the Fake Advise Lab.

You only want to commit working code into the shared current version folder.
Comment out incomplete additions that you want to show to everyone,
or comment out the call to a method that compiles but does not yet
function logically.  An alternative is to have a separate folder for
in-process code to share for comment,
so you will not try to compile it with the current working version.


\subsection{Weekly reports}
\label{project:weekly-reports}
Reports are due from the report writer each Tuesday.
\begin{enumerate}
\item {} 
Inside your team's box folder have a subfolder called WeeklyReports.
A sample stub form to fill out on the computer is in
\href{http://anh.cs.luc.edu/170/examples/Weekly-Report.rtf}{Weekly-Report.rtf}.
Make the name of each weekly
report document be the date it was due, like Mar26.rtf.
It is easy
to copy the table from this week to last week and edit it to show
how much your plans matched reality.
You should post a version for your team to look at first.  Please distinguish
drafts from the final version for me to look at.   You might have a separate
folder Drafts, and move the report into the WeeklyReport folder when
it is final. Box easily allows moving files, but not renaming them.

\item {} 
Only one report should be generated each week, with the person in the role of
report writer making sure a complete version is produced and placed in the
WeeklyReport folder.

\item {} 
Under plans for the next week, include concrete tasks planned to be
completed, and who will do them, with an informative
explanation.  The content and depth of the person's work should be clear.
If you can state that clearly and be brief, great.
The tasks do not only include coding: they can be any of the
parts listed above, and for any particular part of the project, where
that makes sense.  \emph{If individuals cannot state clearly what they are working on,}
\emph{then the team leader and lead coder have a significant issue in their leadership}
\emph{that needs to be addressed.}

\item {} 
In the review of the last week (after the first week) include the
last week's plans and what actually happened, task by task,
concretely, with enough detail to give an idea on the magnitude
of the work. This can include the portion completed and/or changes in
the plans and their reasons. ``Still working on X'' is not useful: Who
was doing what? What methods, doing what, were completed? Which are
in process? Which are being debugged? What part remains to be done,
and who is it assigned to? The report writer is responsible to get a
clear statement from each team member.

\end{enumerate}


\subsection{Intermediate deliverables}
\label{project:intermediate-deliverables}
These materials should be placed in a subfolder \textbf{Intermediate}
of your team project folder.
See the due date in the schedule.
\begin{itemize}
\item {} 
Copy the linked stub of
\href{http://anh.cs.luc.edu/170/examples/projectPlans.rtf}{projectPlans.rtf} document.
Then complete it:
\begin{itemize}
\item {} 
List the project roles again, and who ended up filling them. For
coding, say who was the person primarily responsible for each
part.

\item {} 
If you used old classes, like those from the skeleton project or a lab or
somewhere else, say which ones are included \emph{unchanged} or give a
summary of changes.

\item {} 
If your documentation of methods is not generally done,
say what classes got clear documentation (or individual methods if only
some were done).

\item {} 
Where are you planning to go from here, and who you envision being
primarily responsible for different parts?

\end{itemize}

\item {} 
Include parts 2-4 listed below under Final Deliverables, but for an
intermediate version that runs, and does \emph{not} need to have the goal
working yet. Have documentation of your methods, including summary description
and description of parameters and return values.
If for some reason you do not have all the documentation that you were encouraged
to write \emph{first}, at least be sure to have and point out significant examples of your
clear documentation of purpose, parameters, and return values.
This allows instructor feedback
for completing the rest.

\item {} 
The idea is to have everyone get an idea of what is expected, so we
have no misunderstandings about the final version. We will give you
feedback from this version to incorporate in the final version. We do
not want to have to say anyone did anything ``wrong'' on the final
version. We want to be able to concentrate on your creative
accomplishments.

\item {} 
Look through the list of deliverables again and make sure your collection is complete.

\end{itemize}


\subsection{Final Deliverables}
\label{project:final-deliverables}
\textbf{Group Submission}:

One submission of the group work is due one hour before the final presentations.
\begin{enumerate}
\item {} 
All files listed in parts 2-5.
Also include a zip file, named with your team abbreviation,
containing a Windows executable with (a separate copy of) any other
image and data files needed.  Test to make sure you can
unzip and run the executable.
The final submissions will be accessible to the whole class
-- so we can all play them!

\item {} 
Source code. You can name the classes appropriately
for the content of your game.

\item {} 
User instructions. These should be partly built into the program. The
most extensive documentation may be in a document file separate from
the program, if you like. (Plain text, MS Word, Rich text (rtf), or
PDF, please.) The starting message built into the beginning of the
game should mention the file name of such external documentation, if
you have it.

\item {} 
Programmer documentation. Document the public interface for all
methods in comments directly before the method heading.
Add implementation comments
embedded in the code where they add clarity (not just verbosity). You
may have a separate overview document.  Include ``Overview'' in the
file name

\item {} 
Overall project and process review in a document named like the linked stub,
\href{http://anh.cs.luc.edu/170/examples/projectReview.rtf}{projectReview.rtf}.
\begin{itemize}
\item {} 
The first section should be Changes. So the instructor does not
duplicate effort, please give an overview of the changes from the
intermediate version. What classes are the same? What features
were added? What classes are new? Which classes or methods were
given major rewrites? What classes had only a few changes? (In
this case try to list what to look for.)

\item {} 
List again the roles, and who filled them. For coding, say who was
the person primarily responsible for each part.

\item {} 
What did you learn? What were the biggest challenges? What would
you do differently the next time? What are you most proud of?

\item {} 
How could we administer this project better? What particularly
worked about the structure we set up?

\end{itemize}

\item {} 
A 10-15 minute presentation of your work to the class in final exam
period. What would you want to hear about other projects? (Say it
about yours.) What was the overall idea? What was the overall
organization? What did you learn that was beyond the regular class
topics that others might find useful to know? What were your biggest
challenges? Do not show off all your code just because it is there.
Show specific bits that gave you trouble or otherwise are
instructive, if you like.

\end{enumerate}

Look through the list of deliverables again, before sending files,
and check with the whole team to make sure your collection is complete.

\textbf{Your Assessment of Individuals in the Group}:

This is due electronically 10 minutes after the final class presentation period,
from each team member, \emph{independently}, turned in a manner specified by your
instructor, like other homework assignments.

Change the name of the linked stub file
\href{http://anh.cs.luc.edu/170/examples/Indiv-Mem-Assessment.rtf}{Indiv-Mem-Assessment.rtf}
to your
teamAbbreviation-yourName.rtf.
You may want to tweak it after the
group presentation, but have it essentially done beforehand.

Writing this is NOT a part of your
collective group deliberations. It is individual in two senses: both
in being about individual team members and in being the view of \emph{one}
individual, you. For this document only, everyone should be writing
separately, privately, and independently from individual experience.
If you lack data on some point, say so, rather than using what others are saying.

\index{labs!hg and version control}\index{version control lab}\index{hg}

\section{Lab: Version Control}
\label{lab-versioncontrol:lab-version-control}\label{lab-versioncontrol:index-0}\label{lab-versioncontrol::doc}\label{lab-versioncontrol:lab-versioncontrol}
Modern software development requires an early introduction source code
management, also known as version control. While source code
management is frequently touted as being beneficial to a \emph{project
team}, it is also of great value for \emph{individuals} and provides a
clear mechanism for tracking, preserving, and sharing your work.

In addition, it simplifies the process of demonstrating and submitting
your work to your instructor (and graduate assistants). Long gone are
the days of carrying stuff around on USB drives and sending e-mail
attachments.

There are numerous options for version control. In the free/open
source community, a number of solutions have emerged, including some
old (CVS, Subversion) and some new (Mercurial, Git, and Bazaar). We're
particularly fond of the Mercurial system. A key reason for our choice
is that there is an excellent cloud-based solution to host your
projects known as Bitbucket (\href{http://bitbucket.org}{http://bitbucket.org}).

Mercurial is set up for our labs.  You can install it for your
personal machine from \href{http://mercurial.selenic.com/downloads/}{http://mercurial.selenic.com/downloads/} .

There are other similar solutions to Bitbucket but none at present
provides a completely \emph{free} solution for hosting \emph{private}
repositories, which allow you to keep your work \emph{secret} from others.

The basic idea is to keep a main current copy of a project at a place
like bitbucket.  Anywhere that you work, you can download a copy of the
central version.  You can add and change files.  There are several
layers insulating changes to local files from changes to the
central repository:
\begin{itemize}
\item {} 
You must explicitly \emph{add} any new file names you want the repository to track.

\item {} 
Even on a tracked file, you must \emph{commit} changes to the local repository.

\item {} 
For the committed changes to get to the central repository, you must \emph{push} them.

\item {} 
You have control over what files get ignored.

\end{itemize}

Later, when you want the latest changes to the central repository to get to your
site, you need to \emph{pull} data from the central repository, and then explicitly
\emph{update} your local repository, to incorporate the new data from the central
repository.


\subsection{Goals}
\label{lab-versioncontrol:goals}
In this lab, we're going to learn:
\begin{enumerate}
\item {} 
How to create a source code repository.

\item {} 
How to add files and folders to a repository and track them.

\item {} 
How to make sure certain files and folders are not kept in the repository.

\item {} 
How to push your changes to a remote repository (at Bitbucket.org).

\item {} 
How to do your work at home and in the lab.

\item {} 
How to get our book, examples, and projects (now that that you know how
to use Mercurial).

\end{enumerate}


\subsubsection{Before We Proceed}
\label{lab-versioncontrol:before-we-proceed}
You should know that this lab is designed to be repeated as many times
as needed. You can create as many repositories as you wish, subject to
the limitations at Bitbucket.org, and may want to create different
repositories for different needs (one for yourself, one for you and
your partner in pair programming, etc.) This lab assumes you are
starting with a repository for your own work. We'll include a step for
how to add a \emph{collaborator} to the project.

Future labs will talk about additional things you need to know when it comes
to collaboration, so please view this lab as a \emph{beginning} aimed at helping
you to start using version control right away for your own projects.


\subsection{Steps}
\label{lab-versioncontrol:steps}
\index{bitbucket.org}

\subsubsection{Create Bitbucket.org account}
\label{lab-versioncontrol:create-bitbucket-org-account}\label{lab-versioncontrol:index-1}
We're going to begin by creating a remote repository for our work. The
advantage of doing so is that we get a \emph{hosted} repository that we can
use to push/pull our work. (Unlike a dangerous stunt, you \emph{want} to be able
to try this at home, too!)

Signing up for a repository at \href{http://bitbucket.org}{http://bitbucket.org} is easy. From the
landing page, just click on the option for the \emph{Free Plan}. This allows
you to create any number of public/private repositories with support
for up to 5 users. This is all you'll need for your work in this course.

Once you've created your account (and confirmed it, if required) you
are good to go for the rest of this lab!


\subsubsection{Create repository at Bitbucket}
\label{lab-versioncontrol:create-repository-at-bitbucket}
Now we'll create a first repository at Bitbucket.org.

Go to \code{Repositories -\textgreater{} Create Repository} (the option is at the bottom
of the list of menu options). You'll see this screen:

{\hfill\includegraphics[height=300pt]{hgcreaterepository.png}\hfill}

You'll need to fill in or select the following options:
\begin{itemize}
\item {} 
Name: A short name for your project. You are encouraged to keep this
simple.  If you are using this for all of your work in COMP 170
(which is fine) you might name the repository after your
initials. So if your name is Linus Torvalds, you could give a short
name like \emph{LinusTorvaldsCOMP170} or \emph{LTCOMP170}.

\item {} 
Repository Type: Select Mercurial. Yes, we realize that Xamarin Studio
supports Git natively, but for the reasons mentioned earlier, we
have chosen Mercurial. We will allow you to use Git on your own if
you can figure it out and use it properly. But this lab assumes
Mercurial.

\item {} 
Language: You can select anything you like here. We do C\# for the
most part in this class, so we recommend that you select it.

\item {} 
Description: You can give any description you like. If you are
working with a partner please list both you and your partner's name
in the description.

\item {} 
Web Site: Optional

\item {} 
Private checkbox should be checked.

\end{itemize}

So just go ahead and create your first repository. You can always
create more of them later.

Here is an example of a filled out form:

{\hfill\includegraphics[height=300pt]{hgcreaterepository2.png}\hfill}


\subsubsection{Set up your Mercurial commit username}
\label{lab-versioncontrol:set-up-your-mercurial-commit-username}
If you in a place where you have a permanent home directory,
like on your machine or in the Linux Lab,
create a file named \code{.hgrc} in \emph{your home directory}. Your home directory is
where you are dumped when you open a DOS or Linux/OS X terminal.  This is \emph{not}
inside your repository.
This file must contain the following lines, with the part after the equal sign
personalized for you:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n+na}{[ui]}
\PYG{n}{username} \PYG{p}{=} \PYG{n}{John} \PYG{n}{Doe} \PYG{p}{\PYGZlt{}}\PYG{n}{johndoe}\PYG{n}{@johndoe}\PYG{p}{.}\PYG{n}{com}\PYG{p}{\PYGZgt{}}
\end{Verbatim}

It is a convention to give a name and email address, though
it does not need to match the email address you gave when
signing up for bitbucket.

Creating this file saves you the trouble of having to pass the \code{-u username}
option to \code{hg} each time you do a \emph{commit} operation.

You can put this file in your home directory in Windows labs, but it disappears.
You might want to keep an extra copy in your repository, and copy it to the Windows
home folder when in the lab.

As a gentle reminder, your home directory on Windows can be a bit difficult to find.
The easiest way is to use your editor to locate your home folder.
When in the DOS prompt, you will also see the path to your directory as part of the prompt.
For example, on Windows 7, you will see \code{C:\textbackslash{}Users\textbackslash{}johndoe}.

\begin{notice}{warning}{Warning:}
To ensure that you did this step correctly, please open a \emph{new} terminal or DOS
window at this time and use the \code{ls} or \code{dir} command to verify that the \code{.hgrc}
file is indeed present in your home directory. If it is in any other folder, Mercurial
(the \textbf{hg} command) will not be able to find it--and you will receive an error.
\end{notice}


\subsubsection{Clone a repository from Bitbucket}
\label{lab-versioncontrol:clone-a-repository-from-bitbucket}
Open a terminal or DOS command shell.

On Windows, the Mono shell is not appropriate. You can get a regular DOS
command shell by clicking the start menu and typing \code{cmd} and into the text box
at the bottom of the start menu, and pressing return.

In the terminal/DOS-shell navigate with to the the directory
where you want to place the repository
as a sub-directory.  This could be your home directory on your machine or
a flash drive in a lab.

\textbf{Windows only}:
To navigate in a DOS-Shell to a flash drive, you need to enter the short command:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{E}\PYG{p}{:}
\end{Verbatim}

or possible another drive letter followed by a colon.
DOS drive letters are annoying because they be different another time with different
resources loaded.  Once you see the proper drive displayed, \code{cd} to the desired
directory.

If all has gone well at bitbucket, you should be able to look at your
bitbucket site and see your new repository on the
list of repositories .

For example, the co-author's new repository, \code{gkt170}, shows up on
the list of repositories (the dropdown) as \code{gkthiruvathukal/gkt170}.

So you can now go ahead by selecting this newly created repository
from the list of repositories.  If all goes well, you should see the
following screen:

{\hfill\includegraphics[height=300pt]{hgrepositorysummary.png}\hfill}

Somewhere on this screen, you should see this text:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{Clone} \PYG{k}{this} \PYG{n+nf}{repository} \PYG{p}{(}\PYG{n}{size}\PYG{p}{:} \PYG{l+m}{5}\PYG{l+m}{4}\PYG{l+m}{6} \PYG{n}{bytes}\PYG{p}{)}\PYG{p}{:} \PYG{n}{HTTPS} \PYG{p}{/} \PYG{n}{SSH}
\PYG{n}{hg} \PYG{n}{clone} \PYG{n}{https}\PYG{p}{:}\PYG{c+c1}{//yourusername@bitbucket.org/yourusername/yourrepository}
\end{Verbatim}

Copy the command you see in the browser starting \code{hg clone}, and paste it in
as a command in your terminal/DOS-shell window.

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{hg} \PYG{n}{clone} \PYG{n}{https}\PYG{p}{:}\PYG{c+c1}{//gkthiruvathukal@bitbucket.org/gkthiruvathukal/gkt170}
\end{Verbatim}

You will see some output:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{http} \PYG{n}{authorization} \PYG{n}{required}
\PYG{n}{realm}\PYG{p}{:} \PYG{n}{Bitbucket}\PYG{p}{.}\PYG{n}{org} \PYG{n}{HTTP}
\PYG{n}{user}\PYG{p}{:} \PYG{n}{gkthiruvathukal}
\PYG{n}{password}\PYG{p}{:}
\PYG{n}{destination} \PYG{n}{directory}\PYG{p}{:} \PYG{n}{gkt170}
\PYG{n}{no} \PYG{n}{changes} \PYG{n}{found}
\PYG{n}{updating} \PYG{n}{to} \PYG{n}{branch} \PYG{k}{default}
\PYG{l+m}{0} \PYG{n}{files} \PYG{n}{updated}\PYG{p}{,} \PYG{l+m}{0} \PYG{n}{files} \PYG{n}{merged}\PYG{p}{,} \PYG{l+m}{0} \PYG{n}{files} \PYG{n}{removed}\PYG{p}{,} \PYG{l+m}{0} \PYG{n}{files} \PYG{n}{unresolved}
\end{Verbatim}

You have created a copy of the (empty) bitbucket repository in a
subdirectory named the same as yourrepository (gkt170 in the example).
The is the ``checkout directory'', the top level of your copy.

Again, because the repository at Bitbucket is presently empty, the
above output actually makes sense. There are no files to be
updated. We'll learn more about what this output means later. It is
possible to get \emph{unresolved} files when you make changes that
introduce conflicts. We're going to do whatever we can to avoid these
for the small projects in our course work. However, when working in
teams, it will become especially important that you and your
teammate(s) are careful to communicate changes you are making,
especially when changing the same files in a project.

\begin{notice}{warning}{Warning:}
A version control system doesn't replace the need for human communication and being
organized.
\end{notice}


\subsubsection{Add an .hgignore and Hello World file to your project}
\label{lab-versioncontrol:add-an-hgignore-and-hello-world-file-to-your-project}
Change directory into the top-level directory of your local repository.
That should mean \code{cd} to the directory whose name matches the
bitbucket repository name.

The following is an example of a ``dot hgignore'' file.  Mercurial will neither
list or otherwise pay attention the files in this list:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYGZsh{} This indicates that we are using shell\PYGZhy{}like matching logic
\PYGZsh{}    instead of regular expressions.
syntax: glob
\PYGZsh{} For Mac users
Thumbs.db
.DS\PYGZus{}Store
\PYGZsh{} This is where Xamarin Studio puts compiled stuff.
bin/
In case you compiled your own stuff, we ignore *.exe and *.dll
*.exe
*.dll
\PYGZsh{} This is a temporary debugging file generated by Xamarin Studio
*.pidb
\PYGZsh{} And one other thing we don\PYGZsq{}t need.
*.userprefs
\end{Verbatim}

Here is a brief explanation of what we've included here and why:
\begin{itemize}
\item {} 
\code{syntax: glob} indicates that uses the ``glob'' syntax, which comes
from MS-DOS (the command prompt still found on Windows). Glob syntax
allows you to do special things like match all files having a
certain extension (e.g. \code{*.exe} matches \code{Hello.exe} and any
other filename with extension .exe.)

\item {} 
\code{Thumbs.db} and \code{.DS\_Store}. Unfortunately, the Mac is still
notorious for generating temporary files that serve no purpose,
except on OS X. In general, we try to keep these files out of our
repository and encourage you to do the same, especially if you are a
Mac user.

\item {} 
\code{*.exe} and \code{*.dll}. Anything that can be (re)produced by the
Mono or Xamarin Studio tools should be excluded. In particular, do not
keep these files in your repository. Today, they are quite small,
but in future development work, they can be large. Worse, they are
not text files (unlike your .cs files), so they cannot be stored
optimally in a version control system.

\item {} 
There are some other files produced by Xamarin Studio that we've put on
the exclusion list, including \code{*.pidb} and \code{*.userprefs}. The
reasoning for not keeping these is similar to that in the previous
case.

\end{itemize}

Now do the following steps:
\begin{enumerate}
\item {} 
Using your text editor, create a file \code{.hgignore}. You can simply
copy and paste the above contents into this file.  Be careful of an editor
like notepad, which adds ''.txt'' to the end of file names by default.

\end{enumerate}
\begin{quote}
\begin{description}
\item[{\textbf{Windows}: To change from the default extension, use Save As, and change the}] \leavevmode
file type from .txt by electing the drop-down menu beside file type, and
select ``All files''.

\end{description}
\end{quote}
\begin{enumerate}
\item {} 
Create or copy your existing \code{Hello World} example, hello.cs to the
the \code{labs} folder.

\item {} 
Let's test whether .hgignore is having any effect. Go to the
\code{labs} folder and compile the \code{Hello, World.} example.

\item {} 
Verify that the .cs and .exe files are in the labs directory
(\code{ls} on Linux or OS X; \code{dir} on MS-DOS):

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
gkt@gkt\PYGZhy{}mini:\PYGZti{}/gkt170/labs\PYGZdl{} mcs hello.cs
gkt@gkt\PYGZhy{}mini:\PYGZti{}/gkt170/labs\PYGZdl{} ls \PYGZhy{}l
total 8
\PYGZhy{}rw\PYGZhy{}r\PYGZhy{}\PYGZhy{}r\PYGZhy{}\PYGZhy{} 1 gkt gkt  224 2012\PYGZhy{}02\PYGZhy{}20 20:02 hello.cs
\PYGZhy{}rwxrwxr\PYGZhy{}x 1 gkt gkt 3072 2012\PYGZhy{}02\PYGZhy{}20 20:05 hello.exe
\end{Verbatim}

\item {} 
Check the status:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
gkt@gkt\PYGZhy{}mini:\PYGZti{}/gkt170/labs\PYGZdl{} hg status
? .hgignore
? labs/hello.cs
\end{Verbatim}

What this tells us is that \code{.hgignore} and \code{labs/hello.cs} are not
presently being tracked by our version control system, Mercurial. The
file \code{labs/hello.exe} is not shown, because it's on the ignore list.

Note that we actually need to put the \code{.hgignore} file under version
control if we want to use it wherever we happen to be working with our
stuff (i.e. when we're not in the computer lab but, say, at home).

\item {} 
Add the file to version control:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
gkt@gkt\PYGZhy{}mini:\PYGZti{}/gkt170\PYGZdl{} hg add .hgignore

gkt@gkt\PYGZhy{}mini:\PYGZti{}/gkt170\PYGZdl{} hg add labs/hello.cs
\end{Verbatim}

\item {} 
Commit the changes, and then see the log entry
with the commands below.  If you set the .hgrc file,
the command somewhere inside your local repository could be:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{hg} \PYG{n}{commit} \PYG{p}{\PYGZhy{}}\PYG{n}{m} \PYG{l+s}{\PYGZdq{}adding an .hgignore file and Hello, World to the project\PYGZdq{}}
\end{Verbatim}

If you did not create .hgrc, you need also include identification
with -u yourName after \code{commit}, as in
\begin{quote}

hg commit -u gkt -m ``adding an .hgignore file and Hello, World to the project''
\end{quote}

It is Ok if your message wraps to a new line.  You can check the log entry created
by your commit:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
gkt@gkt\PYGZhy{}mini:\PYGZti{}/gkt170\PYGZdl{} hg log
changeset:   0:9fe6ee1bf907
tag:         tip
user:        George K. Thiruvathukal \PYGZlt{}gkt@cs.luc.edu\PYGZgt{}
date:        Mon Feb 20 20:14:42 2012 \PYGZhy{}0600
summary:     adding an .hgignore file and Hello, World to the project
\end{Verbatim}

\item {} 
Push the changes to Bitbucket with the following command.
(You'll be prompted for user/password not shown here):

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{hg} \PYG{n}{push}
\end{Verbatim}

You should get a response like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{pushing} \PYG{n}{to} \PYG{n}{https}\PYG{p}{:}\PYG{c+c1}{//gkthiruvathukal@bitbucket.org/gkthiruvathukal/gkt170}
\PYG{n}{searching} \PYG{k}{for} \PYG{n}{changes}
\PYG{n}{remote}\PYG{p}{:} \PYG{n}{adding} \PYG{n}{changesets}
\PYG{n}{remote}\PYG{p}{:} \PYG{n}{adding} \PYG{n}{manifests}
\PYG{n}{remote}\PYG{p}{:} \PYG{n}{adding} \PYG{n}{file} \PYG{n}{changes}
\PYG{n}{remote}\PYG{p}{:} \PYG{n}{added} \PYG{l+m}{1} \PYG{n}{changesets} \PYG{n}{with} \PYG{l+m}{2} \PYG{n}{changes} \PYG{n}{to} \PYG{l+m}{2} \PYG{n}{files}
\PYG{n}{remote}\PYG{p}{:} \PYG{n}{bb}\PYG{p}{/}\PYG{n}{acl}\PYG{p}{:} \PYG{n}{gkthiruvathukal} \PYG{k}{is} \PYG{n}{allowed}\PYG{p}{.} \PYG{n}{accepted} \PYG{n}{payload}\PYG{p}{.}
\end{Verbatim}

\end{enumerate}


\subsubsection{Create an initial structure for your project}
\label{lab-versioncontrol:create-an-initial-structure-for-your-project}
We suggest that you follow a scheme similar to what we use when working
with version control. We suggest that your source code goes in
one or more folders, like work, or homework and labs.

So let's do it:
\begin{enumerate}
\item {} 
Make sure you are in the checkout directory, or \code{cd} to it.

\item {} 
Create directories:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{mkdir} \PYG{n}{hw}
\PYG{n}{mkdir} \PYG{n}{labs}
\end{Verbatim}

We will be creating items in each one of these folders during the lab.

\begin{notice}{warning}{Warning:}
Please note that most version control systems do not allow you to add \emph{empty}
folders to the repository. You must create at least one file and \textbf{hg add} it
to the repository (and \textbf{hg add} and \textbf{hg push}) for the folder to actually
be created. The above was just intended to make you aware of a desired ``organization''.
You are free to organize your project any way you like as long as we are able
to find your homework assignments.
\end{notice}

\end{enumerate}


\subsubsection{Create and Test Content}
\label{lab-versioncontrol:create-and-test-content}\begin{enumerate}
\item {} 
copy in or create a simple program in a directory you created,
like labs/hello.cs

\item {} 
Run it.

\item {} 
Now go back to the command prompt, and enterEnter:
\begin{quote}

hg status
\end{quote}

and produce a response like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{p}{?} \PYG{n}{labs}\PYG{p}{/}\PYG{n}{hello}\PYG{p}{.}\PYG{n}{cs}
\end{Verbatim}

Mercurial shows you the tracked files that are modified (none here)
or files not not being tracked (after a `?'),
except for those files explicitly ignored.  As you can see,
the source (.cs) file is shown, but
no ``binary'' objects (like an .exe file),
since you gave instructions to ignore all such files.

\item {} 
Add the new solution/projects to Mercurial. At this point, if the above list looks
``reasonable'' to you, you can go ahead and just add \emph{everything}. The \textbf{hg} command
makes this easy for you. Instead of adding the specific files,
you can just type the following (nothing after the add):
\begin{quote}

hg add
\end{quote}

and produce a response like:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{adding} \PYG{n}{do\PYGZus{}the\PYGZus{}math}\PYG{p}{.}\PYG{n}{cs}
\end{Verbatim}

If you inadvertently added something that you truly don't want in the repository, you
can use the \textbf{hg rm} command to remove it. We have nothing at the moment that
we want to remove, but want to make you aware that correcting mistakes is possible.

\item {} 
As before, commit and push.  Here is a sequence from Dr. Thiruvathukal's Mac:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
gkt@gkt\PYGZhy{}mini:\PYGZti{}/gkt170\PYGZdl{} hg commit \PYGZhy{}m \PYGZdq{}adding hello program\PYGZdq{}
gkt@gkt\PYGZhy{}mini:\PYGZti{}/gkt170\PYGZdl{} hg push
pushing to https://gkthiruvathukal@bitbucket.org/gkthiruvathukal/gkt170\PYGZbs{}
searching for changes
remote: adding changesets
remote: adding manifests
remote: adding file changes
remote: added 1 changesets with 1 change to 1 file
remote: bb/acl: gkthiruvathukal is allowed. accepted payload.
\end{Verbatim}

\end{enumerate}


\subsubsection{Verify that your stuff really made it to bitbucket.org}
\label{lab-versioncontrol:verify-that-your-stuff-really-made-it-to-bitbucket-org}
At this point, it is entirely possible that you need some convincing to believe that
everything we've been doing thus far is really making it to your repository at Bitbucket.
Luckily, this is where having a web interface really can help us.

Do the following:
\begin{enumerate}
\item {} 
Log into bitbucket.org if you are not already logged in.

\item {} 
Go to Repositories and look for your repository. In the authors case, it is under
\code{gkthiruvathukal / gkt170}.

\item {} 
It pays to take a quick look at the dashboard. You'll see the \emph{recent commits} on the
main screen. You should see at least two commits from our lab session thus far, both
of which likely happened just ``minutes ago''.

\item {} 
You can click on any revision to see what changes were made. It is ok to do so at this
time, but we're going to take a look at the powerful capability of ``looking at the
source''. So go to the \emph{Source} tab.

{\hfill\includegraphics[height=290pt]{bitbucket-source.png}\hfill}

\item {} 
If all was done properly, you will see .hgignore and labs. These
were all the result of our earlier sequence of commit+push operations. You can click on
any folder to drill into the hierarchy of folders/files that have been pushed
to Bitbucket (from your local repository). In labs you find
your source code (for hello.cs). Then you
can look at it--through the web! When you do so, you'll see something like this.

{\hfill\includegraphics[height=290pt]{HelloWorld.png}\hfill}

\end{enumerate}


\subsubsection{Working between lab and home (or home and lab)}
\label{lab-versioncontrol:working-between-lab-and-home-or-home-and-lab}
It may not be immediately obvious, but what we have just shown you is how to work between
the classroom/lab environment and home. In the typical scenario, when you go to your
desk (or laptop), you will go through the following lifecycle:
\begin{itemize}
\item {} 
\textbf{hg pull}: To gather any changes that you made at another location. You are always
pulling changes from the repository stored at Bitbucket, which is acting as our
intermediary. Being ``in the cloud'' it is a great place to keep stuff without having
to worry (for the most part) about the repository getting lost.

\item {} 
\textbf{hg update}: To update your local copy of the repository with all of the changes
that you just pulled down from Bitbucket.

\item {} 
Create or modify your folders/files as desired.

\item {} 
If any files that you want included were just created, use \textbf{hg add}.  It does not
hurt to use this command, even if nothing was added.

\item {} 
\textbf{hg commit -m message.}: Save any changes you've made, to your local repository only.

\item {} 
\textbf{hg push}: Push the changes you've stashed in your local repository to the Bitbucket
repository.

\end{itemize}

You might wonder why the pull/update and commit/push operations are separate. For a team
of one (or two, if you have a pair), it is not likely that you'd make a mistake when
coordinating changes to a central repository. In a larger team, however, some coordination
is required. We're not going into all of those details in this lab, of course, but will
likely revisit this topic as we get closer to the team project, which we think will make
you thankful for having a version control system.


\subsubsection{Getting our examples}
\label{lab-versioncontrol:getting-our-examples}
We're going to conclude by taking this opportunity to introduce you to how \emph{we} (Drs.
Harrington and Thiruvathukal) are actually using the stuff we are teaching to work as
a team on developing the book and examples.
\begin{enumerate}
\item {} 
Pick a different location (outside of your repository folder and its subfolders)
to check out our stuff from Bitbucket:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{hg} \PYG{n}{clone} \PYG{n}{https}\PYG{p}{:}\PYG{c+c1}{//gkthiruvathukal@bitbucket.org/loyolachicagocs\PYGZus{}books/introcs\PYGZhy{}csharp\PYGZhy{}examples}
\end{Verbatim}

\item {} 
Don't worry about breaking anything. Because Bitbucket knows what users are allowed
to push changes to our repository, anything you change in your copy won't affect us.

\item {} 
Look under the source tab on the project page.

\item {} 
For example, if you performed a clone to introcs-csharp-examples, you should be able to change
directory one starting with
loyolachicagocs\_books-introcs-csharp-examples-... to see all of our code examples:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
gkt@gkt\PYGZhy{}mini:\PYGZti{}/loyolachicagocs\PYGZus{}books\PYGZhy{}introcs\PYGZhy{}csharp\PYGZhy{}examples\PYGZhy{}662ea45b9965\PYGZdl{} ls
addition1
...
write\PYGZus{}test
\end{Verbatim}

(Most output has been eliminated for conciseness.)

\item {} 
You can explore subfolders to see our programs.

\end{enumerate}

\index{Mercurial}\index{version control}

\section{Mercurial and Teamwork}
\label{hgteamwork:index-0}\label{hgteamwork:mercurial-and-teamwork}\label{hgteamwork::doc}\label{hgteamwork:hg-and-teamwork}
As this course has a team project, this lecture is about how to work as
a team and make effective use of the version control system, Mercurial,
that we have been using throughout the semester. While the focus is on
the use of Mercurial, the principles we are introducing here can be
adapted to other situations (and alternate version control systems).


\subsection{Planning and Communication}
\label{hgteamwork:planning-and-communication}
Two of the most important aspects when it comes to teamwork are planning
and communication. In the real world, planning is often referred to as
\emph{project management}. And communication often takes the form of regular
team \emph{meetings}.

In later courses (e.g. software engineering) there is greater emphasis
placed on thinking more broadly about software process. We're not going
to cover SE in depth here but want you to be aware that software process
is an important topic. Planning and communication are always supporting
ingredients of a \emph{good} software process.

At the level of actual programming, when two folks are working on the
same project, it is important to think about how you can organize your
work so each person on the team can get something done. As we've been
learning throughout the semester, the C\# language gives us a way to
organize our code using projects (with Xamarin Studio). Within a project
we can organize it as a collection of files, each of which maintains
part of the solution to a problem.  These parts are typically organized
using classes within a namespace and methods.

So the key to working together--and apart--is to spend some time, initially,
planning out the essential organization of a project and the files within
it. Much like writing a term paper, you can create classes and methods
that are needed--without writing the actual \emph{body} of the methods--and then
commit your code to the repository. Then each member of the team can work
on parts of the code and test them independently. Then you can sit together
again as a pair to integrate the work you've done independently.

It's easier said than done, but this is intended as a suggestion for
how to collaborate.

In any event, the above suggests that you actually need to
\emph{communicate} if you want to get anything done. You should start by
discussing what needs to be done and work in \emph{real time} to do what
has been described above.  Then you start coding. As you are coding,
you are going to realize that as well as you planned the work to be
done, you ``forgot'' or ``misunderstood'' some aspect. When this happens,
you and your partner(s) need to communicate.

In the modern era of software development, we are richly blessed with
synchronous communication methods such as instant messaging, texting,
group chat, and other forms of synchronous collaboration. When you and
your partner(s) are working on the project, we highly encourage you to
keep a chat window open (Google Talk, AIM, Yahoo, IRC, whatever) and
use it to communicate any issues as they arise.


\subsection{Typical Scenario}
\label{hgteamwork:typical-scenario}
In general, when working with Mercurial, you will find yourself using the
following commands in roughly this order:
\begin{itemize}
\item {} 
\code{hg incoming}: look for incoming changes that were either made by
yourself or your partner(s). We say ``by yourself'' because it is clearly
possible that you are working on another computer somewhere else (laptop,
home computer) and pushed some changes. So it is a good habit to see
whether ``anything has changed'' since the last time you looked, even if
you looked recently.

\item {} 
\code{hg pull}: If there are incoming changes showing up as incoming, then
you should in fact pull them in. This will stage the changes locally
but they will not be incorporated until you type \code{hg update}.

\item {} 
\code{hg update}: Absorbs all changes that were pulled from your remote
repository. This operation has the potential to \emph{overwrite} changes you
are currently making, so you should make sure that the incoming changes
that you observed above are sensible. For example, if you are editing
a file named \code{examples/MyProject/my\_project.cs} and the incoming log
suggests that the same file has been modified, you're likely to end up
with a conflict when performing the update. (We'll cover conflict
resolution shortly.)

\item {} 
\code{hg add}: Whenever you add files to your folder, if you want them to
be in the repository, you always need to \emph{add} them. It is very easy to
forget to do so. The \code{hg status} command can be used to figure out
files that \emph{might} need to be added.

\item {} 
\code{hg status}: This command will become one of your best friends. You
This typically tells you what has happened since you started your work
in this directory (and since the last commit/push cycle). You especially
want to keep on the lookout for the following:
\begin{itemize}
\item {} 
\code{?}: This means that a file is \emph{untracked} in the repository. If you
see a file with the \code{?} status that is important, you'll want
to add it using \code{hg add} as explained above.

\item {} 
\code{M}: This means that a file has been \emph{modified}.

\item {} 
\code{A}: This means that a file has been \emph{added}.

\end{itemize}

\item {} 
\code{hg commit}: In general, you should commit all changes to your
repository, especially before you leave the lab for the day. It is important
to note that committing is a \emph{local} operation and does not affect the
remote repository (at bitbucket.org) until a corresponding push has
been done.

\item {} 
\code{hg push}: Almost immediately after a commit, it makes sense to do a
push, especially if you are in the lab and will be continuing your work
on other computers. In addition, as you've observed with previous homework,
it is the only way to ensure that you can view the code on BitBucket (our
hosting site for Mercurial projects).

\end{itemize}


\subsection{Conflict Avoidance}
\label{hgteamwork:conflict-avoidance}
Inevitably, when you are working on project, you are likely to end up
in a situation where you and your partner(s) make changes that
conflict with one another. In many cases, the version control software
can automatically merge the changes. Here are just a few examples of
where it is possible to do so:
\begin{itemize}
\item {} 
You make changes to different files.

\item {} 
You make additions to the repository.

\item {} 
You make changes to a common file that do not overlap. An example of
this might be where you have two functions in your program and both
you and your partner are careful not to modify them.

\end{itemize}

In general, we encourage you to coordinate your efforts, especially
when you are doing something like the third situation.

Where you get into trouble is when there are changes to a common file
that conflict with one another. When this happens, you have two
choices in practice:
\begin{itemize}
\item {} 
use \code{hg merge} and \code{hg resolve} to merge your changes.

\item {} 
make a copy of the conflicting files (e.g. Copy \code{hello.cs} to
\code{hello.cs-backup} and use \code{hg update -{-}clean} (changing your
copy to match the current version in the remote repository) to just
accept the latest versions of all files from the repository.

\end{itemize}

In our experience, the first option is tricky. You are given the
option to perform the merge anyway or use a merge tool to select the
changes of interest (and decide between them).

The second option basically results in two copies of the file. You can
open up your editor to compare the files side-by-side or use a tool
like \code{diff} on Unix or a Mac, which gives a side-by-side comparison:

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{diff} \PYG{p}{\PYGZhy{}}\PYG{n}{y} \PYG{n}{hello}\PYG{p}{.}\PYG{n}{cs} \PYG{n}{my\PYGZus{}hello}\PYG{p}{.}\PYG{n}{cs}
\end{Verbatim}

(You will need to expand the width of your console window to see clearly!)

This tool is not built into Windows.  In the Windows lab, you can use the
much less visually helpful

\begin{Verbatim}[frame=single,commandchars=\\\{\}]
\PYG{n}{fc} \PYG{n}{hello}\PYG{p}{.}\PYG{n}{cs} \PYG{n}{my\PYGZus{}hello}\PYG{p}{.}\PYG{n}{cs}
\end{Verbatim}

to show differing segments from each file.
You can also download difference display tools for Windows that are more
visually helpful.  One of many choices is at \href{http://winmerge.org}{http://winmerge.org}.


\subsection{E-mail Notifications}
\label{hgteamwork:e-mail-notifications}
One of the best ways to avoid conflicts when working on a team is to
enable e-mail notification on your repository.

Bitbucket, the hosting service we are using and recommending for our
students, provides full support for e-mail notification. Whenever you
or your partner(s) push changes to the hosted repository, an e-mail
will be generated.

These are the steps to set it up. (Owing to the changing nature of web
interfaces, we are providing generic instructions that should be
adaptable if the Bitbucket service decides to change its web user interface.)
\begin{enumerate}
\item {} 
Make sure your repository is selected. This is always the
especially when you visit your repository by URL.

\item {} 
Select the administrative (Admin) tab.

\item {} 
Select Services (left-hand-side navigation).

\item {} 
Add the Email or Email Diff service. These services are basically
equivalent, but one will generate links so you can view the
differences that were just pushed. We recommend Email Diff.

\item {} 
Add the email notification address. You can only have one address.
A good way to overcome this limitation is to set up a group service,
say, at Google Groups.

\end{enumerate}


\subsection{Communication is Key to Success}
\label{hgteamwork:communication-is-key-to-success}
At the risk of repeating ourselves, we close by reminding you of the
central importance of good communication. The authors of this book
communicate when it comes to their changes--even before we make
them. Yet we occasionally trip over each other, and there is usually a
fair amount of manual reconciliation required to deal with conflicts
when we end up touching the same file by mistake.

When you absolutely and positively need to change a common file, it is
important to ask yourself the important question: Shouldn't we be
sitting together to make these changes? It's a rhetorical question,
but working closely together, either in the same room or through a
chat session/phone call, can result in significantly fewer headaches,
especially during the early stages of a project.

So please take this time to stop what you are doing and
communicate. You'll know your communication is good if you never need
to do anything that has been described on this page. Then again, we're
human. So you it is likely to happen at least once. (We know from
experience but are doing everything possible to avoid conflicts in our
work!)


\section{Acknowledgments}
\label{acknowledgments::doc}\label{acknowledgments:acknowledgments}\begin{itemize}
\item {} 
The Sphinx team at \href{http://sphinx.pocoo.org}{http://sphinx.pocoo.org} for creating such an awesome documentation tool.

\item {} 
The Bitbucket team at \href{http://bitbucket.org}{http://bitbucket.org} for giving us a great place to collaborate. We are now moving to GitHub at \href{http://github.com}{http://github.com} but still think very highly of the Bitbucket team, especially for students and faculty who need to do private projects. (We still use both.)

\item {} 
Jeremy Chalmer at \href{http://jchalmer.com/}{http://jchalmer.com/} for his past work to get a \emph{nice} Twitter Bootstrap theme working with Sphinx. We're now using the Sphinx Bootstrap Theme project at \href{http://loose-bits.com/2013/04/10/sphinx-bootstrap-theme-bootswatch.html}{http://loose-bits.com/2013/04/10/sphinx-bootstrap-theme-bootswatch.html} but are indebted to Jeremy for inspiring us to take Bootstrap seriously.

\item {} 
Speaking of Sphinx Bootstrap Theme, I wish to thank the two developers (Ryan Roemer and Russell Sim) for adding support for some missing features, especially to support shorter navigation links, links to key pages (e.g. genindex). Their tireless dedication and friendly attitude are what makes free/open source software so awesome!

\end{itemize}



\begin{thebibliography}{WikipediaShellSort}
\bibitem[WirthADP]{WirthADP}{\phantomsection\label{sorting:wirthadp} 
Niklaus Wirth, Algorithms + Data Structures = Programs, Prentice Hall, 1976.
}
\bibitem[WikipediaShellSort]{WikipediaShellSort}{\phantomsection\label{sorting:wikipediashellsort} 
\href{http://en.wikipedia.org/wiki/Shellsort}{http://en.wikipedia.org/wiki/Shellsort}
}
\bibitem[uClibc]{uClibc}{\phantomsection\label{sorting:uclibc} 
\href{http://en.wikipedia.org/wiki/UClibc}{http://en.wikipedia.org/wiki/UClibc}
}
\bibitem[TCSortingJava]{TCSortingJava}{\phantomsection\label{sorting:tcsortingjava} 
\href{http://tools-of-computing.com/tc/CS/Sorts/SortAlgorithms.htm}{http://tools-of-computing.com/tc/CS/Sorts/SortAlgorithms.htm}
}
\bibitem[CamelCase]{CamelCase}{\phantomsection\label{homework-gradecalculation2:camelcase} 
\href{http://en.wikipedia.org/wiki/CamelCase}{http://en.wikipedia.org/wiki/CamelCase}
}
\bibitem[UPennCSharp]{UPennCSharp}{\phantomsection\label{homework-gradecalculation2:upenncsharp} 
\href{http://www.cis.upenn.edu/~cis193/csstyle.html}{http://www.cis.upenn.edu/\textasciitilde{}cis193/csstyle.html}
}
\end{thebibliography}



\renewcommand{\indexname}{Index}
\printindex
\end{document}
