c++ lectures

484
CS-201: PROGRAMMING LANGUAGE C++ Faculty of Engineering Suleyman Demirel University

Upload: taner-erkan

Post on 13-Apr-2015

81 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: c++ Lectures

CS-201: PROGRAMMING LANGUAGE C++Faculty of Engineering

Suleyman Demirel University

Page 2: c++ Lectures

OVERVIEW

Introduction Contact information Course description Course design Grading Policy

2

C++ Programming Language

Page 3: c++ Lectures

CONTACT INFORMATION

Instructor:- Meirambek Zhaparov Kazimovich- [email protected] ENG faculty 4th floor - Office hours: by appointment

3

C++ Programming Language

Page 4: c++ Lectures

DESCRIPTION

CS 201. Programming Language C++. Lecture 2 hours Practice 2 hours Credit 3

4

Page 5: c++ Lectures

OBJECTIVES

To give students general knowledge of C++ programming language.

To practice general programming techniques in C++ programming language

To learn writing C++ projects.

5

Page 6: c++ Lectures

COURSE DESIGN: TEXT

●C++ without fear. Second Edition. Brian Overland (pdf)

●C++ Language Tutorial,By JuanSoulie. (*)(*) Available online at: http://www.cplusplus.com/doc/tutorial/

●www.cppreference.com

●www.learncpp.com

●Programming.Principles.and.Practice.Using.C++ Bjarne Stroustrup (**)(**) more advanced learning of C++

6

Page 7: c++ Lectures

COURSE DESIGN: ORGANIZATION Lectures- Introduces students to the techniques and practices of

C++ PL.- Review previous lectures. (pop-up quiz)- Attendance check- English speech only Lab sessions- Part of many labs is reserved for individual work,

where everyone works to make progress on exercises.- Tools : GNU C++, Visual Studio, DevCPP, emacs, vi,

QT creator, e.t.c- English speech only- Attendance check

7

Page 8: c++ Lectures

LIST OF TOPICS Introduction to C++, first C++ program Decision Loops Functions Flowchart Array Pointer String, char File Introduction to OOP, class, constructor Operator overloading, dynamic memory Template Stl Inheritance Polymorphism Introduction to UML

8

Page 9: c++ Lectures

COURSE POLICIES: GENERAL Attendance– Attendance is required. We’ll be having regular pop-up

quizzes during lectures. Excused absences will need to be requested in writing ( by EMAIL) and will need evidence.

- Student who has more than 20% of absence will automatically receive “F” grade for the COURSE.

Academic Honesty– Do all assignments by yourself – UNLESS otherwise

instructed.– Do not talk or peek at others papers or cheat sheets

during exams. Cheating is -3 points from general grade.– Develop your own code for practice (can look at others

codes).– University has strict guidelines and we will simply enforce

these.9

Page 10: c++ Lectures

COURSE POLICIES: GRADING Grading Scale

We use the guideline of A for excellent, B for good, C for average, D for poor, and F for fail.

Gradable work and Point Distribution Attendance – 10% ( 5% + 5%)

Quizzes - 10%Tasks, homeworks – 15%

Projects – 25% (10% + 15%)Midterm Exam – 15%

Final – 25%

SubmissionTimely submission is expected on all assignments.

10

Page 11: c++ Lectures

COURSE POLICIES: GRADING Bonus– There is bonus for projects.– There is bonus for practice up to

instructor

Special AccommodationsAny student who feels s/he may need an accommodation based on the impact of a disability should contact me privately to discuss your specific needs.

11

Page 12: c++ Lectures

THANK YOU!

Page 13: c++ Lectures

PL C++ Lecture 1

Page 14: c++ Lectures

C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating 

system.

C++ was written by  Bjarne Stroustrup  at Bell Labs during 1979-1985. C++ is an extension of C.  Prior to 1983, Bjarne Stroustrup added features to C and formed what he called "C with Classes". The term C++ was first used in 1983.

History of C and C++ PL

http://www.cs.bell-labs.com/who/dmr/

http://www2.research.att.com/~bs/homepage.html

Page 15: c++ Lectures

C and C++ difference

C++ is a general –purpose programming language with a bias towards systems programming that

• is a better C;• supports data abstraction

• supports object-oriented programming• supports generic programming

Note: Most things can be done (may be done) also in C, but it will take a century of time

Note 2 : Read books to learn more or google it.

Page 16: c++ Lectures

application

program

machine code

data

compiler

code

statement

source code

Page 17: c++ Lectures

Build the Program (Compile and Link)

Page 18: c++ Lectures
Page 19: c++ Lectures

First program in C++

Page 20: c++ Lectures

Introduction to Data Types

Kazakhstan

Page 21: c++ Lectures

Memory concepts

a = 5; b = 2; 

a = a + 1; result = a - b; 

Page 22: c++ Lectures

Variable always have to begin with a letter. Space, punctuation marks, symbols cannot be used.  They can also begin with an underline character (_ )Variable cannot begin with a digitUse camel case  

Another rule:Variables cannot match any keyword of the C++ language

The standard reserved keywords are:  asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto,if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register,reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while 

Giving a Good name to variable

Page 23: c++ Lectures

Fundamental data types

Name Description Size Range

char Character or small integer.

1byte signed: -128 to 127 unsigned: 0 to 255

short int (short)

Short Integer. 2bytes signed: -32768 to 32767 unsigned: 0 to 65535

Int (*) Integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295

long int (long) Long integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295

Page 24: c++ Lectures

Name Description Size Range

bool Boolean value. It can take one of two values: true or false.

1byte true or false

float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)

double Double precision floating point number.

8bytes 8bytes +/- 1.7e +/- 308 (~15 digits)

long double Long double precision floating point number.

8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t Wide character. 2 or 4 bytes

1 wide character

Page 25: c++ Lectures

int a; float mynumber; 

int a, b;  same meaning as:  int a; int b; 

int a = b = 3;

Declaration

Page 26: c++ Lectures

The integer data types char, short, long and int can be either signed or unsigned

unsigned short int a1;  signed int s2; 

int s2  with exactly the same meaning (with or without the keyword signed)

 The following two variable declarations are equivalent:  short Year;   ==  short int Year; 

The following two declarations are equivalent:  unsigned NextYear;    ==    unsigned int NextYear;

Page 27: c++ Lectures

Do not sleep on PL lecture!!!

Sleep in canteen!!!

To be continued. Wait for updates

Page 28: c++ Lectures

Taking information int a; cin >> a;

There is also usage of cin to request more than one datum input from the user: cin >> a >> b; is equivalent to: cin >> a; cin >> b;

Page 29: c++ Lectures

The assignment operator assigns a value to a variable. a = 5;

The most important rule when assigning is the right-to-left rule: The assignment operation always takes place from right to left, and never

the other way: a = b; (NOTE: what will be result here a=b=c=d=3; )

This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue). The value that was stored until this moment in a is not considered at all in this operation, and in fact that value is lost.

Assignment (=)

a = 2 + (b = 5); is equivalent to: b = 5; a = 2 + b;

that means: first assign 5 to variable b and then assign to a the value 2 plus the result of the previous

assignment of b (i.e. 5), leaving a with a final value of 7.

Page 30: c++ Lectures

Arithmetic operators

Page 31: c++ Lectures

Rules of Operator Precedence

Page 32: c++ Lectures

C++ was written by  

B – Dennis Ritche 

D – John Davis 

A - Bjarne Stroustrup

C – Andrey Stepanov

Page 33: c++ Lectures

D – supports object-oriented programming

A - supports data abstraction

C – supports function overloading

Which is not difference between C and C++  

B – supports generic programming

Page 34: c++ Lectures

What will be result

int b, x = b = 1;x = (2 + x) + (x = b = 5);

B – 8

D – compilation error

A - 4

C – 12

Page 35: c++ Lectures

THANKS.

Page 36: c++ Lectures

PL C++ Lecture 2

Page 37: c++ Lectures

Bool data typeBool data types can take only 2 values true or false. Also in C+ 

bool data types false is equal to 0 and true is equal to 1.

Page 38: c++ Lectures

Char data typeIn C++ char data type is used for a single character.  There are standard  characters like upper and lower case letters of English alphabet, the digit

s '0'..'9' and some special symbols such as *, @, !, etc. Collection of characters is ASCII. Characters are represented as integers. 

(char is a subset of int). For example, in ASCII '9' is decimal 57 and 'A' is decimal 65. 

char c='a' works fine, but char c=“a”; is compilation error. 

Page 39: c++ Lectures

ScopeA variable can be either of global or local scope. 

 If there is same name for global and local variable “::” keyword is used for global. 

Page 40: c++ Lectures

ConstConstant variables are variable with fixed value and cannot be changed. 

Its structure is const data_type name_of_variable = value; 

Note: constant variables must be initialised.

Page 41: c++ Lectures

Escape codesIn C++ there are escape codes, which are used to express more additional

symbols or actions. Its structure consists of “\” sign and letter.

\n newline \t tab\' single quote (') \a alert

e.t.c

Page 42: c++ Lectures

EnumThe enum keyword can be used to create a series of symbolic names

(symbols) each with a constant integer value. Its structure is enum name { symbol_decls };

For enumerated constants rock, paper, scissors and gives them the values 0, 1, and 2.

enum Choice{rock, paper, scissors};

Page 43: c++ Lectures

Integer vs Double

- The range of double is much greater than integer.- Double can also store fractional portions of a number.- Double use more taxing on computer resources.- In double rounding errors an occur.

Page 44: c++ Lectures

Type castingThere are 2 ways:

answer = (double) (numerator) / denominatoranswer = static_cast<double>(numerator) / denominator 

Page 45: c++ Lectures

Everyday we make choice. Or think that we make it.

Page 46: c++ Lectures

if and if-else

Page 47: c++ Lectures
Page 48: c++ Lectures

Dangling-else problem

if ( x > 5 ) if ( y > 5 ) cout << "x and y are > 5";

else cout << "x is <= 5";

The C++ compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces

({ and }). This behavior can lead to what is referred to as the dangling-else problem.

if ( x > 5 ) {

if ( y > 5 ) cout << "x and y are > 5"; } else cout << "x is <= 5";

Page 49: c++ Lectures

(= and ==)?Mostly this type of logical error happens in if structure. Lets assume that in C++ code it is written “if (n=5) ” and “if (n==5)”. In first case number n becomes to equal to 1. In second

case number n checks with 5 and return 0 (true) or 1 (false).

Page 50: c++ Lectures

Conditional operator ?In C++ it can be used conditional operator “?” instead of if .. else

structure. Its structure is : condition ? result1 : result2;

conditional operator can be used in cout stream, which is very powerfull feature.

Page 51: c++ Lectures

Short writing operatorsMostly for short writing code compound assignment operators are used. 

For example “x = x + 5;” can be written as “x += 5;”Also for short writing code increase (++) or decrease (+) are used. 

Page 52: c++ Lectures

pre - post

Page 53: c++ Lectures
Page 54: c++ Lectures

Comparisionrelational operator meaning> x is greater than y< x is less than y>= x is greater than or equal to y<= x is less than or equal to y== x is equal to y!= x is not equal to y

Page 55: c++ Lectures

Logical operators

3 main logical operators in C++: “and” (&&), “or” (||) and “not” (!). 

Page 56: c++ Lectures

Math library

Page 57: c++ Lectures

Appendix F

Page 58: c++ Lectures
Page 59: c++ Lectures

Review 1

int a;char x= “A”;char y= “Z”;a = x – y;

A – 25 B – -25

C – 26 D – Compilation error

Page 60: c++ Lectures

1 – 1

2 – 5

3 – 9

4 – I don't know

Page 61: c++ Lectures

Why “::” symbol is used?

1 - To use standard library

2 – To use global variable

3 – To use local variable

4 – To make difference between local and global variables

Page 62: c++ Lectures

a1 = ? a2 = ?

int a=5, b=2; double a1 = static_cast<double>(a/b); double a2 = (double)(a)/b;

A – 2 2B – 2.5 2.5C – 2 2.5

Page 63: c++ Lectures

What will be output

int a=5, b=4; if (a--==b) cout<<"1";

if (a--==b) cout<<"2"; else cout <<"3";

A – 13B – 23C – 2D – Compilation error

Page 64: c++ Lectures

