\documentstyle[12pt]{article}
\oddsidemargin 0.25in
\topmargin -0.5in
\textheight 8.5in
\textwidth 6.25in
\newcommand{\doublespace}{
   \renewcommand{\baselinestretch}{1.5}
   \large\normalsize}
\newcommand{\singlespace}{
   \renewcommand{\baselinestretch}{1.0}
   \large\normalsize}
\newcommand{\be}{\begin{equation}}
\newcommand{\ee}{\end{equation}}

\begin{document}
\title{Physics 231C: Simulations in C++}
\author{Prof. Clare Yu\\
email: cyu@moses.ps.uci.edu\\
phone: 714-824-6216\\Office: 2164 FRH}
\date{Spring 1998}
\maketitle
\setcounter{page}{1}
\thispagestyle{empty}

These notes draw material from the notes of Prof. Steve White,
from Barton and Nackman's book {\it Scientific and Engineering
C++}, and from {\it C++ for Dummies} by Stephen R. Davis.

\centerline{\bf LECTURE 1}

Discuss Syllabus.

Project possibilities: Matrices of complex numbers, arbitrary precision
arithmetic, data analysis, experiment control, finite elements,
solve differential equations, plotting library (see 
http:\/\/hedrock.ps.uci.edu\/c++\/projects.html for projects done
by the previous course) 

Misc: Web pages, accounts on Suns, you can do work on any machine.
If you use a Sun workstation, use the g++ compiler.

\centerline{\bf Reasons for learning C++}
\begin{enumerate}
\item We can write better, bigger and more sophisticated programs.
\begin{enumerate}
\item Better encapsulation--``Object oriented approach''
\item Dramatic reduction in run--time bugs
\item Code reuse
\end{enumerate}
\item Efficiency:
\begin{enumerate}
\item Memory efficiency is much better.
\item Speed: Can be as good as Fortran (and much better than other things)
\end{enumerate}
\item Good for getting jobs outside of physics
\end{enumerate}

\centerline{\bf Problems with C++}
\begin{enumerate}
\item It's harder to learn.
\item A {\it fast} program takes effort. 
\item C++'s most elegant features tend to be rather inefficient.
\item Not specifically designed for physics--need to make your own
libraries
\end{enumerate}

\centerline{\bf Basic Elements of C++ (Fortran Perspective)}

Simplest program: hello.cc
\begin{verbatim}
#include <iostream.h>
int main()
	{
 	cout<<"hello world"<<endl; 
	return 0;
	}
\end{verbatim}
Or we could have written 
\begin{verbatim}
#include <iostream.h>
void main()
        {
        cout<<"hello world"<<endl;
        }

\end{verbatim}

Here {\tt void main} means nothing is returned, even
though something is done.

To compile this program:
\begin{verbatim}
g++ hello.cc
\end{verbatim}
This gives the executable {\tt a.out}. If you
want the executable to be {\tt hello}, then type

\begin{verbatim}
g++ hello.cc -o hello
\end{verbatim}

To get more information on g++, type {\tt man g++}.

Everything in C and C++ are functions. The main program
{\tt main} is called like a function. 

Syntax: Brackets \{\} group lines. Each line ends with a semicolon ``;''.
Usually there is no semicolon after brackets \{\} (except for a
class). In fortran each line ends when you hit \verb2<return>2 and you 
continue lines with a character in the 6th column. In fortran every
new line must be indented by at least 7 columns. In C and C++,
you don't have to indent lines. 

\verb2#include <iostream>2
means read in the file iostream here. The \verb2#2 sign
indicates that the statement is a preprocessor command. 
Conceptually, the preprocessor is the first step in compilation.
We will discuss preprocessor commands as they arise.
\verb2<  >2 means look for the file in the standard places.

{\tt cout} is defined in the file iostream.h as an iostream. It
represents standard output and writes to the screen. {\tt <<}
is read as an arrow pointing out. {\tt endl} means make a new line
and flush the file from the buffer. {\tt return 0} means standard
return when everything is fine.

