FORMING EMPIRES Motivation for Imperialism. African Trade [15c-17c]
C++-programming - Department of Information …€¦ · · 2011-08-17C++-programming Goal ... I A...
Transcript of C++-programming - Department of Information …€¦ · · 2011-08-17C++-programming Goal ... I A...
C++-programming
Goal
To give basic knowledge of the C++ language. Some previous experiencesin programming are assumed, we assume that you have taken the C part ofthe course.
Litterature, examples
I Skansholm: C++ direkt, in Swedish, Andra upplagan.
I Skansholm: C++ from the beginning, Second edition.
I Etter&Ingber: Engineering Problem Solving with C++, Secondedition.
On the net you can �nd several tutorials, eg
http://www.cplusplus.com/doc/tutorial/http://www.cprogramming.com/tutorial.htmlhttp://www.intap.net/ drw/cpp/
(2009-10-29 � 1.1 )
What is C++?
I An imperative object oriented programming languageI A superset of C, C-programs are usually valid C++I Adds classes and other object oriented basicsI Reference variablesI Stream oriented I/OI Error handling using exceptionsI Name spacesI Declarations and statements can be mixedI A boolean type, bool and a string type, stringI Overloading of functions, default parameters to functionsI Dynamic type checks and conversions at run timeI Templates, that is generic code based on �ctive typesI STL, the Standard Template Library, a collection of classes and other
useful thing, using templates.I No GC, i.e. no automatic garbage collection
I Similarities with Java, Pascal and Fortran
(2009-10-29 � 1.2 )
History
I Originally developed by Bjarne Strostrup 1985.
I First called C with classes
I A versatile object oriented language
I ANSI-standard from 1998 (�ANSI/ISO C++�)
I Inspired languages like Java
(2009-10-29 � 1.3 )
Some features
I C++ uses static typing: all variables has a type that cannot bechanged
I C++ uses weak typing: some type conversions are done automaticallyand uncontrolled and inconsistent conversions are allowed
I In C++ you may works directly with memory addresses
I Explicit manual memory handling
I C++ is compiled to machine code while Python and Java areinterpreted
I Not much of runtime checks while running your program, but it isusually possible to turn on various checkings.
(2009-10-29 � 1.4 )
When, for what and why is C++ used
I Same as C
I A a general purpose object oriented language
(2009-10-29 � 1.5 )
Example
A program that prints Hello, world
// hello.cc
// A first, classic example of a C++-program
#include <iostream>
using namespace std;
int main() {
cout << "Hello, world" << endl;
return 0;
}
(2009-10-29 � 1.6 )
Example: iteration, variables
// squares.cc
// Program that writes a table over squares of the numbers 1, 2, ... 10
//
#include <iostream>
using namespace std;
int main() {
int i = 1;
while ( i<=10) {
cout << i << `\t' << i*i << endl;
i = i + 1;
}
return 0;
}
(2009-10-29 � 1.7 )
Compiling
bellatrix$ ls
squares.cc
bellatrix$ cat squares.cc
// squares.cc
// Program that writes a table over squares of the numbers 1, 2, ... 10
//
#include <iostream>
using namespace std;
int main() {
int i = 1;
while ( i<=10 ) {
cout << i << `\t' << i*i << endl;
i = i + 1;
}
return 0;
}
bellatrix$ g++ squares.cc
bellatrix$ ls
a.out* squares.cc
(2009-10-29 � 1.8 )
Execution
bellatrix$ a.out
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
bellatrix$
(2009-10-29 � 1.9 )
Example: several functions
// factorial.cc
// Program that tabulates the faculty function
//
#include <iostream>
using namespace std;
int factorial(int n) {
int result = 1;
while ( n > 0 ) {
result = result*n;
n = n - 1;
}
return result;
}
int main() {
int i = 0;
while ( i<=15 ) {
cout << i << `` `` << factorial(i) << endl;
i = i + 1;
}
return 0;
}(2009-10-29 � 1.10 )
Example: recursion, conditional statements
// factorialRec.cc
// Program that tabulates the faculty function
// Recursive version.
//
#include <iostream>
using namespace std;
int factorial(int n) {
if ( n<=0 )
return 1;
else
return n*factorial(n-1);
}
int main() {
int i = 0;
while ( i<=15 ) {
cout << i << `` `` << factorial(i) << endl;
i = i + 1;
}
return 0;
}
(2009-10-29 � 1.11 )
Conclusions
I A C++-program consists of one or more function that are stored inone (or more) �le
I Comments: // is used for oneline comments.
I #include <iostream> to use library functions for I/O (cout, cin)
I A C++-function has a return type, a name, a parameter list and afunction body
I The function body can hold declarations of variables and statements
I Semicolon (;) is used to terminate declarations and statements.
I Vaiables can also be declared outside a function. They then becomeglobal in some sense.
(2009-10-29 � 1.12 )
Conclusions continued
I Each �le must be compiled before the program can be executed
I The execution starts in the function named main
I Variables must be declared with type och name
I Variables are assigned values (of the proper type) with assignments
I Statements in a function are executed in sequence
I Statements for selections: if (and switch)
I Statements for iterations: while (and for and do-while).
(2009-10-29 � 1.13 )
Exercises
1. Write a program that reads characters from standard input, and counts thenumber of sentences if the text. A sentence is terminated with a period, anexclamation mark or a question mark.
2. Write a C-function that computes the harmonic sum
1 + 1=2 + 1=3 + 1=4::: + 1=n
What parameters and what return type should the function have?
3. Write a C-program that tabulates the above sum for n = 1; 2; : : : ; 10
4. Write a C-program that computes how many terms are required to get a sum
1 + 1=2 + 1=3 + 1=4::: + 1=n
that is greater than 10.
(2009-10-29 � 1.14 )
Strings
C++ do have a string -type. This is di�erent from the array of charactersthat both C and C++ can use.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = ``Gyro Gearloose''; // create a string
string t = ``Donald Duck'';
if (t < s) cout << t << endl; // compare
cout << ``length is '' << t.length() << endl;
string u;
cin >> u; // read a string, stop at first space or EOL
(2009-10-29 � 1.15 )
Strings
string v;
cin >> ws; // skip rest of the line
getline(cin, v); // read a line into v
for(int i = 0; i < t.length(); i++)
cout << t[i]; // element by element
cout << endl;
for(int i = 0; i < t.length(); i++)
cout << t.at(i); // element by element, safer
cout << endl;
cout << u + v << endl; // concatenate u and v, print sum
u += v; // put v at the end of u, u is changed.
cout << u << endl;
}
(2009-10-29 � 1.16 )
Strings
rontok.it.uu.se> g++ string.cc
rontok.it.uu.se> a.out
Donald Duck
length is 11
Hej
hopp
Donald Duck
Donald Duck
Hejhopp
Hejhopp
(2009-10-29 � 1.17 )
Exercises
1. Write a program that reads numbers from standard input and that countsthe number of words. A word is de�ned as a sequence of characters.
2. Modify the program so that it also prints the length of the longest word.
3. Write a function int isEqual(char c1, char c2) that returns 1 if thecharacters c1 and c2 are equal, otherwise 0. If the characters are letters,they should be treated as equal regardless of case (upper/lower).
4. Write a program that reads a line from standard input and that prints theline translated to �rövarspråket�.
In the translation, a consonant like x is replace with xox while vowels are leftunchanged. For example: The text �Don't panic� becomes �Dodonon'totpopanonicoc�.
5. Write a function that reads a line of arbitrary length from standard inputand that prints the line backwards, i. e. with the last character �rst. Thefunction need not use arrays or lists.
(2009-10-29 � 1.18 )
Formatted output
cout � formatter � variable � . . .
// test of formatted output
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double t = 4.5;
int i = 14;
cout << t << endl;
cout << setw(10) << fixed <<
setprecision(2) << t << endl;
cout << setw(10) << setiosflags(ios::fixed)
<< setprecision(2) << t << endl;
cout << oct << i << `` `` << hex << i << `` ``
<< dec << i << endl;
cout << showbase << oct << i << `` `` << hex << i
<< `` `` << dec << i << endl;
return 0;
}
(2009-10-29 � 1.19 )
Formatted output
rontok.it.uu.se> g++ format.cc
rontok.it.uu.se> a.out
4.5
4.50
4.50
237 9f 159
0237 0x9f 159
(2009-10-29 � 1.20 )
Formatted output
You have a number of �ags that are either set or unset, by default all ofthem except dec and right are unset. You set them either using thefunction setios�ags or using a manipulator. A �ag can be reset using thefunction resetios�ags or using a new manipulator that cancels the previousone.
The manipulators are described below, the setios�ags are left to selfstudies.All manipulators are in e�ect until explicitly cancelled. The setwmanipulator has only e�ect on one item, the printable item that follows themanipulator.
Some manipulators are mutually exclusive eg dec, oct and hex.
(2009-10-29 � 1.21 )
Formatted output
Manipulators are:
uppercase, nouppercase uppercase letters in scientific etc
boolalpha, noboolalpha print true/false instead on 1/0 for bools
showbase, noshowbase show base octal, decimal or hex
showpoint, noshowpoint always set a decimal point for floats
left left justify
right right justify
internal internal fill
dec base 10
oct base 8
hex base 16
fixed fixed notation
scientific scientific notation, i. e. with exponent
setw(n) set width to n
setfill(c) set fill character to the char c
setprecision(n) number of decimals
endl end of line
ends send a NULL character to output
flush empties the print buffers
(2009-10-29 � 1.22 )
Input of numbers and other basic types
The function cin for formatted input
Example:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float x;
int n;
cout << "Give x and n: ";
cin >> x >> n;
cout << x << `` `` << n << `` `` << pow(x,n) << endl;
return 0;
}
(2009-10-29 � 1.23 )
General input of characters
The cin � variable statement reads one token at a time. Tokens areseparated by a white space, i.e a space, tab or new line.
When reading or writing characters you have:
cout << c; // print the character c
cout.put(c); // same as above
cin >> c; // read the next nonblank character to c
cin.get(&c); // read the next character to c
cin.get(); // read and return the next character
cin.peek(); // look at the next character without
// reading it
cin.ignore(); // skip the next character
cin.ignore(n,c); // skips at most n characters, up to
// the first occurance of the character c
cin.getline(s,n) // reads the rest of the line to the array s,
// a most n characters
cin >> ws; // skip white spaces
(2009-10-29 � 1.24 )
General input of characters
Example: Read characters from standard input, echo them on standardoutput.
#include <iostream>
using namespace std:
int main() {
int c;
c = cin.get();
while (c != EOF) {
cout << (char)c;
c = cin.get();
}
return 0;
}
(2009-10-29 � 1.25 )
Some facts about functions
I Functions cannot be nested, i. e. a function cannot contain functions.
I A function has zero or more parametrars of arbitrary type
I At call time, the parameters must match in order, number and type.Automatical type conversion may occur if some cases, e. g. int ->double.
I Parameter transmission uses �call by value� or �call by reference�
I A function can be of the type void if it has no return value.
I A function can be overloaded, i. e. you can have functions with thesame name but with di�erent signatures.
I A function can have default parameters
(2009-10-29 � 1.26 )
I Functions can return any scalar type or structure(struct) but notarrrays.
I Functions returns a value of the type int if no explicit type is speci�ed.
I Local variables dies at return (if not static)
I To use a function, if has to be known. To be �known� it must beintroduced either through a de�nition or a declaration:typ name( parameter list );typ name( void );
(2009-10-29 � 1.27 )
Default parameters
A function can be overloaded, this can look like
#include <iostream>
#include <iomanip>
using namespace std;
void print(int tal) {
cout << setw(5) << tal << endl:
}
void print(double tal) {
cout << fixed << setw(10) << setprecision(4)
<< tal << endl;
}
(2009-10-29 � 1.28 )
Default parameters
int main() {
int i = 5;
double d = 5.5;
print(i); // will call the first function
print(d); // will call the second function
}
(2009-10-29 � 1.29 )
Default parameters
They can have default parameters
#include <iostream>
#include <iomanip>
using namespace std;
void print(int tal, int w = 5) {
cout << setw(w) << tal << endl:
}
void print(double tal, int w = 10) {
cout << fixed << setw(w) << setprecision(4)
<< tal << endl;
}
(2009-10-29 � 1.30 )
Default parameters
int main() {
int i = 5;
double d = 5.5;
print(i); // will call the first function
print(d); // will call the second function
print(d,7); // will call the second function
}
Default parameters must occur the end of the parameter list. You mustonly omit parameters at the end.
(2009-10-29 � 1.31 )
Exercises
1. The series0; 1; 1; 2; 3; 5; 8; 13 : : :
is called Fibonaccis numbers.
1.1 Write a program that reads a number n, calculates and prints the n
�rst Fibonaccinumbers.1.2 Write a program that reads a number m and calcutes how many
Fibonacci numbers that are less than or equal to m.
2. The exponential function ex can be approximated with the ini�nite series
1X
i=0
x i
i ! = 1 + x
1+ x2
2+ x3
6+ x4
24+ � � �
Write a function double exp( double x) that calculates and returns (anapproximation) to ex using the above formula.
3. Write a recursive function void printb(int x, int b) that prints x inthe base b. For simplicity, assume that b <= 10.
(2009-10-29 � 1.32 )
Example: Test if a number is a prime number
bool isPrime(int n) {
// Precondition: n is an integer >= 0
// Returns: true if n is a prime number else false
//
bool answer = true;
int i;
for (i = 2; i <= sqrt(n) and answer; i++) {
if ( n%i == 0 ) {
answer = false;
}
}
return answer;
}
I A new operator: and
I The function sqrt
(2009-10-29 � 1.33 )
The program:
// checkPrimes.cc
// Reads a sequence of integer numbers and tests if these are
// a prime number or not.
// Terminates when the number 0 is read.
//
#include <iostream>
#include <cmath>
using namespace std;
int isPrime(int n) { ... } // As above
int main() {
int number=1; // Number to check
while (number!=0) {
cout << "Number to test: ";
cin >> number;
if (number!=0) {
if (isPrime(number)) {
cout << number << `` is a prime number'' << endl;
} else {
cout << number << `` is not a prime number'' << endl;
}
}
}
return 0;
}(2009-10-29 � 1.34 )
Execution:
kursa$ g++ -o checkPrimes checkPrimes.cc
Undefined first referenced
symbol in file
sqrt /var/tmp//ccZwIZDu.o
ld: fatal: Symbol referencing errors. No output written to checkPrimes
collect2: ld returned 1 exit status
kursa$ g++ -o checkPrimes -lm checkPrimes.cc
kursa$ checkPrimes
Number to test: 2
2 is a prime number
Number to test: 4
4 is not a prime number
Number to test: 12
12 is not a prime number
Number to test: 13
13 is a prime number
Number to test: 4731
4731 is not a prime number
Number to test: -4
-4 is a prime number
Number to test: 0
kursa$
(2009-10-29 � 1.35 )
References
C++ has reference variables and reference parameters. You declare
int n = 5;
int &ri = n;
This gives ri as an alias to n. Thus
ri = 15; // set n to the value 15
cout << n; // will print n, i. e. 15
A reference can be seen as a pointer with automatic dereferrencing that isconstant. A reference cannot be changed once initialized.
C++ do have C-pointers also.
(2009-10-29 � 1.36 )
Reference parametersReferences can also be used as parameters
#include <iostream>
using namespace std;
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int i = 2, j = 3;
cout << ``i = `` << i << `` j = `` << j << endl;
swap(i,j);
cout << ``i = `` << i << `` j = `` << j << endl;
return 0;
}
rontok.it.uu.se> g++ ref.cc
rontok.it.uu.se> a.out
i = 2 j = 3
i = 3 j = 2
(2009-10-29 � 1.37 )
Dynamic allocation
Memory in C++ can be dynamically allocated using new and delete.
double *d = new double; // a scalar
double *p = new double[10]; // an array
for (int i = 0; i++; i < 10) p[i] = 0;
delete d; // release the memory
delete [] p; // release an array
(2009-10-29 � 1.38 )
Error handling using exceptions
Run time errors can be handled by creating an exception. An exception isan event that interrupts normal execution and that produces some datathat describes the error.
An exception either terminates your program or is handled in a specialexception handler that you provide.
(2009-10-29 � 1.39 )
Error handling using exceptions
An example:
#include <iostream>
#include <stdexcept>
using namespace std;
int quotient(int a, int b) {
if (a == 0 and b == 0)
throw domain_error(``undefined operation'');
else if (b == 0)
throw overflow_error(``division by zero'');
else return a/b;
}
(2009-10-29 � 1.40 )
Error handling using exceptions
int main() {
cout << quotient(34, 4) << endl;
cout << quotient(34, 0) << endl;
return 0;
}
rontok.it.uu.se> g++ quote.cc
rontok.it.uu.se> a.out
8
terminate called after throwing an instance of 'std::overflow_error'
what(): division by zero
Abort
(2009-10-29 � 1.41 )
Error handling using exceptions
An better example:
#include <iostream>
#include <stdexcept>
using namespace std;
int quotient(int a, int b) {
if (a == 0 and b == 0)
throw domain_error(``undefined operation'');
else if (b == 0)
throw overflow_error(``division by zero'');
else return a/b;
}
(2009-10-29 � 1.42 )
Error handling using exceptions
int main() {
try {
cout << quotient(34, 4) << endl;
cout << quotient(34, 0) << endl;
}
catch (overflow_error) {
cout << ``Overflow error occurred'' << endl;
}
cout << quotient(14, 2) << endl;
return 0;
}
rontok.it.uu.se> g++ quote1.cc
rontok.it.uu.se> a.out
8
Overflow error occurred
7
(2009-10-29 � 1.43 )
Error handling using exceptions
You use a try -statement around the statements that potentially canproduce an error. Then you add one or more handler using catch to handlethe error.
If an error occurs, the execution is transferred to the error handler, theerror is somehow handled and execution is resumed with the statement thatfollows that catch-block.
It can sometimes be hard to know what kind of execeptions a function canproduce. To make it easier to �nd you can optionally list possible exceptionin the function header
(2009-10-29 � 1.44 )
Error handling using exceptions
int quotient(int a, int b) throw(domain_error, overflow_error)
{
if (a == 0 and b == 0)
throw domain_error(``undefined operation'');
else if (b == 0)
throw overflow_error(``division by zero'');
else return a/b;
}
This adds no functionality, it just clari�es what the function can produce.
(2009-10-29 � 1.45 )