What will be output for 1 2 3

int a,b,c; cin >> a >> b >> c; cout << ((a>b ? ((a>c) ? c:a):(b>c ? c : b)));

A – 1 B – 2

C – 3 D – Compilation error

Page 65: c++ Lectures

#include <iostream>#include <cmath>

int main(){ int a,b,c; a = 4; b = 25; if (a = sqrt(b))

c = 1; else c = -1; std::cout<<c; return 0;}

1 – 1

2 – -1

3 – CE

4 – I don't know

What will be output?

Page 66: c++ Lectures

Process vs Result

Page 67: c++ Lectures

Thanks!!!

Page 68: c++ Lectures

LECTURE #3

Page 69: c++ Lectures

LOOPs

whiledo … while

for

Page 70: c++ Lectures

WHILEThe “while” loop's structure is : while (condition(s) is(are) true) { code }

In while loop there must be increment (decrement) operations or some checking to make condition false, otherwise it can infinite loop.

Page 71: c++ Lectures

DO … WHILEThe “do .. while” loop's structure is do { code } while (condition[s] is[are] true);

The main difference between do/while and while loops is that sometimes in do/while it can be 1 more step, because firstly it run code then checks the condition.

Page 72: c++ Lectures

FORThe “for” loop's structure is: for (initialization; condition; increase)

Page 73: c++ Lectures

STRUCTURE

Page 74: c++ Lectures

FOR vs WHILE

Page 75: c++ Lectures

BREAK

Break command is used to finish loop and exit from loop even if the loop condition is true.

Page 76: c++ Lectures

CONTINUE

The continue causes to pass rest of loop and go to next iteration.

Page 77: c++ Lectures

EXIT

The “exit” is used to terminate program even if it is not finished. It can be used when error happens in code.

Page 78: c++ Lectures

while (true){

}

INFINITE LOOPS

Page 79: c++ Lectures

Statements with “for”

for (i=0, j=1; i<=10; i=i+2, j++){

j = j+3;i++;

}

Page 80: c++ Lectures

FOR in LAB

FOR (SDUdent i = 1; i<=7; i++)

Page 81: c++ Lectures

FUNCTIONS

In C++ structure of function is:data_type name_of_function (data_type parameter_name) {}

Parameters can be used from 0 to many as needed. The paramet

ers are separated by commas (,). By parameter, function receives variable (arguments), which acts in the function

as local variable.

Page 82: c++ Lectures
Page 83: c++ Lectures
Page 84: c++ Lectures

VOID TYPEIn C++ programmer can write void type specifier in data_type for functions. Its structure is :

void name_of_function(data_type parameter_name) {}This functions with no type is used for example to print values of array, show message.

Page 85: c++ Lectures

The Basics Using Function

Page 86: c++ Lectures

Forward declarationA function prototype is a declaration of function without its implementation. Programmer declares function prototype at the top of the file to show to compiler that it will b

e used. This is called forward declaration.

If forward declaration of function is not used in code and function is written after main function then when programmer tries to use function after compiler gives error.

Page 87: c++ Lectures

EXTERNAL FUNCTIONIn C++ programmer can write a functions in other file and use them. To use external file in C+

+ code it must be included and have an extension .h. Also to include the structure must be like:#include "name_of_file.h"

Page 88: c++ Lectures

LOCAL vs GLOBAL

Page 89: c++ Lectures
Page 90: c++ Lectures

RECURSION

The technique of a function calling itself is called recursion.

The obvious problem is the same one for infinite loops.

If a function calls itself, when does it ever stop?

Page 91: c++ Lectures

GET_DIVISOR

Page 92: c++ Lectures
Page 93: c++ Lectures

INLINE FUNCTION

C++ provides inline functions to help reduce function call overheade specially for small functions. Placing the qualifier inline before a function's return type in the

function definition "advises" the compiler to generate a copy of the function's code in place (when appropriate) to avoid a function call.

12345678910111213141516

#include <iostream> using namespace std;inline double cube( const double side ) { return side * side * side; }   int main() { double sideValue; cout << "Enter n: "; cin >> sideValue;   cout << "Volume is " << cube( sideValue ) << endl; return 0; }

Enter n: 5Volume is 125

Page 94: c++ Lectures

Random Number Generation

i = rand();The function rand generates an unsigned integer between 0 and

RAND_MAX (a symbolic constant defined in the <cstdlib> header file).

To produce integers in the range 0 to 5: rand() % 6

The number 6 is called the scaling factor.

To randomize without having to enter a seed each time srand( time( 0 ) );

To produce integers in the range 10 to 15: 10 + rand() % 6

The number 10 is called the shiftingValue

Page 95: c++ Lectures

Overloading FUNCTION

Page 96: c++ Lectures

int area(int);

int area(int, int);

Page 97: c++ Lectures

A = 1, B = 3

A) 3B) -3C) CE

Page 98: c++ Lectures

OUTPUT A=2, B=3

B function x : 2function y : 3function a : 6------------------function x : 3function y : 4function a : 12------------------main x : 6main y : 12main a : 2

A function x : 2function y : 3function a : 6------------------function x : 3function y : 4function a : 12------------------main x : 6main y : 12main a : 6

C function x : 6function y : 12function a : 72------------------function x : 3function y : 4function a : 12------------------main x : 72main y : 12main a : 72

Page 99: c++ Lectures

A) CEB) 30 1 2C) 30

Page 100: c++ Lectures

int display(){cout << "Hello" << endl;return 1;}void display(int x){cout << x << endl;}void display(float x){cout << x << endl;}void display(float y, char *str){cout << y;cout << ”str” << endl;}

int main(){int z = display();display(33);display(3.2);return 0;}

A) CEB) 33 3.2C) hello 33 3.2

Page 101: c++ Lectures

Lecture 4

Page 102: c++ Lectures

ALGORITHM

The word "Algorithm" or "Algorism" in some other writing versions, comes from the name Al-Khwārizmī (c. 780-850), a Persian mathematician, astronomer, geographer and a scholar in the House of Wisdom in Baghdad, whose name means "the native of Kharazm", a city that was part of the Greater Iran during his era and now is in modern day Uzbekistan.

He wrote a treatise in Arabic language in the 9th century, which was translated into Latin in the 12th century under the title Algoritmi de numero Indorum. This title means "Algoritmi on the

numbers of the Indians", where "Algoritmi" was the translator's Latinization of Al-Khwarizmi's name.

Al-Khwarizmi was the most widely read mathematician in Europe in the late Middle Ages, primarily through his other book, the Algebra.

Page 103: c++ Lectures

Algorithm

A procedure for solving a problem in terms of the 1- actions to execute and the 2 - order in which these actions execute is called an algorithm.

Page 104: c++ Lectures

PSEUDOCODE

Pseudocode (or "fake" code) is an artificial and informal language that helps programmers develop algorithms without having to worry about the strict details

of C++ language syntax.

Page 105: c++ Lectures

FLOWCHART

Flowcharts is showing algorithm using “special” figures

Page 106: c++ Lectures

FLOWCHART vs PSEUDOCODE

Page 107: c++ Lectures

Decision

Page 108: c++ Lectures

Decision

Page 109: c++ Lectures

LOOP

Page 110: c++ Lectures

LOOP

Page 111: c++ Lectures

Functions

Functions (or subroutines, or sub programs) are named chunks of logic that do something.

We break our big problem into many smaller problems that can be easily solved. These become our functions. We then use

these functions to solve the big problem.

You can read as many books about repairing cars as you like, but until you actually do it, you won't see the value of the written

advice. Practice and enjoy, and be kind to yourself, it can be very frustrating.

Page 112: c++ Lectures

Array

An array is a data type that saves multiple variables with same type through a single name by use of an index.

An index is an integer parameter with use of the subscript operator ([]).

In C++ index begins with 0 and finishes with size of array – 1 elements.

Index is used to assign to ith-1 element of array.

Its structure is :data_type name_of_array [size_of_array];

Page 113: c++ Lectures

Array

Page 114: c++ Lectures

Initialize

If a variable or an array is global, then by default C++ initializes it to zero. (In the case of arrays, C++

initializes every element to zero.)

But local variables not initialized contain random values (garbage).

Page 115: c++ Lectures

Why zero based indexing?

Many other languages use 1-based indexing.

But all programs, regardless of what language they are written in, must ultimately be translated into machine language, which is what the CPU actually executes.At the machine level, array indexing is handled through offsets. One register (a memory location on the CPU itself) contains the address of an array—actually,

the address of the first element. Another register contains an offset: the distance to the desired element.

To get the element with index I, do this:address of element I = base address + ((I – 1) * size of each element)

address of element I = base address + (I * size of each element)

Even though it results in only a slight saving of CPU cycles, it’s very muchin the spirit of C-based languages to use this approach, because it is closer to

what the CPU does.

Page 116: c++ Lectures

DEFINE

You can work with any number of values, simply by changing one setting in the program.

You can do this with a #define directive near the beginning of the code. This directive instructs the compiler to replace all occurrences of a

symbolic name (in this case, "VALUES") with the specified text.

For example, first put the following directive at the beginning of the code:#define VALUES 5

Then use the symbolic name VALUES throughout the program, wherever the program refers to the number of possible values. For example, you’d

declare the hits array as follows:int hits[VALUES];

Page 117: c++ Lectures

Array of strings

Page 118: c++ Lectures

Out of range

C++ doesn’t stop you. Instead, the operation proceeds at the memory location where array[5] or a[4] would be if it existed. The result is that a piece of data outside of the array is overwritten. This can

create bugs that are difficult to track down.

If there is an array of 4 elements (a[4]). a[0] = 0, a[1] = 1, a[2] = 2, a[3] = 3

What will happen if try to print a[5] or a[4]?

Page 119: c++ Lectures

Multidimensional array

Page 120: c++ Lectures
Page 121: c++ Lectures

VECTOR

Vector are implemented as dynamic arrays. Vector have their elements stored in contiguous storage and can be accessed as in arrays. Vectors have one important advantage with respect to arrays in

C++ vectors can be resized during the execution of the program to accommodate extra elements as needed.

Its structure is vector<data_type> name_of_vector; OR vector<data_type> name_of_vector (size);

Note: to use vector there must be #include <vector> in code

To resize vector size programmer can use functions resize(size), push_back(new_element).

Also by using Standard Library for vector there are ready functions, which makes easy programming.

Page 122: c++ Lectures
Page 123: c++ Lectures

Using file

Page 124: c++ Lectures

Using file

Page 125: c++ Lectures

CS 201 “C++ programming language”Suleyman Demirel University

Midterm project

In midterm student must implement definite algorithm (given below) in explanation view. Here you can download bubble sort prepared specially for students.

Do not use arrays instead use vector, queue (STL library).

Student must send project to 1 – lecturer email [email protected]

2 – to his/her instructor

Also student makes oral defence to his/her instructor

List of topicsGraph algorithms

1) Coloring algorithm: Graph coloring algorithm. 2) Topological sort: finds linear order of nodes (e.g. jobs) based on their dependencies.

3) Ford–Fulkerson algorithm: computes the maximum flow in a graph 4) Karger's algorithm: a Monte Carlo method to compute the minimum cut of a connected graph

Minimum spanning tree

5) Kruskal's algorithm 6) Prim's algorithm

Shortest path problem

7) Bellman–Ford algorithm: computes shortest paths in a weighted graph (where some of the edge weights may be negative)

8) Dijkstra's algorithm: computes shortest paths in a graph with non-negative edge weights 9) Floyd–Warshall algorithm: solves the all pairs shortest path problem in a weighted, directed graph

Sorts

10)Quicksort

11)Merge sort

12)Heap sort

Substrings

13)Aho–Corasick string matching algorithm: trie based algorithm for finding all substring matches to any of a finite set of strings

14)Boyer–Moore string search algorithm: amortized linear (sublinear in most times) algorithm for substring search

15)Knuth–Morris–Pratt algorithm: substring search which bypasses reexamination of matched characters

Page 126: c++ Lectures

Geometry

16)Closest pair problem: find the pair of points (from a set of points) with the smallest distance between them 17) Find intersections of two lines18) Collision detection algorithms: check for the collision or intersection of two given solids 19) Graham scan : convex hull algorithms: determining the convex hull of a set of points

Number theoretic algorithms