Input and output of numbers:
\begin{verbatim} 
	double a,b;	//or could write float
	cin >> a >> b;
	cout << "a=" << a << ", b=" << b << endl;
\end{verbatim}

{\tt cin} is a way of reading numbers in that have been entered from
the keyboard.
\centerline{\bf Things which are similar in Fortran, C, and C++}

\centerline{\bf Types}
\begin{tabbing}
\hspace{2em} \={\underline{Fortran}} \hspace{17em} \={\underline{C, C++}}
\end{tabbing}
\begin{verbatim}
 integer                                int (16 or 32 bits)
 integer*8 (8 bytes)   (1 byte=8 bits)  long or long int (32 or 64 bits)
 integer*4                              short or short int (16 or 32 bits)
 integer*2	
 character*1                            char (8 bits)
 
real                                    float (32 bits)
real*8                                  double (64 bits)
real*16         (not on many machines)  long double (128 bits)

complex                                 defined in library: Complex

character*20                            char a[20]; or use "string" library
logical                                 int (or 1 byte) (0 or 1)

Arrays
  Real A(10) has elements               float a[10]; has elements from
  from A(1) to A(10)                    a[0] to a[9]
 
  Real A(10,10) is 2D array             float a[10][10];  // [row][col]

\end{verbatim}
To initialize arrays in C: 
\begin{verbatim}
int a[5]={0,2,18,12,5};

float b[2][4]={{23.0, 1.3, 22.2, 0.2},
               {0.24, 4.1, 12.0, 9.7}};
\end{verbatim}  


\centerline{\bf Comparisons}

\begin{verbatim}
  x.lt.y                                x < y
  x.le.y                                x <= y
  x.eq.y                                x == y
  x.gt.y                                x > y
  x.ge.y                                x >= y
  x.ne.y                                x != y
\end{verbatim}

\centerline{\bf Logical expressions}

\begin{verbatim}
  .false.                                0
  .true.                                 nonzero, 1
  .not.x                                 !x
 x.and.y                                 x && y
 x.or.y                                  x || y (inclusive or)
\end{verbatim}

Arithmetic operations: \verb2+, -, *, /2 mean the same in fortran, C and C++.
But in fortran $x^y$ is written as {\tt x**y}, while in C and C++,
{\tt x**y} means nothing. One often uses {\tt pow(x,y)} from the
math.h library.

\centerline{\bf Conditional Statements}

\begin{verbatim}
  if(   ) then                           if(x<0)
  ......                                   { .....
  endif                                    }
\end{verbatim}

Style statement: No \{\} are needed if there is only one statement.
\begin{verbatim}
      if(x<0.0) 
        x=0.0;
\end{verbatim}

\{\} 
make a group of statements look like a single statement.

\centerline{\it Else Statements}
\begin{verbatim}
	if(    )
          {...
          }
        else if(...)
          {
          }
        else
          {
          }
\end{verbatim}

\centerline{\it Nested {\tt if} statements}
\begin{verbatim}
        if(    )
          {
           if(    )
             {    }
           else {    }
          }
\end{verbatim}

As an example, let's implement the {\tt fabs()} function:
\begin{verbatim}
    float fabs(float x)         //A function has () after its name.
      {
       float y;
       if(x<0.0)
         y = -x;
       else
         y = x;
       return y;
      }
\end{verbatim}

Another way to write this is
\begin{verbatim}
    float x,y;
    y = (x<0.0)? -x : x;
    return y;
\end{verbatim}
In {\tt y = expr1 ? expr2 : expr3}, expression {\tt expr1} is
evaluated first. If it is true (nonzero), {\tt y} is set equal
to {\tt expr2}. If it is false ({\tt expr1 = 0}), {\tt y = expr3}.

\centerline{\bf Switch}
 
The {\tt switch} statement is a multi--way decision that tests whether
an expression matches one of a number of constant integer values, and
branches accordingly. The syntax is as follows:
\begin{verbatim}
   switch (expression) {
    case const-expression: statements
    case const-expression: statements
    default: statements
    }
\end{verbatim}

