C++ Beginners


:: Session 2 ::

Chapter 4: computation


Programming, Principles and Practice Using C++ — Bjarne Stroustrup

Computation

input -→ I/O -→ output

get input from outside sources

I/O's internally, i.e. internal data exchanges and sharing between cooperating parts of a program

give output to outside world

Computation

computation means the act of producing some outputs based on some inputs

Objectives

Correctly, Simply, Efficiently

  1. Get it to work.
  2. Make the code beautiful.
  3. Optimize.

tools

Abstraction: hide details, such as usage of sort();or access memories indirectly.

Devide & Conquer: break-down or devide a large problem into smaller problems

Concerns about structure

e.g. using existing libraries: saves us from dealing with the hardware's I/O ports.

Expressions


…computes a value from a number of operands

the simplest expression is a literal value

Names of variables are expressions, which represent the values found in the objects with that name.

the Lvalue and the Rvalue: e.g x = x*3;

group expressions with parentheses.

Constant expressions

notion of a symbolic constant: a named object initialized with a constant value which can't be changed


  constexpr double pi = 3.1415926;  // initialize constant "pi"
  const int x = n + 7; // initialize constant "x"
  // value "n" which is unknown at compile time
              

Avoid magic constants. i.e. avoid using non-obvious literals, like 299792458, in code.

constexpr must be given a value that is known at compile time.

common operators
Name Comment
f(a) function call pass a to f as an argument
++lval pre-increment increment and use the increment value
--lval pre-decrement decrement and use the decrement value
!a not result is bool
-a unary minus
a*b multiply
a/b divide
a%b modulo(remainder) only for integer types
a+b add
a-b subtract
out<<b write b to out where out is an ostream
in>>b read from in to b where in is an istream
a<b less than result is bool
a<=b less than or equal result is bool
a>b greater than result is bool
a>=b greater than or equal result is bool
a==b equal
a!=b not equal result is bool
a&&b logical and result is bool
a||b logical or result is bool
lval=a assignment
lval*=a compound assignment lval=lval*a; also for /, %, +, -

Conversions


  5/2;  // is 2 not 2.5
  2.5/2;  // is 1.25 (integer 2 is converted to double)
  'a'+1;  // means int{'a'}+1; char a is converted to int
              

Statements


Selection

if-statement


  if() { ...; }
  else if() { ...; }
  else { ...; }
              

switch-statement


  switch(s) {             // "s" can't be a string (must be int, char, or enumeration types)           
              case 'a':   // value of case must be a constant expression
                ...;      // cannot use a variable in a case label
                break;    // cannot use the same value for two case labels 
              case 'b':
                ...;
                break;    // end each case with a break
              ...
              default:
                ...;    
            }
              

Can use several case labels for a single case


  case'0':case'2':case'4': break;              
  case'1':case'3':case'5': 
                           .....;              
                           break;      
  default:                 .....;        
              

Iteration

while-statement


  // calculate and print a table of squares 0–99
  int main() {
    int i = 0;    // the loop variable for a while-statement must be
                  // initialized outside/before the while-statement
    while(i<100) {
      cout << i << '\t' << square(i) << '\n';  
      ++i;        // increment
    }             // …is called a block or a compound statement
  }
              

{ } is a empty block which does nothing.

for-statement

is just a while-statement, used when with simple initializer, condition and increment.


  // calculate and print a table of squares 0–99
  int main() {
    for (int i = 0; i<100; ++i)
    cout << i << '\t' << square(i) << '\n';
  }
              

Functions


function definition

type identifier (parameter-list) function-body

function declaration


  int square(int);
  double sqrt(double);              
            

Vector


…is one of the ways of storing collections of data

A vector is a sequence of elements accessable by an index.


  vector<int> v = {5,6,7,8,9};
  vector<string> friends = {"Anna","Bob","Ted","Joe","Mischa"};
              

A vector stores its elements and knows its size

Use the (n) notation to define a vector of a given size


  vector<int> vi(6);
              

Traversing a vector


v.size() gives the number of elements of v

v.size(0) is an empty vector

v[0] is the first element

v[v.size()-1] is the last element

A range-for-loop


  vector<int> v = {5,6,7,8,9};
  for(int x:v)  // for each x in v
    cout << x << '\n';
              

Growing a vector


Use push_back() operation


  vector<double> v;
  v.push_back(2.7);   // "dot" notation: a member function call
              

A numeric example



// read some temperatures into a vector 
int main() { 
  vector<double> temps; // initialize an empty vector "temps" 
  for (double temp; cin>>temp; ) // read into temp 
    temps.push_back(temp);  // put temp into vector 
                            // . . . do something . . . 
}              
              
  • Using the input operation as the condition for a for-statement
  • it's true if a value was read correctly
  • use "|" to terminate the input loop
  • for- instead of while- to limit the scope of "temp"

A text example



  // simple dictionary: list of sorted words 
  int main() { 
    vector<string> words; 
    for(string word; cin>>word; ) // read each words 
      words.push_back(word); // put into vector 
    cout << "Number of words: " << words.size() << '\n'; 
    sort(words); // sort the words 
    for (int i = 0; i<words.size(); ++i) 
      if (i==0 || words[i–1]!=words[i]) // is this a new word?
        cout << words[i] << "\n"; 
  }
              

Question: How to terminate the input loop of strings?

Answer: ^ + Z (windows), ^ + D (Mac OS X)