20)Extended Euclidean algorithm: to solve the equation ax+by=c.

Computation of π:

21)Gauss–Legendre algorithm: computes the digits of pi

Matrix multiplication

22)Strassen algorithm: faster matrix multiplication

Solving systems of linear equations

23)Gaussian elimination

Root finding

24)Newton's method: finds zeros of functions with calculus

Asymmetric (public key) encryption

25)RSA

Hash

26)Hash function: convert a large, possibly variable-sized amount of data into a small datum, usually a single integer that may serve as an index into an array

Permutations

27)Fisher–Yates shuffle (also known as the Knuth shuffle): randomly shuffle a finite set

Pseudorandom number generators

28)Linear congruential generator

Traveling salesman problem

29)Christofides algorithm

Subsequences

30)Longest common subsequence problem: Find the longest subsequence common to all sequences in a set of sequences (Dynamic programming)

Page 127: c++ Lectures

Integer factorization: breaking an integer into its prime factors

31)Dixon's algorithm 32)Fermat's factorization method

BonusMax 2 points – Student draws flowchart of program.

Max 4 points – Students makes a video clip of algorithm.Max 4 points – Student makes GUI of program.

Student can use GUI libraries of C++ like (or try others):

1) Fast Light Toolkit (FLTK) www.fltk.org FLTK is a cross-platform C++ GUI toolkit for Linux, Microsoft Windows, and MacOS.

2) The GTK+ Project www.gtk.org GTK+, or the GIMP Toolkit, is a multi-platform toolkit for creating graphical user interfaces. Offering a complete set of widgets, GTK+ is

suitable for projects ranging from small one-off tools to complete application suites.3) wxWidgets www.wxwidgets.org is a C++ library that lets developers create applications

for Windows, OS X, Linux and UNIX on 32-bit and 64-bit architectures as well as several mobile platforms including Windows Mobile, iPhone SDK and embedded GTK+.

4) SmartWin++ smartwin.sourceforge.net is a 100% free C++ GUI and SOAP library for developing Windows applications both on Desktop, Pocket PC, Windows Mobile or Windows

CE based systems

Page 128: c++ Lectures

PL C++ Lecture 1

Page 129: c++ Lectures

C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating 

system.

C++ was written by  Bjarne Stroustrup  at Bell Labs during 1979-1985. C++ is an extension of C.  Prior to 1983, Bjarne Stroustrup added features to C and formed what he called "C with Classes". The term C++ was first used in 1983.

History of C and C++ PL

http://www.cs.bell-labs.com/who/dmr/

http://www2.research.att.com/~bs/homepage.html

Page 130: c++ Lectures

C and C++ difference

C++ is a general –purpose programming language with a bias towards systems programming that

• is a better C;• supports data abstraction

• supports object-oriented programming• supports generic programming

Note: Most things can be done (may be done) also in C, but it will take a century of time

Note 2 : Read books to learn more or google it.

Page 131: c++ Lectures

application

program

machine code

data

compiler

code

statement

source code

Page 132: c++ Lectures

Build the Program (Compile and Link)

Page 133: c++ Lectures
Page 134: c++ Lectures

First program in C++

Page 135: c++ Lectures

Introduction to Data Types

Kazakhstan

Page 136: c++ Lectures

Memory concepts

a = 5; b = 2; 

a = a + 1; result = a - b; 

Page 137: c++ Lectures

Variable always have to begin with a letter. Space, punctuation marks, symbols cannot be used.  They can also begin with an underline character (_ )Variable cannot begin with a digitUse camel case  

Another rule:Variables cannot match any keyword of the C++ language

The standard reserved keywords are:  asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto,if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register,reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while 

Giving a Good name to variable

Page 138: c++ Lectures

Fundamental data types

Name Description Size Range

char Character or small integer.

1byte signed: -128 to 127 unsigned: 0 to 255

short int (short)

Short Integer. 2bytes signed: -32768 to 32767 unsigned: 0 to 65535

Int (*) Integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295

long int (long) Long integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295

Page 139: c++ Lectures

Name Description Size Range

bool Boolean value. It can take one of two values: true or false.

1byte true or false

float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)

double Double precision floating point number.

8bytes 8bytes +/- 1.7e +/- 308 (~15 digits)

long double Long double precision floating point number.

8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t Wide character. 2 or 4 bytes

1 wide character

Page 140: c++ Lectures

int a; float mynumber; 

int a, b;  same meaning as:  int a; int b; 

int a = b = 3;

Declaration

Page 141: c++ Lectures

The integer data types char, short, long and int can be either signed or unsigned

unsigned short int a1;  signed int s2; 

int s2  with exactly the same meaning (with or without the keyword signed)

 The following two variable declarations are equivalent:  short Year;   ==  short int Year; 

The following two declarations are equivalent:  unsigned NextYear;    ==    unsigned int NextYear;

Page 142: c++ Lectures

Do not sleep on PL lecture!!!

Sleep in canteen!!!

To be continued. Wait for updates

Page 143: c++ Lectures

Taking information int a; cin >> a;

There is also usage of cin to request more than one datum input from the user: cin >> a >> b; is equivalent to: cin >> a; cin >> b;

Page 144: c++ Lectures

The assignment operator assigns a value to a variable. a = 5;

The most important rule when assigning is the right-to-left rule: The assignment operation always takes place from right to left, and never

the other way: a = b; (NOTE: what will be result here a=b=c=d=3; )

This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue). The value that was stored until this moment in a is not considered at all in this operation, and in fact that value is lost.

Assignment (=)

a = 2 + (b = 5); is equivalent to: b = 5; a = 2 + b;

that means: first assign 5 to variable b and then assign to a the value 2 plus the result of the previous

assignment of b (i.e. 5), leaving a with a final value of 7.

Page 145: c++ Lectures

Arithmetic operators

Page 146: c++ Lectures

Rules of Operator Precedence

Page 147: c++ Lectures

C++ was written by  

B – Dennis Ritche 

D – John Davis 

A - Bjarne Stroustrup

C – Andrey Stepanov

Page 148: c++ Lectures

D – supports object-oriented programming

A - supports data abstraction

C – supports function overloading

Which is not difference between C and C++  

B – supports generic programming

Page 149: c++ Lectures

What will be result

int b, x = b = 1;x = (2 + x) + (x = b = 5);

B – 8

D – compilation error

A - 4

C – 12

Page 150: c++ Lectures

THANKS.

Page 151: c++ Lectures

PL C++ Lecture 2

Page 152: c++ Lectures

Bool data typeBool data types can take only 2 values true or false. Also in C+ 

bool data types false is equal to 0 and true is equal to 1.

Page 153: c++ Lectures

Char data typeIn C++ char data type is used for a single character.  There are standard  characters like upper and lower case letters of English alphabet, the digit

s '0'..'9' and some special symbols such as *, @, !, etc. Collection of characters is ASCII. Characters are represented as integers. 

(char is a subset of int). For example, in ASCII '9' is decimal 57 and 'A' is decimal 65. 

char c='a' works fine, but char c=“a”; is compilation error. 

Page 154: c++ Lectures

ScopeA variable can be either of global or local scope. 

 If there is same name for global and local variable “::” keyword is used for global. 

Page 155: c++ Lectures

ConstConstant variables are variable with fixed value and cannot be changed. 

Its structure is const data_type name_of_variable = value; 

Note: constant variables must be initialised.

Page 156: c++ Lectures

Escape codesIn C++ there are escape codes, which are used to express more additional

symbols or actions. Its structure consists of “\” sign and letter.

\n newline \t tab\' single quote (') \a alert

e.t.c

Page 157: c++ Lectures

EnumThe enum keyword can be used to create a series of symbolic names

(symbols) each with a constant integer value. Its structure is enum name { symbol_decls };

For enumerated constants rock, paper, scissors and gives them the values 0, 1, and 2.

enum Choice{rock, paper, scissors};

Page 158: c++ Lectures

Integer vs Double

- The range of double is much greater than integer.- Double can also store fractional portions of a number.- Double use more taxing on computer resources.- In double rounding errors an occur.

Page 159: c++ Lectures

Type castingThere are 2 ways:

answer = (double) (numerator) / denominatoranswer = static_cast<double>(numerator) / denominator 

Page 160: c++ Lectures

Everyday we make choice. Or think that we make it.

Page 161: c++ Lectures

if and if-else

Page 162: c++ Lectures
Page 163: c++ Lectures

Dangling-else problem

if ( x > 5 ) if ( y > 5 ) cout << "x and y are > 5";

else cout << "x is <= 5";

The C++ compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces

({ and }). This behavior can lead to what is referred to as the dangling-else problem.

if ( x > 5 ) {

if ( y > 5 ) cout << "x and y are > 5"; } else cout << "x is <= 5";

Page 164: c++ Lectures

(= and ==)?Mostly this type of logical error happens in if structure. Lets assume that in C++ code it is written “if (n=5) ” and “if (n==5)”. In first case number n becomes to equal to 1. In second

case number n checks with 5 and return 0 (true) or 1 (false).

Page 165: c++ Lectures

Conditional operator ?In C++ it can be used conditional operator “?” instead of if .. else

structure. Its structure is : condition ? result1 : result2;

conditional operator can be used in cout stream, which is very powerfull feature.

Page 166: c++ Lectures

Short writing operatorsMostly for short writing code compound assignment operators are used. 

For example “x = x + 5;” can be written as “x += 5;”Also for short writing code increase (++) or decrease (+) are used. 

Page 167: c++ Lectures

pre - post

Page 168: c++ Lectures
Page 169: c++ Lectures

Comparisionrelational operator meaning> x is greater than y< x is less than y>= x is greater than or equal to y<= x is less than or equal to y== x is equal to y!= x is not equal to y

Page 170: c++ Lectures

Logical operators

3 main logical operators in C++: “and” (&&), “or” (||) and “not” (!). 

Page 171: c++ Lectures

Math library

Page 172: c++ Lectures

Appendix F

Page 173: c++ Lectures
Page 174: c++ Lectures

Review 1

int a;char x= “A”;char y= “Z”;a = x – y;

A – 25 B – -25

C – 26 D – Compilation error

Page 175: c++ Lectures

1 – 1

2 – 5

3 – 9

4 – I don't know

Page 176: c++ Lectures

Why “::” symbol is used?

1 - To use standard library

2 – To use global variable

3 – To use local variable

4 – To make difference between local and global variables

Page 177: c++ Lectures

a1 = ? a2 = ?

int a=5, b=2; double a1 = static_cast<double>(a/b); double a2 = (double)(a)/b;

A – 2 2B – 2.5 2.5C – 2 2.5

Page 178: c++ Lectures

What will be output

int a=5, b=4; if (a--==b) cout<<"1";

if (a--==b) cout<<"2"; else cout <<"3";

A – 13B – 23C – 2D – Compilation error

Page 179: c++ Lectures

What will be output for 1 2 3

int a,b,c; cin >> a >> b >> c; cout << ((a>b ? ((a>c) ? c:a):(b>c ? c : b)));

A – 1 B – 2

C – 3 D – Compilation error

Page 180: c++ Lectures

#include <iostream>#include <cmath>

int main(){ int a,b,c; a = 4; b = 25; if (a = sqrt(b))

c = 1; else c = -1; std::cout<<c; return 0;}

1 – 1

2 – -1

3 – CE

4 – I don't know

What will be output?

Page 181: c++ Lectures

Process vs Result

Page 182: c++ Lectures

Thanks!!!

Page 183: c++ Lectures

LECTURE #3

Page 184: c++ Lectures

LOOPs

whiledo … while

for

Page 185: c++ Lectures

WHILEThe “while” loop's structure is : while (condition(s) is(are) true) { code }

In while loop there must be increment (decrement) operations or some checking to make condition false, otherwise it can infinite loop.

Page 186: c++ Lectures

DO … WHILEThe “do .. while” loop's structure is do { code } while (condition[s] is[are] true);

The main difference between do/while and while loops is that sometimes in do/while it can be 1 more step, because firstly it run code then checks the condition.

Page 187: c++ Lectures

FORThe “for” loop's structure is: for (initialization; condition; increase)

Page 188: c++ Lectures

STRUCTURE

Page 189: c++ Lectures

FOR vs WHILE

Page 190: c++ Lectures

