programming in c++ teacher: lisa brouwers –phd student –[email protected] litterature: jesse james,...

43
Programming in C++ Teacher: Lisa Brouwers PhD student [email protected] Litterature: Jesse James, “Teach yourself C++ in 21 days”

Post on 22-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Programming in C++

• Teacher: • Lisa Brouwers

– PhD student

[email protected]

• Litterature:• Jesse James, “Teach

yourself C++ in 21 days”

Page 2: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

General information

• Lessons: Monday, Wednesday and Thursday 9 - 12 and 13 - 16 in #606

• Exercises: Tuesday and Friday

• Examination:

• 8 small assignments

• 1 large assignment (co-assignment with the course in agent-programming)

Page 3: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Lesson 1, topics

• Algorithm• Pseudo-code• Why C++ ?• Object-Oriented programming• First program (Hello World)• Types• Variables & Constants• Expressions & Statements

Page 4: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Algorithm“A series of steps that systematically outline how to accomplish a goal.”

Find a suitable method for solving the problem

The description of how to solve the problem is called an algorithm

An algorithm must:• solve the problem• be non-ambiguous• - if the problem has a

final goal, the algorithm must terminate after a finite number of steps

Page 5: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

More on algorithms

• There are three (omitting the goto…) ways a computer can work its way through a set of instructions. It can:

• Sequence– execute the instructions in

sequence;

• Selection– use some test to decide which of

two sets of instructions to perform;

• Iteration– repeat some set of instructions

over and over.

• For handling complex problems:

• Divide into sub-problems

• Solve the sub-problems independently

• or (if still too complex):– divide the sub-problems

further

• continue until all sub-problems can be solved easily

Page 6: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Pseudo-code

• “A high-level abstraction of code, used to outline the general steps in an algorithm without having to write actual code”

Page 7: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Example (algorithm in pseudo-code)

An algorithm in pseudo-code, describing how the sum of

1 + 2 + 3 + … + n , can be calculated.

n is known and is an integer > 0:

1. Set ‘sum’ to 0 and the counter k to 1.

2. Repeat the following until k is larger than n:

2.1 Add ‘sum’ and k and store the result in ‘sum’

2.2 Increase k by 1

3. The result looked for is now in ‘sum’

Page 8: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Example continued

Expressed as part of a C++ program the code looks like:cin >> n;

sum = 0;

for (int k = 1; k<=n; k++)

sum += k;

cout << sum;

Page 9: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Why Program in C++?• 1. C++ allows expression of abstract ideas

– C++ is a third generation language that allows a programmer to express their ideas at a high level as compared to assembly languages.

• 2. C++ still allows a programmer to keep low-level control

– Even though C++ is a 3G language, it allows a programmer to get down into the low-level workings and tune as necessary. C++ allows programmers strict control over memory management.

• 3. C++ has national standards (ANSI)

– Code written in C++ that conforms to the national standards can be easily integrated with pre-existing code. Programmers can reuse certain common libraries, so certain common functions do not need to be written more than once, and these functions behave the same anywhere they are used.

Page 10: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Why Program in C++ (2)

• 4. C++ is reusable and object-oriented

– C++ is an object-oriented language. This makes programming conceptually easier (once the object paradigm has been learned) and allows easy reuse of code, or parts of code through inheritance.

• 5. C++ is widely used and taught

– C++ is a very widely used programming language. Because of this, there are many tools available for C++ programming, and there is a broad base of programmers contributing to the C++ "community".

Page 11: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Object-oriented (OO) programming

• A type of programming in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure. In this way, the data structure becomes an object that includes both data and functions. In addition, programmers can create relationships between one object and another. For example, objects can inherit characteristics from other objects.

• One of the principal advantages of OO programming techniques over procedural programming techniques is that they enable programmers to create modules that do not need to be changed when a new type of object is added. A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify.

Page 12: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

What is an object?

• An object-oriented program is made up of objects.

• An object has an internal state (i.e. variables that are local to the object) and operations to modify that state.

• For example, Björn’s car is an object. It has an internal state consisting of 'amount of fuel', 'make of car', 'number of miles driven' and 'colour' and it responds to the operations 'drive n miles', 'how many miles have you driven?' and 'repaint with colour c'.

• Where relevant, objects know how to display themselves on the screen and how to load and save themselves.

Page 13: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

What is an Instance

• Every object is an instance of (belongs to) a class.

• In simple terms a class is just a template for the object. It contains details of all the behaviour of an object along with what state information the object has (i.e. it has the code and data structure definitions).

• 'Car' is an example of a class. It describes what it is like to be a car but it isn't actually a car itself.

• To make a 'real' car you have to instantiate the class, and then you get an object such as Björn’s car which is a blue Mitsubishi or Anna’s car which is a red Saab.

Page 14: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

