Date post: | 11-Nov-2014 |
Category: |
Documents |
Upload: | alejandro-mendez-armada |
View: | 21 times |
Download: | 2 times |
OVERVIEW
Introduction Contact information Course description Course design Grading Policy
2
C++ Programming Language
CONTACT INFORMATION
Instructor:- Meirambek Zhaparov Kazimovich- [email protected] ENG faculty 4th floor - Office hours: by appointment
3
C++ Programming Language
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
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
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
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
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
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
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
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
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.
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
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
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
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;
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;
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.
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
What will be result
int b, x = b = 1;x = (2 + x) + (x = b = 5);
B – 8
D – compilation error
A - 4
C – 12
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.
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.
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.
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.
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
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};
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.
Type castingThere are 2 ways:
answer = (double) (numerator) / denominatoranswer = static_cast<double>(numerator) / denominator
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";
(= 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).
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.
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.
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
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
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
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
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
#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?
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.
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.
EXIT
The “exit” is used to terminate program even if it is not finished. It can be used when error happens in code.
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.
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.
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.
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"
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?
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
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
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
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
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.
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.
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.
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.
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];
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).
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.
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];
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]?
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.
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
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)
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
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
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.
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
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
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
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;
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;
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.
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
What will be result
int b, x = b = 1;x = (2 + x) + (x = b = 5);
B – 8
D – compilation error
A - 4
C – 12
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.
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.
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.
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.
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
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};
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.
Type castingThere are 2 ways:
answer = (double) (numerator) / denominatoranswer = static_cast<double>(numerator) / denominator
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";
(= 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).
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.
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.
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
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
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
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
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
#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?
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.
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.
EXIT
The “exit” is used to terminate program even if it is not finished. It can be used when error happens in code.
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.
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.
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.
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"
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?
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
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
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
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
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.
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.
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.
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.
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];
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).
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.
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];
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]?
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.
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!
Declaring pointers
A pointer declaration uses the following syntax:data_type *name;
int *a;double *b;float *c;
& 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;
* 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;
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”.
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.
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)
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++; }}
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...
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
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
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
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;
#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
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>.
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.
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:
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.
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.
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';
}
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
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?
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
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.
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();
Example 8.1
MAX_PATH is a a predefined constant that contains the maximum length for filenames (including the path) supported on the system.
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.
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.
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.
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.
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.
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.
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.
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]
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
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());
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.
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;}
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.
C++x0
C++0x is the new standard that major vendors are expected to implement in
coming years if not already.
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
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
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
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.
Example
struct student{
char name[20];
float GPA;
int age;
}; struct student a;
student b;
// keyword struct
// not required in C++
. 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.
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;
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; };
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.
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;
}
Greatest Common Factor
int Fraction::gcf(int a, int b) {
if (b == 0)
return a;
else
return gcf(b, a%b);
}
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
#include "Fraction.h"
● To include declarations from your own project files, you need to use quotation
marks: #include "Fraction.h"
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
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 }
class student
{
string name;
double GPA;
int course;
public :
student(string, int, double); // constructor
void print();
};
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.
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();
};
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.
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.
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.
class rectangle {
int width, height;
public:
rectangle();
rectangle(int);
int area();
};
rectangle r1;
rectangle r2(a);
r1 = r2; // copy c.
cout << r1.area();
Which of them constructor for class person
A)Person();
B)void person(string);
C)person(string, string);
D)person(int person);
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
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;}
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
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
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
A Bridge From Heart To Heart : Empathy
Friend – friend – friend - friend – friend - friend – friend -
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
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.
How should a person spend one day, one week, one month, and one year in order to perform services in the
path of (***)?
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.
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];
In dynamic object
. is changed to →
number *a = new number;cout<<a->getX();
number b;cout << b.getX();
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;
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.
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.
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?”
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.
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.
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; }
Kind of templates
C++ provides two kinds of templates:
1 – function templates
search, print, sort
2 – class templates
vector, list, queue class
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 ; }
#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 ;
}
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:
#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
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);
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
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
// 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;}
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);};
● 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
#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
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>
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
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.
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.
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),
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");
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;
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.
Reverse Polish Notation (RPN)
Standard calculation : 2+3
In RPN : 2 3 +
Standard calculation : (2+3) * (17-10)
In RPN : 2 3 + 17 10 - *
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.)
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 -
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
#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
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
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;
VECTOR
The simplest STL container is vector.
Vector is just an array with extended functionality.
#include <vector>
[] 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
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
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;
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();
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
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));
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
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;
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
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
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);
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
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()) { }
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
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
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<
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.
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()));
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.
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
'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());
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.
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") }
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;
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());
Extra functions as parameter
void f1 (int i) { cout << " " << i; }
vector<int> v(10, 2);
for_each (v.begin(), v.end(), f1);
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;
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.
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();
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.
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); } };
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
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); }};
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.
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
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); } };
CRectangle rect; CTriangle trgl; CPolygon poly;
CPolygon * ppoly1 = ▭ 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;
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.
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;
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)
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.
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.
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 (;)
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