BREAK

Break command is used to finish loop and exit from loop even if the loop condition is true.

Page 191: c++ Lectures

CONTINUE

The continue causes to pass rest of loop and go to next iteration.

Page 192: c++ Lectures

EXIT

The “exit” is used to terminate program even if it is not finished. It can be used when error happens in code.

Page 193: c++ Lectures

while (true){

}

INFINITE LOOPS

Page 194: c++ Lectures

Statements with “for”

for (i=0, j=1; i<=10; i=i+2, j++){

j = j+3;i++;

}

Page 195: c++ Lectures

FUNCTIONS

In C++ structure of function is:data_type name_of_function (data_type parameter_name) {}

Parameters can be used from 0 to many as needed. The paramet

ers are separated by commas (,). By parameter, function receives variable (arguments), which acts in the function

as local variable.

Page 196: c++ Lectures
Page 197: c++ Lectures
Page 198: c++ Lectures

VOID TYPEIn C++ programmer can write void type specifier in data_type for functions. Its structure is :

void name_of_function(data_type parameter_name) {}This functions with no type is used for example to print values of array, show message.

Page 199: c++ Lectures

The Basics Using Function

Page 200: c++ Lectures

Forward declarationA function prototype is a declaration of function without its implementation. Programmer declares function prototype at the top of the file to show to compiler that it will b

e used. This is called forward declaration.

If forward declaration of function is not used in code and function is written after main function then when programmer tries to use function after compiler gives error.

Page 201: c++ Lectures

EXTERNAL FUNCTIONIn C++ programmer can write a functions in other file and use them. To use external file in C+

+ code it must be included and have an extension .h. Also to include the structure must be like:#include "name_of_file.h"

Page 202: c++ Lectures

LOCAL vs GLOBAL

Page 203: c++ Lectures
Page 204: c++ Lectures

RECURSION

The technique of a function calling itself is called recursion.

The obvious problem is the same one for infinite loops.

If a function calls itself, when does it ever stop?

Page 205: c++ Lectures

GET_DIVISOR

Page 206: c++ Lectures
Page 207: c++ Lectures

INLINE FUNCTION

C++ provides inline functions to help reduce function call overheade specially for small functions. Placing the qualifier inline before a function's return type in the

function definition "advises" the compiler to generate a copy of the function's code in place (when appropriate) to avoid a function call.

12345678910111213141516

#include <iostream> using namespace std;inline double cube( const double side ) { return side * side * side; }   int main() { double sideValue; cout << "Enter n: "; cin >> sideValue;   cout << "Volume is " << cube( sideValue ) << endl; return 0; }

Enter n: 5Volume is 125

Page 208: c++ Lectures

Random Number Generation

i = rand();The function rand generates an unsigned integer between 0 and

RAND_MAX (a symbolic constant defined in the <cstdlib> header file).

To produce integers in the range 0 to 5: rand() % 6

The number 6 is called the scaling factor.

To randomize without having to enter a seed each time srand( time( 0 ) );

To produce integers in the range 10 to 15: 10 + rand() % 6

The number 10 is called the shiftingValue

Page 209: c++ Lectures

Overloading FUNCTION

Page 210: c++ Lectures

int area(int);

int area(int, int);

Page 211: c++ Lectures

A = 1, B = 3

A) 3B) -3C) CE

Page 212: c++ Lectures

OUTPUT A=2, B=3

B function x : 2function y : 3function a : 6------------------function x : 3function y : 4function a : 12------------------main x : 6main y : 12main a : 2

A function x : 2function y : 3function a : 6------------------function x : 3function y : 4function a : 12------------------main x : 6main y : 12main a : 6

C function x : 6function y : 12function a : 72------------------function x : 3function y : 4function a : 12------------------main x : 72main y : 12main a : 72

Page 213: c++ Lectures

A) CEB) 30 1 2C) 30

Page 214: c++ Lectures

int display(){cout << "Hello" << endl;return 1;}void display(int x){cout << x << endl;}void display(float x){cout << x << endl;}void display(float y, char *str){cout << y;cout << ”str” << endl;}

int main(){int z = display();display(33);display(3.2);return 0;}

A) CEB) 33 3.2C) hello 33 3.2

Page 215: c++ Lectures

Lecture 4

Page 216: c++ Lectures

ALGORITHM

The word "Algorithm" or "Algorism" in some other writing versions, comes from the name Al-Khwārizmī (c. 780-850), a Persian mathematician, astronomer, geographer and a scholar in the House of Wisdom in Baghdad, whose name means "the native of Kharazm", a city that was part of the Greater Iran during his era and now is in modern day Uzbekistan.

He wrote a treatise in Arabic language in the 9th century, which was translated into Latin in the 12th century under the title Algoritmi de numero Indorum. This title means "Algoritmi on the

numbers of the Indians", where "Algoritmi" was the translator's Latinization of Al-Khwarizmi's name.

Al-Khwarizmi was the most widely read mathematician in Europe in the late Middle Ages, primarily through his other book, the Algebra.

Page 217: c++ Lectures

Algorithm

A procedure for solving a problem in terms of the 1- actions to execute and the 2 - order in which these actions execute is called an algorithm.

Page 218: c++ Lectures

PSEUDOCODE

Pseudocode (or "fake" code) is an artificial and informal language that helps programmers develop algorithms without having to worry about the strict details

of C++ language syntax.

Page 219: c++ Lectures

FLOWCHART

Flowcharts is showing algorithm using “special” figures

Page 220: c++ Lectures

FLOWCHART vs PSEUDOCODE

Page 221: c++ Lectures

Decision

Page 222: c++ Lectures

Decision

Page 223: c++ Lectures

LOOP

Page 224: c++ Lectures

LOOP

Page 225: c++ Lectures

Functions

Functions (or subroutines, or sub programs) are named chunks of logic that do something.

We break our big problem into many smaller problems that can be easily solved. These become our functions. We then use

these functions to solve the big problem.

You can read as many books about repairing cars as you like, but until you actually do it, you won't see the value of the written

advice. Practice and enjoy, and be kind to yourself, it can be very frustrating.

Page 226: c++ Lectures

Array

An array is a data type that saves multiple variables with same type through a single name by use of an index.

An index is an integer parameter with use of the subscript operator ([]).

In C++ index begins with 0 and finishes with size of array – 1 elements.

Index is used to assign to ith-1 element of array.

Its structure is :data_type name_of_array [size_of_array];

Page 227: c++ Lectures

Array

Page 228: c++ Lectures

Initialize

If a variable or an array is global, then by default C++ initializes it to zero. (In the case of arrays, C++

initializes every element to zero.)

But local variables not initialized contain random values (garbage).

Page 229: c++ Lectures

Why zero based indexing?

Many other languages use 1-based indexing.

But all programs, regardless of what language they are written in, must ultimately be translated into machine language, which is what the CPU actually executes.At the machine level, array indexing is handled through offsets. One register (a memory location on the CPU itself) contains the address of an array—actually,

the address of the first element. Another register contains an offset: the distance to the desired element.

To get the element with index I, do this:address of element I = base address + ((I – 1) * size of each element)

address of element I = base address + (I * size of each element)

Even though it results in only a slight saving of CPU cycles, it’s very muchin the spirit of C-based languages to use this approach, because it is closer to

what the CPU does.

Page 230: c++ Lectures

DEFINE

You can work with any number of values, simply by changing one setting in the program.

You can do this with a #define directive near the beginning of the code. This directive instructs the compiler to replace all occurrences of a

symbolic name (in this case, "VALUES") with the specified text.

For example, first put the following directive at the beginning of the code:#define VALUES 5

Then use the symbolic name VALUES throughout the program, wherever the program refers to the number of possible values. For example, you’d

declare the hits array as follows:int hits[VALUES];

Page 231: c++ Lectures

Array of strings

Page 232: c++ Lectures

Out of range

C++ doesn’t stop you. Instead, the operation proceeds at the memory location where array[5] or a[4] would be if it existed. The result is that a piece of data outside of the array is overwritten. This can

create bugs that are difficult to track down.

If there is an array of 4 elements (a[4]). a[0] = 0, a[1] = 1, a[2] = 2, a[3] = 3

What will happen if try to print a[5] or a[4]?

Page 233: c++ Lectures

Multidimensional array

Page 234: c++ Lectures
Page 235: c++ Lectures

VECTOR

Vector are implemented as dynamic arrays. Vector have their elements stored in contiguous storage and can be accessed as in arrays. Vectors have one important advantage with respect to arrays in

C++ vectors can be resized during the execution of the program to accommodate extra elements as needed.

Its structure is vector<data_type> name_of_vector; OR vector<data_type> name_of_vector (size);

Note: to use vector there must be #include <vector> in code

To resize vector size programmer can use functions resize(size), push_back(new_element).

Also by using Standard Library for vector there are ready functions, which makes easy programming.

Page 236: c++ Lectures
Page 237: c++ Lectures

Using file

Page 238: c++ Lectures

Using file

Page 239: c++ Lectures

LECTURE 5

Page 240: c++ Lectures

PointerA pointer is just a variable that contains an address.

While most variables contain useful information (such as 5, 3, and 8 in this example), a pointer contains the numeric location of

another variable. A pointer is only useful as a way to get to something else.

int *p;int a = 5;p = &a; // p now points to a!

Page 241: c++ Lectures

Declaring pointers

A pointer declaration uses the following syntax:data_type *name;

int *a;double *b;float *c;

Page 242: c++ Lectures

& signThe ampersand (&) gets the address of its operand.

Programmers generally don’t care what the address is;

all that matters is that pointer contains the address of variable—that is, pointer points to variable.

int x=1;int *a;a = &x;

double b1=3.0;double *b=&b1;

Page 243: c++ Lectures

* signPointer means address of another variable.

To show value of pointed variable the dereference operator (*) is used.

Do not mix * sign with dereference operator and pointer. Dereference operator is used after pointer is declared.

int a;int *ptr1=&a, *ptr2=&a; // here * is used for pointer cin >> a;

*ptr2 = 2 * a; // here * is used as dereferencecout << "Dereference " << *ptr1 << endl;cout << "Inside " << *ptr2 << endl;

Page 244: c++ Lectures

int n;int *p = &n;

Page 245: c++ Lectures

Size of pointer

A size of pointer is 4 bytes or 8 bytes, because of architecture of computer.

It does not change up to data type of pointer.

So lets reminder again “pointer saves address of variable not its value”.

Page 246: c++ Lectures

Pointer in function

In this example nothing happens

In this example p will change to twice

Page 247: c++ Lectures

Sending pointer to function

NOTE

Page 248: c++ Lectures

Function

Page 249: c++ Lectures

Function

Pass by reference

Pass by value

Page 250: c++ Lectures

Relation between pointer and array

In C++ a pointer can be equivalent to the address of the first element of array.

This can be represented like : int a [20];int *ptr1;

ptr1 = a; // ptr1 = &a[0]

And after programmer can use arithmetics to go to next elements like ptr1++.

Note C+ compiler automatically goes to next element up to data type. This means that if array is

double then pointer goes 8 bytes.

Page 251: c++ Lectures

Pointer arithmetic

assign p the address of arr[2]p = arr + 2;

// p = &arr[2];

C++ interprets all array names as address expressions. arr[2] translates into

the following:*(arr + 2)

Page 252: c++ Lectures

Using array in function#include <iostream>using namespace std;void zero_out_array(int *arr, int n);

int main() {int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

zero_out_array(a, 10);for (int i = 0; i < 10; i++) cout << a[i] << " ";return 0;}

void zero_out_array(int *p, int n) { while (n-- > 0) { *p = 0; p++; }}

Page 253: c++ Lectures

Pointer to pointer

In C++ there is pointer to pointer which means that if there is a pointer, programmer can

make another pointer to it.

In this case add an asterisk (*) for each level of reference in declarations.

Its structure is data_type *pointer1;

data_type **pointer2 = &pointer1; and so on...

Page 254: c++ Lectures

What will be output?

#include <iostream>using namespace std;

int main(){char a='Q';double b=2.0;char *ptr1=&a; // pointer for chardouble *ptr2=&b; // pointer for double

cout << sizeof(a) << endl; // size of charcout << sizeof(ptr1) << endl; // size of pointercout << sizeof(b) << endl; // size of doublecout << sizeof(ptr2) << endl; // size of pointer}

A)1484