Each case is labeled by one or more integer--valued constants or
constant expressions. If a case matches the expression value, the
execution starts at that case. All case expressions must be different.
The case labeled {\tt default} is executed if none of the other cases
are satisfied. A {\tt default} is optional; if it isn't there and if none
of the cases match, no action at all takes place. Cases and the
default clause can occur in any order. For example
\begin{verbatim}
   
   int i, j;
   cin >> i;
   switch(i) {
    case 1: 
      j=i;
    case 2: 
    case 3:
      j=i+5;
    default:
      break;
   }
\end{verbatim}
The {\tt break} statement causes an intermediate exit from the {\tt switch}.
After the code for one case is done, execution falls through to the next 
case unless you take explicit action to escape. {\tt break} and
{\tt return} are the most common ways to leave a {\tt switch}.
\centerline{\bf While loops}
\begin{verbatim}
        while(expression)
          statement
\end{verbatim}
The {\it expression} is evaluated. If it is nonzero, {\it statement} is
executed and {\it expression} is re--evaluated. This cycle continues
until {\it expression} becomes zero, at which point execution resumes after
{\it statement}.

\centerline{\bf Do--While loops}
\begin{verbatim}
      do
        statement
      while (expression);
\end{verbatim}
The {\it statement} is executed, then the expression is evaluated.
If it is true, the {\it statement} is evaluated again, and so on.
When the expression becomes false, the loop terminates.

\centerline{\bf Do Statement/ For loop}

In fortran, the do loop has the form
\begin{verbatim}
     do i=1,10
      .....
     enddo
\end{verbatim}
In C and C++, we would write
\begin{verbatim}
    for(i=1;i<=10;i++)  // i++ is the same as i=i+1
    .....
\end{verbatim}
(Comment follows \verb2//2. ``\verb2//2'' is equivalent to ``!'' in Fortran or
``\verb2/*...*/2'' in C.)
The {\tt for} statement is equivalent to
\begin{verbatim}
    i=1;
    while(i<=10)
     {
     ....
     i++;
     }
\end{verbatim}
 
\centerline{\bf Common Blocks vs. external variables}

In fortran we denote a common block by
\begin{verbatim}
    common /x/ a,b, ...
\end{verbatim}

In C and C++, anything defined outside a function is global, unless declared
otherwise.
\begin{verbatim}
   int a;
   void func1()
     { 
      a=2;
     }
   void func2()
     {
      cout << a << endl;
     }
\end{verbatim}
Here these are all the same {\tt a}. 

A variable defined inside a function is local to the function, and 
no other function can have direct access to it. Each local variable in
a function comes into existence when a function is called, and disappears
when the function is exited. External variables are globally accessible
by all functions, and they exist permanently, rather than appearing
and disappearing as functions are called and exited. Suppose
our program consists of several files with some functions in 
filea.cc, other functions in fileb.cc, and still other functions
in filec.cc. How can we have
variables that are global to the functions in filea.cc and fileb.cc
but not in filec.cc? That's what the {\tt extern} declaration
is for. Suppose we want {\tt aa} to be global to filea.cc and fileb.cc.
Then we would define {\tt aa} outside of any function in one file,
say filea.cc, and then put an {\tt extern} declaration in fileb.cc.
One can either put the {\tt extern} declaration at the top of
fileb.cc or in each function that requires it in fileb.cc.
Note that a variable can only be {\it defined} once in a program
but it can be {\it declared} more than once. A {\it definition}
refers to the place where the variable is created or assigned storage.
A {\it declaration} refers to places where the nature of the variable is
stated but no storage is allocated. Our example would look something
like this:
\begin{verbatim}
//****************************filea.cc***************************
  
  float aa;              //global definition of aa is outside of any function
  int func1(){

   aa=2;
   ...
   }

  float func2(){
  
   aa=aa*3.0;
   ...
   }
//**************************fileb.cc*****************************

  extern float aa;     // declaration of aa that indicates the
                       // definition of aa is elsewhere.
  void func3(){
   cout<<aa<<endl;
   ....
   }

  void func4(){
   ...
   }