"Hello, World"

#include <iostream.h>

int main() {

//print out the text string, "Hello, World!" cout << "Hello, World!" << endl;

return 0;}//-----------------------------------------• C++ source files use one of the suffixes: .c, .cc, .cxx, .cpp, or .c++;

• Compile , but do not link: g++ -c hello.cc

• Compile, link and place output in file hello: g++ -o file hello hello.cc

• The compiler issues warnings´: g++ -Wall -o file hello hello.cc

Page 15: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Int main( )

• Main is a special function in C++, because it is called automatically when you execute a program.

• It returns an int (to the operating system) , therefore you should add the line return 0; as last line in the main function.

Page 16: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Input (cin)

#include<iostream.h>

int main(){ int i1; char c1; float f1; char s1[6]; cin >> i1 >> c1 >> f1 >> s1; return 0;}

This program will input the line

3e3.4yesand store the value 3 in i1, 'e' in c1, 3.4 in f1 and "yes" in s1.

Page 17: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Output (cout)

#include<iostream.h>

int main(){ cout << 3 << 'e' << 3.4 << "yes"; return 0;}

This program will output the line

3e3.4yes

cout can output constant values, variables, expressions or manipulators

Page 18: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Simple data-types

The built-in scalar C++ types include:

Type Size* Range* Comments

int 16 -32768 to 32,767 Most common integer type

long 32 -2,147,483,648 to 2,147,483,647 Used when int is not large enough

float 32 3.4 x 10-38 to 3.4 x 1038 Real Numbers with 7 digit prec.

double 64 1.7 x 10-308 to 1.7 x 10308 Real Numbers with 15 digit prec.

char 8 -128 to 127 For ASCII-char’s and small integers

enum 16 -32768 to 32,767 Enumerated types

*As found in Borland C++ 5.0

Page 19: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Declaring variables

• Names for variables, constants, functions, classes and user-defined types are called identifiers.

• All identifiers must be declared before they can be used in a program.

• Identifiers must start with a letter or an underscore, '_', but digits can be included elsewhere.

• C++ is a case sensitive language meaning that the identifiers 'abc', ABC', and 'aBc' are all different.

• Whitespace cannot be included in identifiers.

• A variable declaration consists of a type name, an identifier name, and possibly an equal sign (=) followed by a value - to initialise the variable.

Page 20: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Declaring variables (2)

Valid declarations include:

int value1, value2 = 3; // value2 is initialised to 3

double sum;

char initial;

Note the semicolon at the end of each declaration.

Page 21: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Declaring constants

C++ programs can include specific integer, real, character, and string values. Such values are called constants. Constants must be initialised and can not change value during runtime. Numeric constants (integer and real constants) appear simply as values. Character constants consist of single characters surrounded by single quotes. String constants are some sequence of zero or more characters surrounded by double quotes. Examples of constants include:

2, 341, 4.55, -45, -56.78, 'a', 'Z', '2', "a", "Z", "Hello there”

Note that 'a' is a character constant while "a" is a string constant. A variable of type char could hold 'a' but not "a". Also, '2' is a character while the digit 2 is an integer.

Often, constants are declared in programs as named constants. The best way to make such a declaration is by using the word const followed by the type of the constant, the name (identifier) of the constant, an equal sign, and its value:

const int MAX_ITEMS = 23;

const char INITIAL = 'J';

const double PI = 3.1417;

Page 22: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Assignment-operator ( = )

Name of variable(identifier) = expression

the value of the expression on the right hand side is first evaluated. The value is then assigned to the variable on the left hand side.

The old value of the variable is overwritten.

The expression on the RHS must be of the same type, or be automatically transformed into, as the variable.

Page 23: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Statements & expressions

• compound-statement• { statement-list ? }

• statement-list• statement• statement-list statement

• statement• declaration-statement• expression-statement• function-statement• flow-control-statement• compound-statement

Page 24: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Statements & expressions (2)

• A declaration-statement is any declaration of a variable. Variables can be declared along with an initialisation. In C++ this can include a value computed in earlier statements in that block.

• An expression-statement is an expression, including assignments.

• A function-statement is a function call.

• A flow-control statement is a conditional, switch or loop statement.

Page 25: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Arithmetic Operators

• Addition +

• Subtraction -

• Multiplication *• Division / (when int’s are divided the rest is omitted,

8 / 3 = = 2)

• Modulus % (the rest in a division, 8 % 3 = = 2)

Page 26: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Shorthand operators

• Int a = 5;• a = a + 5;

instead….• a+=5; //plus-equals• works with all

arithmetic operators.

Page 27: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Postfix Increment and DecrementInt b = 1;

b+=1; // b is increased by 1

instead you can write:

b++; // postfix increment, fetch the value and then increase it by 1

likewise you can decrease the value (by one):