B)1188

C)1244

Page 255: c++ Lectures

What will be output

#include <iostream> using namespace std; int main() { int a; int *ptr1=&a, *ptr2=&a; a= 5;cout << "1- " << a << endl;cout << "2- " << ptr1 << endl;*ptr2 = 2 * a; cout << "3- " << *ptr1 << endl;return 0;}

A)1-52-53-5

B)1-5

2-0xAAF4A03-5

C)1-5

2-0xAAF4A03-10

Page 256: c++ Lectures

What will be output?#include <iostream>using namespace std;void f1(int x, int y);

int main() {int a = 2; int b = 3;

cout << "1 " << a << b;cout << endl;f1(a,b);cout << "3 " << a << b;return 0;}

void f1(int x, int y) {x = x*3;y = y*2;cout <<"2 " << x << y;cout << endl;

}

A)1 232 663 66

B)1 232 663 23

D)CE

C)1 232 663 00

Page 257: c++ Lectures

a[4] = {4,3,2,1};int x=0;

f2(a, &x);

void f2(int *p, int *n) { *n = *p; p++; *n += *p; p+=2; *n = *n + *p; p--; *n += *p;}

At the end of function

A) x = 0

B) x = 4

C) x = 7

D) x = 10;

Page 258: c++ Lectures

#include <iostream> using namespace std;

int main(){int a=5;

int *ptr1=&a; // pointer to aint **ptr2=&ptr1; // pointer to ptr1

cout << "Value1 : " << a << endl;cout << "Address1 : " << &a << endl;cout << "Value2 : " << *ptr1 << endl;cout << "Value3 : " << *ptr2 << endl;cout << "Value4 : " << **ptr2 << endl;

return 0;}

A)Value1 : 5Address1 : 0xFFAA23Value2 : 5Value3 : 5Value4 : 5

B)Value1 : 5Address1 : 0xFFAA23Value2 : 5Value3 : 0xDFA12AValue4 : 0xFFAA23

C)Value1 : 5Address1 : 0xFFAA23Value2 : 5Value3 : 0xFFAA23Value4 : 5

Page 259: c++ Lectures

C-style string

The sequences of characters (arrays of char) produces string.

A string is a sequence of characters that are interpreted as a piece of text.

To show end of characters a special character is used to signal the end: the

null character '\0' (backslash, zero).

char str[]="SDU"; char str [] = { 'S', 'D', 'U', '\0' };

This type is called C-style string. Also in C++ there is a special class <string>.

Page 260: c++ Lectures

Allocation of string

Page 261: c++ Lectures

Functions

Page 262: c++ Lectures

getline

char name[100];cin.getline(name, 99);

The getline function gets an entire line of input: All the characters input

before the user pressed ENTER. The first argument (in this case, name) specifies the

destination string.

The second argument specifies the maximum number of characters to copy; this should never be more than N–1, where N is the number of bytes allocated for the

string.

Page 263: c++ Lectures
Page 264: c++ Lectures
Page 265: c++ Lectures

Individual Characters vs. StringsC++ makes a distinction between individual characters and strings. A lot

depends on whether you use single or double quotation marks.

The expression 'A' represents a single character. During compilation, C++ replaces this expression with the ASCII value for a letter 'A', which

happens to be 65 decimal.

On the other hand, expression "A" represents a string of length 1. When C++ sees this expression, it places two bytes in the data area:

Page 266: c++ Lectures

STRTOKThere is a text : Me, myself, and I.

Suppose you want to break this into the individual substrings separated bycommas and spaces (delimiters).

MeMyself

andI

1 way - by search2 way - use the strtok function (string token) from the C++ standard library.

There are two ways to use this function.

Page 267: c++ Lectures

The first time you use strtok, specify both the source string and the delimiter characters; strtok returns a pointer to the first

substring (that is, token) it finds.For example:

p = strtok(the_string, ", ");

Thereafter, call strtok specifying NULL for the first argument; strtok returns the next token from this same source string. The function

remembers what source string it was working on and where it was in that string.

p = strtok(NULL, ", ");

If instead you specify source_string again, strtok starts over and returns the first token.

The return value from the function is usually a pointer to a token; but if there are no further tokens (substrings) left to read, strtok

returns NULL.

Page 268: c++ Lectures

New C++ STRING class

Page 269: c++ Lectures

Declaration in string

Page 270: c++ Lectures

Input output

Page 271: c++ Lectures

Easy way to use string

The STL string class lets you to create, copy contents (=), test for equality of contents (==), and concatenate (+) strings

without having to worry about size issues.

#include <string>using namespace std;//...string str = "SDU";for (int i = 0; i < str.size(); i++){

cout << str[i] << endl;str[i] = 'A';

}

Page 272: c++ Lectures

Appendix H STRING

Page 273: c++ Lectures

What will be output?#include <iostream>#include <string>using namespace std;int main() {char the_string[81]="Mother, don't stop me! I will go to Kaskelen", *p;

p = strtok(the_string, " ");while (p != NULL) {

cout << p << endl;p = strtok(NULL, ", ");}

}

A) Mother, don't stop me! I will go to Kaskelen

B) Mother,

don't stop me!

I will go to

KaskelenC) CE

Page 274: c++ Lectures

User enters:Arman Askarov

Almaty Orbita 3a

#include <iostream> using namespace std;

int main(){char name[100];cin.getline(name, 99);char address[10];cin >> address;cout << name << endl << address;

return 0;}

A) Arman AskarovAlmaty Orbita 3a

B) Arman AskarovAlmaty

C) Arman AskarovAlmaty Orb

Note what will happen if you write char name[10] and why?

Page 275: c++ Lectures

Difference

What is difference between cin.getline(variable) and getline(cin,variable)

a) No difference same work

b) First is used for c-style string, second for C++ string

c) First is used to read definte number of character in second for undefinite

d) For first we must use <string> library, for second <cstring> library

Page 276: c++ Lectures

Thank you!

Page 277: c++ Lectures

LECTURE 6

Page 278: c++ Lectures

Stream

A stream is something to which you can read or write data.

Flowing of water in a river — flowing from some source (for example, the console) or toward some

destination (for example, a file).

C++ provides file streams that support the functions of reading, writing to file.

Page 279: c++ Lectures

file-stream types

Page 280: c++ Lectures
Page 281: c++ Lectures

Multiple file-stream objects

To have multiple file-stream objects - open at the same time one object for each file.ofstream file_1("memo.txt");

ofstream file_2("messages.txt");

file_1 << “Say HI”;file_2 <<”Say Bye”;

Note: C++ closes the file when the program exits successfully, but it’s a good idea to close files as soon as you no longer need them.

Call the close function. This causes the program to give up ownership of the file so that some other process can access it.

out_file_1.close();out_file_2.close();

Page 282: c++ Lectures

Refer to Disk files

Note: \\ is used not \.

Page 283: c++ Lectures

Example 8.1

MAX_PATH is a a predefined constant that contains the maximum length for filenames (including the path) supported on the system.

Page 284: c++ Lectures

EOF

The amount of data stored in the file, however, is often unknown.

C++ provides a special function, eof( ), that returns nonzero (meaning TRUE) when there are no more data to

be read from an input file stream, and zero (meaning FALSE) otherwise.

Page 285: c++ Lectures

Carriage return

In text mode, each newline character (ASCII 10) is translated into a carriagereturn–linefeed pair during a write operation—and during a read, a carriage

return–linefeed pair is translated back into a newline.

Page 286: c++ Lectures

To find proper thing you must be in proper way.

Page 287: c++ Lectures

Text files vs BinaryTwo kinds of files

◗ Text files, which you read and write to as you would the console. Usually, every byte written to a text file is the ASCII code for a printable

character. ◗ Binary files, which you read and write using the actual numeric values

of the data. With this approach, ASCII translation is not involved.

For example, when you write the number 255 to a text file, the program writes the ASCII character codes for 2, 5, and 5.

file_out << 255;

But there’s another way to store data. Instead of writing the ASCII character codes for 255, you write the value 255 directly. If you then tried

to view the file with a text editor, you wouldn’t see the numerals 255. Instead, the text editor would try to show you ASCII code 255, which is

not a regular printable character.

Page 288: c++ Lectures

Difference between binary and text

◗ If a file is opened in text mode, you should use the same operations used for communicating with the

console; these involve the stream operators (<<, >>)and the getline function.

◗ If a file is opened in binary mode, you should transfer data only by using the read and write member functions. These are direct read/write

operations.

Page 289: c++ Lectures

Opening file

A binary file stream object can be opened in one of two ways.

First, you can supply a file name along with an i/o mode parameter to the constructor when declaring an object:

ifstream myFile ("data.bin", ios::in | ios::binary);

Alternatively, after a file stream object has been declared, you can call its open method:

ofstream myFile; myFile.open ("data2.bin", ios::out | ios::binary);

In order to manipulate binary files, you should always specify the i/o mode, including ios::binary as one of the mode flags.

Page 290: c++ Lectures

Reading from file

To read from binary, use the read method.

This method takes two parameters:     istream& read(char*, int);

The read member function extracts a given number of bytes from the given stream, placing them into the memory pointed to by the first

parameter.

The bytes that are read and not interpreted, the method does not assume anything about line endings, and the read method does not place a null terminator at the end of the bytes that

are read in.

Page 291: c++ Lectures

Writing to file

To write to binary, use the write method. This method takes two parameters:     ostream& write(const char*, int);

The write member function writes a given number of bytes on the given stream, starting at the position of the "put" pointer. If the put pointer is current at the end of the file, the file is extended. If the

put pointer points into the middle of the file, characters in the file are overwritten with the new

data. The bytes that are written and not interpreted, no carriage return is added after the data, and the write method does not assume there is a null terminator at the end of the bytes that are

being written.

Page 292: c++ Lectures

sizeof

returns size in bytes of the object representation of type.

sizeof( type )

Note 1. When applied to a reference type, the result is the size of the referenced type.

Note 2. The sizeof operator is often used to calculate the number of elements in an array using an expression of the form:

sizeof array / sizeof array[0]

Page 293: c++ Lectures

The moral: Know your data formats precisely before proceeding with binary I/O.

Page 294: c++ Lectures
Page 295: c++ Lectures
Page 296: c++ Lectures

What does \10\13 mean for compiler?

A) go to next line

D) show information in next line

C) user pressed tab

B) user pressed enter

Page 297: c++ Lectures

atoiThis function accepts a C-style string and converts it into an integer. For example, if "1234" is passed into

the function, it will return 1234, an integer. If the string contains a decimal place, the number will be

truncated. Eg, "104.21" will be returned as 104.

int i;char number[256];cin>>number;i = atoi (number);cout << i;

Note : if there is C++ string you must convert it.

string str;

int i = atoi(str.c_str());

Page 298: c++ Lectures

File modes

Page 299: c++ Lectures

Appendix G

Page 300: c++ Lectures

What is difference between binary and text files?

A) Binary saves in binary format, text saves in decimal format

D) For binary read, write is used. For text only fin, fout is used

C) In text file ASCII is used for each character, binary save actual numeric values

B) Text files uses fin, fout, binary files uses bin, bout.

Page 301: c++ Lectures

Command-line arguments

Page 302: c++ Lectures
Page 303: c++ Lectures

Overloading functions

Page 304: c++ Lectures

Which function is used to convert string to int?

A) <int>

D) atoi

C) toInt

B) char()

Page 305: c++ Lectures

Multiple modules

Page 306: c++ Lectures

Extern

main.cpp#include <iostream>#include "mylibrary.h"using namespace std;

int main(){

extern double pi;cout << pi;

}

mylibrary.hdouble pi=3.14;int area(int x, int y){

return x*y;}

Page 307: c++ Lectures

Exception Handling

1 - Syntax errors, which require you to fix your program code before you can successfully compile your program.2 - Program-logic errors, which you discover only after

compiling the program, running, and testing it.

3 - runtime errors (exceptions) The term refers to an occurrence at runtime that is “exceptional” because it

interrupts the normal flow of the program. The program must respond to the situation, exit, or both.

Examples include the following:Attempt to divide by zero.

Use of a null pointer in an expression that requires a valid address.

Page 308: c++ Lectures

try-catch Exception Handling