\end{verbatim}
Or if we only want {\tt func3} to know about {\tt aa},
we could write 
\begin{verbatim}
//**************************fileb.cc*****************************

  void func3(){
  extern float aa;     // declaration of aa that indicates the
                       // definition of aa is elsewhere.

  } 
  void func4(){
     float aa;         // here aa is local to func4() and is not the
                       // same as the global variable aa.
   ...
   }
\end{verbatim}

\centerline{\bf Built--in types that are not in Fortran:}

{\it Enumerations}

\begin{verbatim}
   enum Color {red, pink, blue};
   Color c = blue;
\end{verbatim}

Each color actually denotes an integer. By default, the count starts at
0.
\begin{verbatim}
   enum Color {red=0, pink=1, blue=2}    //default
\end{verbatim}

But you can specify some other numbering scheme:
\begin{verbatim}
   enum Color {red=5, pink=7, blue}     //In this case, blue=8.
\end{verbatim}

It is legal to go from {\tt enum} to {\tt int}. {\tt int i = pink;}
is legal. But it is not legal to go from {\tt int} to {\tt enum}.
{\tt Color c = blue + 1;} is not legal because there are more integers
than Colors.

(By the way, C and C++ are sensitive to upper and lower case, while
Fortran is not case sensitive.)

\centerline{\bf New arithmetic operations in C and C++:}

There is a nice shorthand involving \verb2+=, -=, *=, /=2.
For example, {\tt a=a+b} becomes {\tt a += b} and
{\tt a=a*c} becomes {\tt a *= c}.

Increment: 

{\tt i++} is the same as {\tt i=i+1}\\
{\tt i--} is the same as {\tt i=i-1}.\\

{\tt ++} and {\tt --} may be used either as prefix operators
(before the variable, as in {\tt ++n}), or postfix operators (after
the variable: {\tt n++}). In both cases, the effect is to
increment {\tt n} by 1. But the expression {\tt ++n} increments
{\tt n} {\it before} its value is used, while {\tt n++} increments
{\tt n} {\it after} its value has been used. For example, 
\begin{verbatim}
      n=5;
      x=n++;
\end{verbatim}
sets {\tt x} to 5  and {\tt n} to 6. But
\begin{verbatim}
      n=5;
      x=++n;
\end{verbatim}
sets both {\tt x} and {\tt n} to 6. Increment and decrement operators
can only be applied to variables; and an expression like
{\tt (i+j)++} is illegal.
 
Assignments using {\tt =} signs return values, namely a new left side:
{\tt a=(i=4)+2} sets {\tt a} to 6.

{\it Modulo} {\tt i \% j} = modulus = remainder. For example,
{\tt 5 \% 3 = 2}, {\tt 20 \% 7 = 6}, etc.

\centerline{\bf Bit Operators}
\begin{verbatim}
  ~i              bit by bit "not", switches 0 to 1 and 1 to 0
  i & j           "AND"
  i ^ j           exclusive "OR"  1^1 yields 0
  i | j           inclusive "OR"  1 | 1 yields 1

 operator        i            j          i operator j
_____________________________________________________

   ~           001                       100
   &           011          110          010	(Both have to be 1 to get 1)
   ^           011          110          101
   |           011          110          111

\end{verbatim}

{\tt <<} left shifts bits. For example, {\tt 1 << 2 = 4} since 4 is
written {\tt 100} in binary. The {\tt 2} tells how far to shift the 1 bit.

{\tt >>} right shifts bits. For example, {\tt 4 >> 2 = 1}.

Octal constants: {\tt 030 = 24} since {\tt 3 x 8 = 24}. Hexadecimal
constants are a sequence of digits preceeded by {\tt 0x}. For example,
{\tt 0x10 = 16}.

{\bf Unsigned type} such as
{\tt unsigned int} means that all the bits go into numbers, and
none of the bits is used to designate a sign. This gives more bits
to be used for numbers.

\centerline{\bf Characters and Strings}

A single quoted letter is a constant for one character. {\tt 'a'}
means one character, the letter {\tt a}.
\begin{verbatim}
    char c = 'X';        //defines c and initializes it.
    c='y';               //reassigns c.