b--;

The value of the variable can also be in-/decreased first (before fetching the value).

Int a = 0, b = 5;

a = b++; a is assigned the value of a (5), after this the value of a is increased

a=++b; the value of b is first increased (to 7) thereafter the value is assigned to a.

Page 28: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Program Structure [selection]

if (some test condition ) { block 1}

else{ block2 }

// the program continues

The 'else' part is optional. The brackets are not required in either part if only one statement is to be executed, but you are advised to always include them to avoid certain errors, hard to understand.

When executed, this statement first evaluates the test condition. If TRUE is returned, the system executes the first block and then moves on to the code after the second set of brackets . If FALSE is returned by the test, the system executes the code inside the 2nd block and then continues with the rest of the program. If there is no 'else' clause, it continues with the rest of the program.

The test condition can involve both relational and logical operators.

Page 29: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Relational operators (true or false)

Equals = =

Not equals !=

Gr than >

Gr than or Eq >=

Less than <

Less than or Eq <=

----------------------------------

Logical operators

AND &&

OR | |

NOT !

Page 30: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Declarations vs. Definitions

A declaration by itself does not include the setting aside or allocation of memory for the identifier being declared. It is only a statement describing what may later come into existence in the computer's memory.

A statement that sets aside memory is called a definition.

Int SomeFunction(int, int); // declaration - no body

int SomeFunction(int first, int second) //definition, tells what the function does

{

first += second;

return first;

}

Page 31: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

The type enum

Used for things you describe in words rather than in numbers, the days of a week for instance.

When defining a variable of the type enum you specify the possible values the variable may take:

int day;

enum weekDay {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

cout <<“Enter a week-day (0 - 6)\n”;

cin>>day;

if (day = = Saturday || day == Sunday)

cout<<“That is in the week-end.\n”;

else

cout<< “This is in the week.\n”;

Page 32: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Lesson 2, topics

• Functions

– parameters

– return values

• Define a new class

• Create instances of the class

• member-data, -functions

• Constructors

• Looping (WHILE and FOR)

Page 33: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Functions

• When a program calls a function the execution switches to the function and then resumes at the line after the call to the function.

• Functions can return something or nothing.

• If they return nothing, they are said to return void

• Returning functions can return any type (int, char, string etc)

• You can send data to a function (arguments)

• The functions are first declared ( a declaration = a prototype) and then defined

• But it is possible to declare the function already in the declaration.

Page 34: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Declaring a function

• Write the prototype (declaration) in a file that is included in your program

• Write the prototype direct in the program where the function is used

• returntype FunctionName(type para1, …);

Page 35: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Defining a function

Int SomeFunction(int a, int b)

{

do something….

return (a*b);

}

the function may take many parameters of different types

you can use Local variables within the function, and the values of those local variables can be returned from the function.

Page 36: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Global variables

• Variables defined outside all functions (even main) have global scope.

• Local variables hide global ones.

• Global variables can be reached from functions by ::

Page 37: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Parameters are local variables

• The formal parameters are assigned the values of the actual parameters (with which the function is called).

• Changes are made on the copies only

• Parameters are passed by value

• correct value can be returned instead

Page 38: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Overloading functions

• You may define several functions with the same name, if they are different enough.

• They must differ in at least:– number of parameters or/and– type of parameters

• Return-type is not different enough

Page 39: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

classes

• Own data-type– encapsulates data (member-data)– and related functions (member-functions)

class Cat{ //declaration of class Cat

int itsAge;

void Meow();

};

Page 40: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

More on classes

The member-functions of a class must be defined as well:

void Cat::Meow(){cout<<“Meooow\n”}; //definition

To call a member you must first create an instance (object) of the class:

Cat Frisky;

Frisky.itsAge = 10;

you reach the inner of an object by using the dot-operator

Frisky is an instance or an Object of the type (class) Cat.

Page 41: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Even more on classes

• Private / Public– private data-members

are only accessible to member-functions in the same class

– Keep data private

• Accessor-functions– used to manipulate

private data

• Isolate the interface (declaration of the class) in a header-file

• Define the classmethods in a .cpp program (or .cc or..)

• Constructors• Destructors

Page 42: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

Looping!

• Iteration• the WHILE statement• while (condition)• FOR-loops• for (int i = 0; cond.; i++)

Page 43: Programming in C++ Teacher: Lisa Brouwers –PhD student –lisa@dsv.su.se Litterature: Jesse James, “Teach yourself C++ in 21 days”

References in C++

• For example:

int ix; /* ix is "real" variable */

int &rx = ix; /* rx is "alias" for ix */

ix = 1; /* also rx == 1 */ rx = 2; /* also ix == 2 */• References can be used as function arguments and return

values. This allows to pass parameters as reference or to return a ``handle'' to a calculated variable or object.