Page 309: c++ Lectures
Page 310: c++ Lectures

C++x0

C++0x is the new standard that major vendors are expected to implement in

coming years if not already.

Page 311: c++ Lectures
Page 312: c++ Lectures

What will be output.txt if main.cpp runned 2 times

main.cpp#include <fstream>#include <string>

using namespace std;

int main(){

string str="HI";ofstream fout("output.txt", ios::app);

fout << str;}

A) HI

D) CE

C) HIHI

B) nothing

Page 313: c++ Lectures

Why in binary files we must know structure of file?

A) Because we can read garbage

C) It is not so important because it can be viewed with notepad

B) Because we can rewrite on information

Page 314: c++ Lectures

Mister A wants to make her own database system in C++. And he is not crazy.

Which type is more efficient?

A - binary

B - text

Page 315: c++ Lectures
Page 316: c++ Lectures

Lecture 7

Page 317: c++ Lectures

Struct

● A structure (struct) is a more versatile data form than an array because a single

structure can hold items of more than one data type.

● This enables you to unify your data representation by storing all the related information in a single structure variable.

Page 318: c++ Lectures

Example

struct student{

char name[20];

float GPA;

int age;

}; struct student a;

student b;

// keyword struct

// not required in C++

Page 319: c++ Lectures

. signstruct student{string name;float GPA;int age;};

int main(){student a;cin >> a.name;cin >> a.GPA;cin >> a.age;// a is a structure variable of type student

cout << a.name << " " << a.GPA << endl;…..

Use the membership operator (.) to access individual members.

For example, a.name refers to the name member of the structure.

Page 320: c++ Lectures

Arrays of Structures

● It’s also possible to create arrays whose elements are structures. The technique is exactly the same as for creating arrays of

the fundamental types.

students course[100];

// array of 100 students

cin >> course[0].name;

cout << course[2].GPA << endl;

Page 321: c++ Lectures

Which of them is right?

Astruct point{double x;double y; }

Bstruct point{double x;double y; double z;}

Cstruct point{int x;int y; };

Page 322: c++ Lectures
Page 323: c++ Lectures

Object-oriented programming(OOP)

● The world of classes and objects.

● CLASS

● OBJECT

Page 324: c++ Lectures

Structure of class

A class or data declaration always ends with a semicolon.

Page 325: c++ Lectures

Private vs Public

Page 326: c++ Lectures

Private in declaration

Are not same class structuresBy default in C++ class data is private.

Page 327: c++ Lectures

Struct vs Class

In C++, the struct and class keywords are equivalent, except that members of a struct are public by default. Both keywords create

classes in C++. ● The C language has no public or private keyword, and the user of a struct type must

be able to access all members.

Page 328: c++ Lectures

Functions in class

inline function

Page 329: c++ Lectures

class Fraction {

private:

int num, den;

public:

void set(int n, int d) {num = n; den = d; }

private:

void normalize();

};

void Fraction::normalize(){

return num/den;

}

Page 330: c++ Lectures

Sometimes people can do great things, if they believe

Page 331: c++ Lectures

Great LETTERsMP

Page 332: c++ Lectures

Chapter 11

Introducing Classes:

The Fraction Class

Page 333: c++ Lectures

Greatest Common Factor

int Fraction::gcf(int a, int b) {

if (b == 0)

return a;

else

return gcf(b, a%b);

}

Page 334: c++ Lectures

Lowest Common Denominator

int Fraction::lcm(int a, int b) {

int n = gcf(a, b);

return a / n * b;

}

The LCM is the lowest number that is a multiple of both of two inputs. This isthe converse of the greatest common factor (GCF). So, for example, the LCM of

200 and 300 is 600. The greatest common factor, meanwhile, is 100.

n = GCF(a, b)LCM(A, B) = n * (a / n) * (b / n)which simplifies to the following:LCM(A, B) = a / n * b

Page 335: c++ Lectures

#include "Fraction.h"

● To include declarations from your own project files, you need to use quotation

marks: #include "Fraction.h"

Page 336: c++ Lectures

In house can be 10 doors. Success is finding open door and enter.

(Staying outside is not success)

Page 337: c++ Lectures

Constructor

The term constructor is C++-speak for an initialization class

For example for class point

point p1(0, 0); // constructor

point x; // default constructor

Page 338: c++ Lectures

Structure of constructor

Constructor must have the same name as the class, and cannot have any return

type; not even void.

Its structure is :

name_of_class(data_type parameter)

{ C++ code }

Page 339: c++ Lectures

class student

{

string name;

double GPA;

int course;

public :

student(string, int, double); // constructor

void print();

};

Page 340: c++ Lectures

Multiple Constructors (Overloading)

In class there can one and more constructors with different types or number

of parameters.

This is called overloading of constructor.

All of them must have the same name, but the compiler will call only one whose parameters match the arguments.

Page 341: c++ Lectures

class rectangle

{

int width, height;

public :

rectangle(); // with no parameters

rectangle(int); // with parameter width. Square

rectangle(int, int); // with parameters width and // height

int area();

};

Page 342: c++ Lectures

Default constructor

If there is no declaration of constructor in a class definition, the compiler assumes that the class

has a default constructor with no arguments. So programmer can declare objects of class by

simply declaring them without any arguments.

If you write no constructors, the compiler automatically supplies a default constructor for

you (which is a “no-op”). But if you write any constructors at all, the compiler does not supply a

default constructor.

Page 343: c++ Lectures
Page 344: c++ Lectures

The Copy Constructor

The copy constructor is special for two reasons.

First, this constructor gets called in a number of common situations, whether

you’re aware of its existence or not.

Second, if you don’t write one, the compiler automatically supplies one for you.

Page 345: c++ Lectures

Example

Page 346: c++ Lectures

The copy constructor uses a reference argument, as well as the const keyword, which prevents changes to an argument.

The copy constructor has this syntax:

class_name(class_name const &source)

If you don’t write a copy constructor, the compiler supplies one for you. It carries out

a simple member-by-member copy.

Page 347: c++ Lectures

class rectangle {

int width, height;

public:

rectangle();

rectangle(int);

int area();

};

rectangle r1;

rectangle r2(a);

r1 = r2; // copy c.

cout << r1.area();

Page 348: c++ Lectures

Which of them constructor for class person

A)Person();

B)void person(string);

C)person(string, string);

D)person(int person);

Page 349: c++ Lectures

Public vs private

A)No difference

B)In struct only some difference

C)Security

D)In privelegy

Page 350: c++ Lectures

person student;string n="Askar";int a=10;student.name = n; student.age = a; student.print();

A) Askar 10

B) Name : Askar Age : 10

C) CE

Page 351: c++ Lectures

LECTURE 8

Page 352: c++ Lectures

Returning object from function

class number {

public:

int x;

number add(number);

};

number a, b;number c;a.x=5;b.x=10;c = a.add(b);cout << c.x <<endl;

number number::add(number n1) {number temp;temp.x = x + n1.x;return temp;}

Page 353: c++ Lectures

Overloading operators

number a, b;number c;

c = a.add(b);

c = a + b;

Page 354: c++ Lectures

Types of overloading operators

● Unary● Binary

● IO operator

Page 355: c++ Lectures

Unary operator

● Whenever an unary operator is used, it works with one operand, therefore with the user defined data types, the operand becomes the caller and hence no arguments are required.

● ++, --, !, e.t.c

Page 356: c++ Lectures
Page 357: c++ Lectures

Binary operator

● Whenever a binary operator is used - it works with two operands, therefore with the user defined data types - the first operand becomes the operator overloaded function caller and the second is passed as an argument. This results in compulsion of receiving one argument in overloading of the binary operators.

● +, -, % e.t.c

Page 358: c++ Lectures
Page 359: c++ Lectures

IO operator

● In C++ there are overloading functions of cin and cout. This means that programmer can make class function to read data as it needs or write data

Page 360: c++ Lectures
Page 361: c++ Lectures

Public

Page 362: c++ Lectures

Private

Page 363: c++ Lectures

A Bridge From Heart To Heart : Empathy

Friend – friend – friend - friend – friend - friend – friend -

Page 364: c++ Lectures

Friend function or class

● A friend function is a function that can access the private members of a class as though it were a member of that class. In all other regards, the friend function is just like a normal function.

● Same for class

Page 365: c++ Lectures

Here x is private

Page 366: c++ Lectures
Page 367: c++ Lectures
Page 368: c++ Lectures

The Class Assignment Function (=)

The compiler-supplied operator= function is similar to the compiler-supplied copy constructor: It performs a

simple member-by-member copy.

Page 369: c++ Lectures

How should a person spend one day, one week, one month, and one year in order to perform services in the

path of (***)?

Page 370: c++ Lectures

Midterm project is waiting you!!!

And SMILE

Page 371: c++ Lectures

Dynamic Memory and theString Class

As you become more experienced with C++, you’ll find you need dynamic memory allocation. This big phrase means

you can create new data items “on the fly,”in response to the needs of the moment. Dynamic memory

gives you much more direct control over when data is allocated. It’s also an aspect of C++ inwhich there is a rich use for pointers.

Page 372: c++ Lectures

Operators new & new[]

In order to request dynamic memory we use the operator new.

Its structure is: pointer = new type

pointer = new type [number_of_elements]

int * a; a = new int [5];

Page 373: c++ Lectures
Page 374: c++ Lectures

In dynamic object

. is changed to →

number *a = new number;cout<<a->getX();

number b;cout << b.getX();

Page 375: c++ Lectures

Operator delete & delete[]

Since the necessity of dynamic memory is usually limited to specific moments within a program, once it

is no longer needed it should be freed so that the memory becomes available again for other requests

of dynamic memory.

delete pointer; delete [] pointer;

Page 376: c++ Lectures

Introducing Class Destructors

The destructor is opposite of constructor. Normally it is automatically called when an object is destroyed, either because its scope of existence has finished or because it is an object dynamically assigned and it is released using the operator delete. But programmer

can also make his destructor.

Its structure is :

~name_of_class ()

{

}

Note : in class there can be only one destructor.

Page 377: c++ Lectures
Page 378: c++ Lectures

Operator this

The keyword this identifies a special type of pointer. It is used to store the address of called

object.

Suppose that you create an object named x of class A, and class A has a nonstatic member function f(). If you call the function x.f(), the

keyword this in the body of f() stores the address of x. You cannot declare the this pointer or make

assignments to it.

Page 379: c++ Lectures
Page 380: c++ Lectures

NEXT WEEK WILL BE MIDTERM AND QUIZ FROM PRACTICE

Have you ever wondered “how often a person leaves stress behind every day?” or “how much of our privacy

are we sharing with others?”

Page 381: c++ Lectures

LECTURE #9

Page 382: c++ Lectures

One function for 2 data types

Function 1

void printData(int value)

{

cout<<value<<endl;

}

Function 2

void printData(string value)

{

std::cout<<value<<endl;

}

The codes written for two functions are almost identical. There are difference just in the type of the variable.

We have to duplicate the function for each distinct type.

Page 383: c++ Lectures

One function for 2 data types

Function 1

void printData(int value)

{

cout<<value<<endl;

}

Function 2

void printData(string value)

{

std::cout<<value<<endl;

}

The codes written for two functions are almost identical. There are difference just in the type of the variable.

We have to duplicate the function for each distinct type.

Page 384: c++ Lectures

Template

C++ templates are a powerful mechanism for code reuse, as they enable the

programmer to write code that behaves the same for data of any type.

template<typename T>

void printData(T value)

{ cout<<value<<endl; }

Page 385: c++ Lectures

Kind of templates

C++ provides two kinds of templates:

1 – function templates

search, print, sort

2 – class templates

vector, list, queue class

Page 386: c++ Lectures

Structure of function template

Function templates are implemented like regular functions, except they are prefixed

with the keyword template.

template <class T>

T max(T a, T b)

{ return a > b ? a : b ; }

Page 387: c++ Lectures

#include <iostream>using namespace std ;

template <class T>T max(T a, T b){ return a > b ? a : b ; }

int main(){

cout << "INT " << max(10, 15) << endl ;cout << "CHAR " << max('k', 's') << endl ;cout << "DOUBLE " << max(10.1, 15.2) << endl ;

}

Page 388: c++ Lectures

Structure of class template

// student.h

template <class t>