\end{verbatim}

Special characters: 
\begin{verbatim}
    '\n' = newline
    '\t' = tab
     etc.
\end{verbatim}

Literally a char is a byte--size integer. {\tt 'a'} means ``ascii
code for {\tt a} as a byte--sized integer.''
\begin{verbatim}
    cout << 'a' << (int)('a') << endl;
\end{verbatim}
yields {\tt a97} because 97 is the code for {\tt a}. Here's how you can
print out the ascii code for the alphabet:
\begin{verbatim}
    for(char c = 'A'; c <= 'z'; c ++)
      cout << c << "  " << (int)c << endl;
\end{verbatim}
 
(Try it!).

{\bf Cast} In the above example \verb2(int)c2 is an example of
using the {\it cast} operator. Even though {\tt c} is of type {\tt char},
writing \verb2(int)c2 forces a type conversion into an {\tt int}.
{\tt c} isn't converted into an {\tt int}, but the expression
\verb2(int)c2 delivers the integer value of {\tt c}. In general,
a cast construction has the form
\begin{verbatim}
     (type-name) expression
\end{verbatim}
Here the value of {\tt expression} is converted to the named type, even
though {\tt expression} itself is not actually altered.

A {\bf string} is an array of chars. 
\begin{verbatim}
    char s[20];
\end{verbatim}
A string constant looks like this:
\begin{verbatim}
   "A string"            A   s t r i n g \0
                         - - - - - - - - -
                         0   2   4   6   8
\end{verbatim}
The array elements occupy slots 0 through 8. The array size usually
is larger than the string length. The last array element is a \verb2\02.

\begin{verbatim}
   char s[]="A string";		//sets the length automatically
   char s[20]="A string"	//sets s to  A   s t r i n g \0 \0 \0 \0 ...
\end{verbatim}

To copy strings, treat them like arrays. So don't say
\begin{verbatim}
    char s[20],t[20];
    s=t;
\end{verbatim}
(This makes {\tt s} and {\tt t} point to the
same point in memory. We want to make 2 copies of the
same array that will occupy 2 different places in memory.) Rather say

\begin{verbatim}
    char s[20],t[20];
    for(i=0;i<20;i++)
      s[i]=t[i];
\end{verbatim}
If we don't want to waste time copying all the \verb2\0's2,
we can write
\begin{verbatim}
   char s[20],t[20];
   i=0;
   while (1)
    {
     s[i]=t[i];
     i++;
     if(t[i]=='\0')
       break;
    }
\end{verbatim}
or
\begin{verbatim}
   char s[20],t[20];
   i=0;
   while((s[i]=t[i]) != '\0')
     i++;
\end{verbatim}
``{\tt break;}'' tells the program to exit the innermost loop that it is inside 
of. If the program doesn't break, then it continues with the next iteration.

\centerline{\bf Typedef}
The {\tt typedef} declaration gives an additional name to an existing
type. For example,
\begin{verbatim}
       typedef float distance;
\end{verbatim}
Now distance is a synonym for {\tt float}. We can write
\begin{verbatim}
       distance d;
\end{verbatim}
This can make the variables in a program easier to understand. Another use
for {\tt typedef} is if you want to change the variable types in a program.
You may want to do this to suit machine--dependent data types, since
different machines can have different numbers of bytes for 
{\tt long, short}, and {\tt int}. So rather than change every
line, you declare your variables with a synonym and then just
change the {\tt typedef} statement. For example, let's say you write
\begin{verbatim}
       typedef long number;
       number a;
       number b;
       number c;
\end{verbatim}
Later, if you want to change all the {\tt number} variables to 
be {\tt short}, you just change the {\tt typedef} statement:
\begin{verbatim}
       typedef short number;
       number a;
       number b;
       number c;
\end{verbatim}
This is much easier to change than if you had originally written
\begin{verbatim}
       long a;
       long b;
       long c;
\end{verbatim}
and then had to change each line to
\begin{verbatim}
       short a;
       short b;
       short c;
\end{verbatim}
\end{document}