class student

{

public:

student();

void print();

} ;

// student.cpp

#include "student.h"

template <class t>

student<t>::student()

{ }

template <class t>

void student<t>::print()

{ }

In case that we define a function member outside the declaration of the class template, we must always precede that

definition with the template <...> prefix:

Page 389: c++ Lectures

#include <iostream>using namespace std;

template <class T>class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} T getmax (); };

template <class T>T mypair<T>::getmax () { return a>b? a : b;}

int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0;}

Again template must be written

Page 390: c++ Lectures

More template parameters

To define function templates that accept more than one type parameter, we specify more template

parameters between the angle brackets

template <class T, class U>

T GetMin (T a, U b)

{ return (a<b?a:b); }

int i,j; long l;

i = GetMin<int,long> (j,l);

i = GetMin (j,l);

Page 391: c++ Lectures

Find the Difference

Page 392: c++ Lectures

Template specialization

To define a different implementation for a template when a specific type is passed as

template parameter, declare a specialization of that template.

template<>class X<string>

{X(string s);

};

template<typename T>class X

{X(T x);

};

All types,except string

Page 393: c++ Lectures

Template specialization

To define a different implementation for a template when a specific type is passed as

template parameter, declare a specialization of that template.

template<>class X<string>

{X(string s);

};

template<typename T>class X

{X(T x);

};

All types,except string

Page 394: c++ Lectures

// class template:template <class T>class mycontainer { T element; public: mycontainer (T arg) { element=arg; } T increase () { return ++element; }};

// class template specialization:template <>class mycontainer <char> { char element; public: mycontainer (char arg) {element=arg;} char uppercase () { if ((element>='a')&&(element<='z')) element+='A'-'a'; return element; }};

Note : there is no "inheritance" of members from the generic template to the specialization

int main () { mycontainer<int> myint (7); mycontainer<char> mychar ('j'); cout << myint.increase() << endl; cout << mychar.uppercase() << endl; return 0;}

Page 395: c++ Lectures

Non-type parameters for templates

Besides the template arguments that are preceded by the class or typename keywords , which represent types,

templates can also have regular typed parameters (int, char, float)

template <class T, int N>class sequence { T array[N]; public: void setmember (int x, T value); T getmember (int x);};

Page 396: c++ Lectures

● From the point of view of the compiler, templates are not normal functions or classes. They are compiled on demand, meaning that the code of a template function is not compiled

until an instantiation with specific template arguments is required.

● At that moment, when an instantiation is required, the compiler generates a function specifically for those

arguments from the template.

Templates and multiple-file projects

Page 397: c++ Lectures

#include <iostream>using namespace std;

template <class T>void print (T a, int x){

for (int i=0; i<x; i++)cout << a[i] << " ";

cout << endl;}

int main () { int a[5]={1,2,3,4,5}; char c[] = "HELLO SDU"; print(a, 3); print(c, 2); return 0;}

What will be output?

A)1 2 3 4 5H E L L O S D U

B)1 2 H

C)1 2 3 H E

D)CE

Page 398: c++ Lectures

Which template declaration is false?

A - template <class T>

D - template <>

B - template <class T, class U>

C - template <class T, class U, class T>

Page 399: c++ Lectures

template <class T>class A {public: T x; T f1(){ return x*2; }};

template <>class A <double> {public: double x; double f1(){ return x*3;}};

What will be output if in main A<float> a1; A<double> a2; a1.x = 1.3; a2.x = 3.1; cout << a1.f1() << " " << a2.f1();

A)1.3 3.1

B)2.6 9.3

D)CE

C)2.6 6.2

Page 400: c++ Lectures

STL

The Standard Template Library (STL) is part of the C++ Standard Library.

Collection of algorithms, containers, iterators, and other fundamental

components to extend

STL main focus is to provide improvements implementation standardization with

emphasis in performance and correctness.

Page 401: c++ Lectures

History of STL

The C++ Standard Library incorporated part of the STL (published as a software

library by SGI/Hewlett-Packard Company). The primary implementer of the C++ Standard Template Library was

Alexander Stepanov.

Page 402: c++ Lectures

Container

A container is a holder object that stores a collection of other objects (its elements). They

are implemented as class templates, which allows a great flexibility in the types supported

as elements.

Some containers are :

dynamic arrays (vector), queues (queue),

stacks (stack), heaps (priority_queue),

linked lists (list), trees (set),

Page 403: c++ Lectures

Creating and Using a List Class

Page 404: c++ Lectures

Front & Back

push_back member function adds elements to the end (that is, the back) of

the list.

push_front member function adds elements to the front of the list.

list<string> LS;

LS.push_back("D");

LS.push_front("S");

LS.push_back("U");

Page 405: c++ Lectures

Creating and Using Iterators

Iterator is a device for stepping through a list one element at a time—that is, iterating

through it.

Iterators look and feel a great deal like pointers—especially in their use of ++, --, and * operators—even though there are

differences.

list<type>::iterator iterator_name;

Page 406: c++ Lectures

list<string> LS;

list<string>::iterator iter = LS.begin();

Page 407: c++ Lectures
Page 408: c++ Lectures

Pointers vs. Iterators

Iterators are safe and designed to be that way.

In true pointers (“raw” pointers) there is no protection against invalid memory access.

The program can attempt to increment an iterator off the end, but if it does so, nothing

drastic happens.

Page 409: c++ Lectures
Page 410: c++ Lectures

Reverse Polish Notation (RPN)

Standard calculation : 2+3

In RPN : 2 3 +

Standard calculation : (2+3) * (17-10)

In RPN : 2 3 + 17 10 - *

Page 411: c++ Lectures

60 seconds = 1 minute

60 minutes = 1 hour? years = life

Page 412: c++ Lectures

Using a Stack for RPN

Page 413: c++ Lectures
Page 414: c++ Lectures
Page 415: c++ Lectures

Correct Interpretation of Angle Brackets

Because brackets (< and >) have multiple uses in C++, ambiguity is possible when you get into heavy use of templates.

list<stack <int>> list_of_stacks; //1 example

list<stack <int> > list_of_stacks; //2 example

in first example two right-angle brackets (>>) acts as the right-shift operator, and that causes a baffling syntax error. (operator overloaded as a stream data in-flow operator with objects such as cin.)

Page 416: c++ Lectures

Which of the following is RPN

A) - 2 3 + 17 10 - *

B) 2 3 + 17 10 - * 3

C) + 2 3 - 17 10 *

D) 2 3 + 17 -

Page 417: c++ Lectures

What will be order in stack x?

stack <int> x;x.push(6);x.push(2);x.push(3);x.push(8);sort(x);

A)6 2 3 8

B)2 3 6 8

C)8 6 3 2

Page 418: c++ Lectures

#include <iostream> #include <list> using namespace std; int main(){list <int> v1;list <int>::iterator i;v1.push_back(1);v1.push_front(4);v1.push_back(10);v1.push_front(80);for (i=v1.begin(); i!=v1.end(); i++)

cout << *i << " ";return 0;}

What will be output?

A)80 4 1 10

B)1 4 10 80

C)4 80 10 1

D)CE

Page 419: c++ Lectures

Your MP is waiting for you.

original way to successfully waste your time

Page 420: c++ Lectures

LECTURE #10

Page 421: c++ Lectures

STL

The Standard Template Libraries (STL's) are a set of C++ template classes to provide common

programming data structures and functions such as doubly linked lists (list), paired arrays (map),

expandable arrays (vector), large string storage and manipulation (rope), etc.

http://www.sgi.com/tech/stl

http://www.cplusplus.com/reference/stl

Page 422: c++ Lectures

USING NAMESPACE STD;

Container types (and algorithms, functors and all STL as well) are defined not in global namespace,

but in special namespace called “std."

Add the following line after your includes and before the code begin:

using namespace std;

Page 423: c++ Lectures

Everyone in this world is unique.

Page 424: c++ Lectures

VECTOR

The simplest STL container is vector.

Vector is just an array with extended functionality.

#include <vector>

Page 425: c++ Lectures

[] vs ()

vector<int> v[10];

declare 'v' as an array of 10 vector<int>’s, which are initially empty

vector<int> v(10);

declare 'v' as an array of 10 elements

Page 426: c++ Lectures

Constructor types

vector<string> a(20, “AB”);

// fill vector a with word ”AB”

a[0]=a[1]=a[3]=....... =”AB”

vector<string> b = a;

vector<string> c(a);

// they are same

Page 427: c++ Lectures

Function at()

[] Subscripting access without bounds checking

at Subscripting access with bounds checking

Difference is function at() signals if the requested position is out of range by throwing an out_of_range

exception.

v[1] = 5;

v.at(1) = 5;

Page 428: c++ Lectures

Function size()

int elements_count = v.size();

1 - size() is unsigned, which may sometimes cause problems.

2 - Second, it’s not a good practice to compare v.size() to zero if you want to know whether the

container is empty.

bool s = (v.size() >= 0); // Try to avoid this

bool ok = !v.empty();

Page 429: c++ Lectures

Function clear()

To clear a vector use clear() member function.

It makes vector to contain 0 elements. It does not make elements zeroes (it completely erases the

container)

vector <int> v(10,2);

cout << v.size(); // answer 10

v.clear();

cout << v.size(); // answer 0

Page 430: c++ Lectures

Multidimensional vector

The simplest way to create the two-dimensional array via vector is to create a vector of vectors.

vector< vector<int> > Matrix;

To create the two-dimensional vector of given size

int N, M;

vector< vector<int> > Matrix(N, vector<int>(M, -1));

Page 431: c++ Lectures

Using vector in function

When vector is passed as a parameter to some function, a copy of vector is actually created. It may take a lot of time and memory to create new vectors

when they are not really needed.

void f1(vector<int> v) { } // Never do it void f1(const vector<int>& v) { } // OK

To change the contents of vector in the function

void f2(vector<int>& v) { } // Correct

Page 432: c++ Lectures
Page 433: c++ Lectures

pair

Pair of values : this class couples together a pair of values, which may be of different types (T1 and T2).

It is defined in <utility>. The individual values can be accessed through the public members first and

second.

pair <string,double> p1 ("ABC",3.25);

pair <string,double> p2;

p2.first = "CDE"; p2.second = 0.99;

p1 = make_pair ("XYZ", 20.0);

cout << p1.first << " = " << p1.second;

Page 434: c++ Lectures

Complex pair

pair<string, pair<int, int> > is a pair of string and two integers.

pair<string, pair<int,int> > P;

string s = P.first; // extract string

int x = P.second.first; // extract first int

int y = P.second.second; // extract second int

Page 435: c++ Lectures

Iterators

In STL iterators are the most general way to access data in containers.

vector<int>::iterator myIntVectorIterator;

begin()

end()

v.erase(v.begin()+1); // delete 2 element of vector v

Page 436: c++ Lectures

Reverse

Each container also has the rbegin()/rend() functions, which return reverse iterators. Reverse

iterators are used to traverse the container in backward order.

vector<int> v2(v.rbegin()+(v.size()/2), v.rend());

You can use function reverse()

reverse(v2.begin()+2, v2.begin()+5);

Page 437: c++ Lectures
Page 438: c++ Lectures

Algorithm

The Standard Template Library provides a number of useful, generic algorithms to perform the most

commonly used operations on groups/sequences of elements. These operations include traversals,

searching, sorting and insertion/removal of elements.

#include <algorithm> in your source when using STL algorithms

Page 439: c++ Lectures

Function find()

The find() algorithm looks for appropriate elements in an interval. If the element is found, the iterator pointing to the first occurrence of the element is

returned. Otherwise, the return value equals the end of interval

template <class Iterator, class T>

Iterator find (Iterator first, Iterator last, const T & value);

if(find(v.begin(), v.end(), 49) != v.end()) { }

Page 440: c++ Lectures

MIN & MAX

To get the value of min/max element, like in find(), use min_element(...) or max_element(...), to get

index in array subtract the begin iterator of a container or range

int v1 = *max_element(v.begin(), v.end()); // value of max

int i1 = max_element(v.begin(), v.end())–v.begin; index of max element in vector

int data[5] = { 1, 5, 2, 4, 3 };

int v2 = *min_element(data, data+5); // value of min

int i3 = min_element(data, data+5) – data; // index of min

Page 441: c++ Lectures

Function sort()

It's very easy to use.

vector<int> X;

sort(X.begin(), X.end()); // Sort in ascending order

sort(X.rbegin(), X.rend()); // Sort array in descending order using with reverse iterators

Page 442: c++ Lectures

Function insert()

Insert an element to vector by using the insert() function:

vector<int> v;

v.insert(1, 42); // Insert value 42 after the first

vector<int> v2;

v2.insert(v2.begin(), v1.begin(), v1.end());

// insert all elements of v1<

Page 443: c++ Lectures

Function erase()

function erase() has two forms. erase(iterator);

erase(begin iterator, end iterator);

At first case, single element of vector is deleted. At second case, the interval, specified by two iterators,

is erased from vector.

Page 444: c++ Lectures

next_permutation

Rearranges the elements in the range [first, last) into the lexicographically next greater permutation of

elements

vector<int> m;

m.push_back(1); m.push_back(2); m.push_back(3);

do {

cout << m[0] << " " << m[1] << " " << m[2] << endl;

} while ( next_permutation (m.begin(), m.end()));

Page 445: c++ Lectures

SET

Sets are a kind of associative container that stores unique elements, and in which the elements

themselves are the keys.

Set can add, remove and check the presence of particular element in O(log N), where N is the count

of objects in the set.

The push_back() member may not be used with set because the order of elements in set does not matter.

Page 446: c++ Lectures

set<int> s;

for(int i = 1; i <= 100; i++) { s.insert(i); // Insert 100 elements, [1..100]

}

s.insert(42); // does nothing, 42 already exists in set

for(int i = 2; i <= 100; i += 2) { s.erase(i); // Erase even values

}

int n = int(s.size()); // n will be 50

Page 447: c++ Lectures

'v2' will contain the same elements as 'v' but sorted in ascending order and with duplicates removed.

vector<int> v; v.push_back(2);v.push_back(4);v.push_back(6);v.push_back(2);v.push_back(4);

set<int> s(v.begin(), v.end()); vector<int> v2(s.begin(), s.end());

Page 448: c++ Lectures

MAP

Maps are a kind of associative container that stores elements formed by the combination of a key value

and a mapped value.

In a map, the key value is generally used to uniquely identify the element, while the mapped value is

some sort of value associated to this key. Types of key and mapped value may differ. For example, a

typical example of a map is a telephone guide where the name is the key and the telephone number is the

mapped value.

Page 449: c++ Lectures

map<string, int> M; M["S"] = 1; M["D"] = 2;

M["U"] = 10;

int x = M["S"] + M["D"];

if(M.find("U") != M.end()) { M.erase(M.find("U"));

// or M.erase("U") }

Page 450: c++ Lectures

Multiset

Multisets are associative containers with the same properties as set containers, but allowing for

multiple keys with equal values.

multiset<int> m;

multiset<int>::iterator it;

for (int i=1; i<=5; i++) m.insert(i*10);

it=m.insert(20);

for (it=m.begin(); it!=m.end(); it++)

cout << " " << *it;

Page 451: c++ Lectures

Multimap

Multimaps are a kind of associative container that stores elements formed by the combination of a key value and a mapped value with allowing different

elements to have the same key value

multimap<char,int> m1, m2;

m1.insert ( pair<char,int>('a',100));

m1.insert ( pair<char,int>('a',150));

m2.insert(m1.begin(),m1.end());

Page 452: c++ Lectures

Do not believe everything. You have brains

Page 453: c++ Lectures
Page 454: c++ Lectures

Extra functions as parameter

void f1 (int i) { cout << " " << i; }

vector<int> v(10, 2);

for_each (v.begin(), v.end(), f1);

Page 455: c++ Lectures

Extra functions as parameter

bool IsOdd (int i) { return ((i%2)==1); }

vector<int> v(4);

v[0]=2; v[1]=12; v[2]=3; v[3]=5;

vector<int>::iterator it;

it = find_if (v.begin(), v.end(), IsOdd);

cout << "The first odd value is " << *it << endl;

Page 456: c++ Lectures
Page 457: c++ Lectures

Lecture #11

Page 458: c++ Lectures

Inheritance

Inheritance allows to create classes which are derived from other classes, so that they automatically include some of its

"parent's" members, plus its own.

Page 459: c++ Lectures

class Person

{

public:

string Name;

int Age;

string GetName()

{ return Name; }

Person(string s, int n) { }

};

class BaseballPlayer : public Person

{

public:

double points;

int match;

BaseballPlayer() { }

};

BaseballPlayer c;

c.Name = "Joe";

c.match = 5;

cout << c.GetName();

Page 460: c++ Lectures

class Supervisor: public Employee {};

class Employee: public Person {};

Page 461: c++ Lectures

Holland inheritance

FatherFather

Son But not inherited

Page 462: c++ Lectures

Protected

The protected access specifier is similar to private. Its only difference occurs in fact with inheritance.

When a class inherits from another one, the members of the derived class can access the

protected members inherited from the base class, but not its private members.

Page 463: c++ Lectures

class CPolygon { protected: //not private int width, height; public: void set_values (int a, int b) { width=a; height=b;} };

class CRectangle: public CPolygon { public: int area () { return (width * height); } };

Page 464: c++ Lectures

Inheritance relationship

class A: public B;

class A: protected B;

Page 465: c++ Lectures

class A: private B;

Page 466: c++ Lectures

What is inherited from base class

In principle, a derived class inherits every member of a base class except:

its constructor and its destructor

its operator=() members

its friends

Page 467: c++ Lectures

Multiple inheritance

class C: public A, public B;

class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} };

class COutput { public: void output (int i); };void COutput::output (int i) { cout << i << endl; }

class CRectangle: public CPolygon, public COutput {public: int area () { return (width * height); }};

Page 468: c++ Lectures

Object Containment

A class can contain data of any type, including objects of other classes. There is, of course, an important

restriction: You cannot create objects of a particular class before that class is

declared.

Page 469: c++ Lectures

class Quantity {

private:

Fraction frAmount;

string units;

double x;

public:…..….};

Page 470: c++ Lectures

Polymorphism

Polymorphism enables us to "program in the general" rather than "program in the specific."

The name "polymorphism" means that something has many (poly), forms (morph). So you can have the same thing that does

something different according to the situation

A class that declares or inherits a virtual function is called a polymorphic class

Page 471: c++ Lectures
Page 472: c++ Lectures

The main difference between animals and human is that animals do their job perfectly.

Page 473: c++ Lectures

class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area () { return (0); }

};

class CRectangle: public CPolygon { public: int area () { return (width * height); } };

class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } };

Page 474: c++ Lectures

CRectangle rect; CTriangle trgl; CPolygon poly;

CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; CPolygon * ppoly3 = &poly;

ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly3->set_values (4,5);

cout << ppoly1->area() << endl; cout << ppoly2->area() << endl; cout << ppoly3->area() << endl;

Page 475: c++ Lectures

Abstract Classes and Pure virtual Functions

There are cases in which it is useful to define classes from which the programmer never intends to instantiate any objects. Such classes are

called abstract classes.

A class is made abstract by declaring one or more of its virtual functions to be "pure." A pure virtual function is specified by placing

"= 0" in its declaration

virtual void draw() const = 0; // pure virtual function

The "=0" is known as a pure specifier. Pure virtual functions do not provide implementations.

Page 476: c++ Lectures

WHY?

Page 477: c++ Lectures

class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; };

CPolygon * ppoly1 = new CRectangle(); CPolygon * ppoly2 = new CTriangle(); ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << ppoly1->area() << endl; cout << ppoly2->area() << endl;

CPolygon poly; cout << poly->area() << endl;

Page 478: c++ Lectures

Your FP is waiting for you. BONUS (3 p)

Page 479: c++ Lectures
Page 480: c++ Lectures

1. Chess2. Toguz Kumalak3. Number finding4. Steganography5. Compiler6. Tic tac toe expanded7. Database8. Archive9. Translator

Chess

Write a chess program with base class figure and derived classes king, queen, rooks, knights, bishops, pawns. You can write classes that are interconnected with each other by inheritance, like king can be derived from rook.

In constructor there must be 32 figures, which are placed in their order in board.

Write overloading input operator like a1 b2 which means from cell a1 go to cell b2. Your program must check is there any figure, is it possible to move for this figure, and is it free or there will be operation “eating”. Write overloading output operator which prints a board with figures on real time.

You can learn rules from this link : http://en.wikipedia.org/wiki/Chess

There is no need for GUI (Graphical User Interface) and AI (Artificial Intelligence)

Page 481: c++ Lectures

Toguz kumalak

То ыз малағ құ қ (toğızqumalaq, sometimes spelled toghyzqumalaq or togyzqumalaq, according to different transliterations, or toguz kumalak, "nine balls") is the Kazakh name of a mancala game also known as toguz korgool in Kyrgyz.

You can learn rules from this link : http://wikimanqala.org/wiki/To%C4%9F%C4%B1z_qumalaq

Write a program toguzkumalak with base class board and derived classes player1 and player2. Player 2 must contain AI (artificial intelligence), which means that computer must play.

Player1 class contains functions for standard playing.

Write in the constructor state as shown in picture above.

Use list not vector.

Write an overloading output operator, which prints with balls in real time.

At the end of game program must print player who wins or DRAW otherwise.

Number finding

Write a program that reads a bmp file (picture). Then check which number is drawn in it or UNKNOWN otherwise.

In bmp file there is only one digit number (between 0 and 9).

You can learn more about bmp from this link : http://www.digicamsoft.com/bmp/bmp.html or http://c-site.h1.ru/infa/bmp_struct.htm also there is a special library imagemagic (http://www.imagemagick.org/script/index.php) to read different picture files and make operations.

Use int argc, char *argv[] to read bmp file from console.

Page 482: c++ Lectures

Steganography

Steganography is the way of hiding information in picture files. (it can be also music, document files e.t.c)

Here you can learn more : http://habrahabr.ru/blogs/programming/115673

Write a program that hides and shows information in bmp file using steganogrpahy.

First program shows a choice of (a) hiding or (b)showing.

After user makes his/her choice, program ask for file.

If user asks for hiding information then user must also write a new name for bmp file.

Compiler

Write a simple C++ compiler which can check only statements, equals, if, else, variables, library.

You must use int argc, char *argv[] (command line arguments), where you write in console like: comp.exe test.cpp which means your program name and name of cpp file to compile

as output it must show line number and error and line statement like 1 no such library – #include <Istream>3 there is no such variable – a=5;6 end of statement – cout << “HI”

Note: There is no need to check loops, functions, class and OOP.

Note: Try to use STL. Use stack to check '{' and '}'

Note: In C++ the statements finish with ';'. In one line can be 1 and more statements.

Note: In C++ if there is no using namespace std then programmer must write std::cout e.t.c instead of cout.

Page 483: c++ Lectures

Tic tac toe expanded

Write a program which plays a tic-tac-toe for a matrix 20x20, where player who makes 5 lines connected wins. Lines can be connected in diagonal, horizontal, vertical straight lines.

Write C++ program which plays in optimal way to win.

Use class.

Use vector <vector > > for matrix.

Write an input overloading operator like 1 2, which means 1 column, 2 row. Write an output overloading operator for print matrix with realtime positions.

You can use x for player1 and 0 for second player.

At the end of game program must show who wins or DRAW.

Database

Write a database program with binary file for saving and deleting information.

In program there are 4 choices:create tableadd recorddelete recordselect record (show)

Each statement must finish with semicolon (;)

Page 484: c++ Lectures

Data compression

Write a program that archive of file using Huffman coding (recommended) (also there is a special library for compression http://www.zlib.net)

User enters it choices a-ZIP, b-UNZIP After user makes his/her choice, program ask for file.

Here is a link : http://stackoverflow.com/questions/1588377/compressing-a-file

Translator

Write a program that translate simple sentence from English to Kazakh (preferred) (Russian). All words of dictionary are saved in dict.txt. Sentence must be only future time. Like : I will go home. Marat and Askar will go to the SDU tomorrow.

Use STL (You can binary search tree for more speed search for words.)

You can read from file or from console (it is up to student)

If there is no such word program asks for inserting it to dictionary.

Here is a link : http://answers.yahoo.com/question/index?qid=20070827092257AAvobXY