Lecture 1 PythonToCppPart1
Lecture 1 PythonToCppPart1
Rasha Alkhansa
2 / 38
Why C++
3 / 38
C++ vs. Python: Compiled vs. interpreted
4 / 38
C++ vs. Python: Compiled vs. interpreted
4 / 38
C++ vs. Python: Compiled vs. interpreted—2
5 / 38
C++ vs. Python: Compiled vs. interpreted—2
5 / 38
C++ vs. Python: Static and dynamic typing
6 / 38
C++ vs. Python: Static and dynamic typing
6 / 38
C++ vs. Python: Static and dynamic typing
6 / 38
Hello world program
#i n c l u d e < iostream >
i n t main ()
{
std :: cout << " Hello ! This is my first program . " << std :: endl ;
r e t u r n 0;
}
7 / 38
Hello world program
#i n c l u d e < iostream >
i n t main ()
{
std :: cout << " Hello ! This is my first program . " << std :: endl ;
r e t u r n 0;
}
7 / 38
Hello world program — comments
// This is a line - comment preceded by comment - delimiters
#i n c l u d e < iostream > // similar ( not the same ) to import / Python
u s i n g namespace std ; // simplifies referring to objects in std
i n t main ()
{ // braces delimit code - blocks : no need for indentation
// indentation ( while not mandatory as in Python ) keeps code readable
8 / 38
Comments
9 / 38
Comments
9 / 38
Building the program
10 / 38
C++ basic types
11 / 38
Declarations
#i n c l u d e < string >
Syntax
u s i n g namespace std ; typename variablename;
i n t main () { typename variablename=initialvalue;
bool b;
c h a r c = ’h ’;
typename variablename(initialvalue);
i n t y; variablename is a string
i n t x =0;
i n t a (4) ; Starts with a character in
double d; X = {_, a, b, . . . , z, A, B, . . . , Z }
d o u b l e z =0.2; Followed by any character in X ∪ {0, 1, . . . , 9}
string s ;
string name ( " eece330 " ) ;
r e t u r n 0; }
Examples above:
First line: bool is the type, variable name is ‘b’, and we did not provide
an initial value.
Fourth line: int is the type, variable name is ‘x’, and it is initialized to 4.
12 / 38
Declarations
#i n c l u d e < string >
Syntax
u s i n g namespace std ; typename variablename;
i n t main () { typename variablename=initialvalue;
bool b;
c h a r c = ’h ’;
typename variablename(initialvalue);
i n t y; variablename is a string
i n t x =0;
i n t a (4) ; Starts with a character in
double d; X = {_, a, b, . . . , z, A, B, . . . , Z }
d o u b l e z =0.2; Followed by any character in X ∪ {0, 1, . . . , 9}
string s ;
string name ( " eece330 " ) ;
r e t u r n 0; }
13 / 38
Assignment
Syntax
#i n c l u d e < string >
u s i n g namespace std ; variablename = expression;
i n t main () { variablename must be a declared variable
// construction
string crs ( " eece330 " ) ; expression must be an expression that
// assignment
crs = " eece 331 " ; evaluates to a value of a type compatible with
i n t x; variablename
x = 1024;
r e t u r n 0; } Multi-assignment on one line is not allowed
Semantics:
Store value of expression in memory corresponding to variablename
Python assignments infer (and may change) the type associated with
variablename based on expression
C++ incompatible assignments fire error messages
int x = 20; x = "hello"; error: invalid conversion from ‘const
char*‘ to ‘int‘
14 / 38
Assignments and type casting
15 / 38
Arithmetic expressions
+, −, ∗, /, % are familiar
Shortcuts with assignment: + =, − =, ∗ =, / =
No ∗∗ exponentiation
C++ supports increment (++) and decrement (−−)
x++; is equivalent x=x+1;
y = x++; equivalent to y = x; x = x+1;
y = ++x; equivalent to x = x+1; y = x;
Decrement is similar
16 / 38
Relational operations
17 / 38
Relational operations
17 / 38
Conditional statements
Differences with Python
Parenthesis are required around expression
No colon (:)
Indentation is strongly recommended but not required
Indentation is not enough to specify a block of code
Must use open and close braces {} for conditional blocks of code of two or
more statements
In Python indentation is enough to specify a code-suite
No elif: use else if
i n t i = 0; // initialize i
w h i l e ( i < 4) { // up to four trials
cout << " Guess x (0 <x <65) : " ;
cin >> x ; // read value
i f ( x == secret ) {
cout << " you win ! " ; > ./ guess
i = 10; // force loop exit
Guess x (0 <x <65) : 32
} e l s e i f ( x < secret ) {
secret is smaller . Guess x (0 <x <65) : 16
cout << " secret is larger . " ;
secret is smaller . Guess x (0 <x <65) : 8
} else {
secret is smaller . Guess x (0 <x <65) : 4
cout << " secret is smaller . " ;
secret is smaller . you lose
}
i = i +1; // Increment i
}
i f ( i == 4) {
cout << " you lose " ;
}
19 / 38
Repetition: while loop – break statement
Statement break; breaks the innermost loop
transfers execution to line directly after loop
when x is equal to secret break exits the loop
i n t i = 0; // initialize i
w h i l e ( i < 4) { // up to four trials
cout << " Guess x (0 <x <65) : " ;
cin >> x ; // read value
i f ( x == secret ) {
cout << " you win ! " ;
b r e a k ; // Exit the loop . > ./ guess
} Guess x (0 <x <65) : 32
i f ( x < secret ) { // no need for else
secret is smaller . Guess x (0 < x <65) : 16
cout << " secret is larger . " ;
i = i +1;
secret is smaller . Guess x (0 < x <65) : 8
c o n t i n u e ; // iterate again secret is smaller . Guess x (0 < x <65) : 4
secret is smaller . you lose
} // no need for else
cout << " secret is smaller . " ;
i = i +1; // Increment i
}
i f ( i == 4) {
cout << " you lose " ;
}
20 / 38
Repetition: break with nested loops
w h i l e ( cond1 ) {
some code
w h i l e ( cond2 ) {
some code
b r e a k ; // Line A : go to Line X directly
some code
}
some code // Line X : Break from Line A leads to here
}
some code
21 / 38
Repetition: while loop – continue statement
Statement continue; continues iterating the loop
transfers execution to loop condition and ignores rest of current iteration
when x is less than secret continue ignores rest of current iteration
i n t i = 0; // initialize i
w h i l e ( i < 4) { // up to four trials
cout << " Guess x (0 <x <65) : " ;
cin >> x ; // read value
i f ( x == secret ) {
cout << " you win ! " ;
b r e a k ; // Exit the loop . > ./ guess
} Guess x (0 <x <65) : 32
i f ( x < secret ) { // no need for else
secret is smaller . Guess x (0 < x <65) : 16
cout << " secret is larger . " ;
i = i +1;
secret is smaller . Guess x (0 < x <65) : 8
c o n t i n u e ; // iterate again secret is smaller . Guess x (0 < x <65) : 4
secret is smaller . you lose
} // no need for else
cout << " secret is smaller . " ;
i = i +1; // Increment i
}
i f ( i == 4) {
cout << " you lose " ;
}
22 / 38
Repetition: for loop
The for statement has four components
Initialization statement
Control (or condition) statetement
Increment (or update) statement
Code block (delimited by braces)
Syntax
for ( init; condition; increment) { code-block }
Semantics equivalent to
init; while(condition) { code-block increment; }
i n t sum = 0;
i n t sum = 0; i = 0;
f o r ( i = 0; i < n ; i = i +1) { w h i l e (i < n) {
cin >> x ; cin >> x ;
sum = sum + x ; sum = sum + x ;
} i = i +1;
}
23 / 38
Repetition: do/while loop variant
Sometimes you would like to perform at least one iteration
Syntax
do { code-block } while (condition);
Semantics equivalent to
code-block; while(condition) { code-block }
i n t number , sum = 0;
do {
cout << " Kindly enter a number : " ;
cin >> number ;
sum = sum + number ;
} w h i l e ( number != 0) ;
cout << " Sum is : " << sum ;
24 / 38
Control and repetition one line code blocks
If you forget to provide the open and close braces with
if, else, while, for, and do-while
Only the first next line is considered to be the code-block
Indentation has no meaning or effect (other than neat readability)
Missing braces is a serious source of confusion and mistakes
Becomes worse with nested loops and conditions
Can avoid mistakes by always using open and close braces to delimit code blocks
Note: a semi-colon is counted as a statement (an empty statement)
Common mistake: inserting a semi-colon directly after the if-condition
What would be the outcome of the first code block below if we add a
semi-colon after (a==0)?
i f ( a == 0) {
i f ( a == 0)
b = 10;
b = 10;
}
25 / 38
Control and repetition one line code blocks
If you forget to provide the open and close braces with
if, else, while, for, and do-while
Only the first next line is considered to be the code-block
Indentation has no meaning or effect (other than neat readability)
Missing braces is a serious source of confusion and mistakes
Becomes worse with nested loops and conditions
Can avoid mistakes by always using open and close braces to delimit code blocks
Note: a semi-colon is counted as a statement (an empty statement)
Common mistake: inserting a semi-colon directly after the if-condition
What would be the outcome of the first code block below if we add a
semi-colon after (a==0)?
i f ( a == 0) {
i f ( a == 0)
b = 10;
b = 10;
}
i f ( a == 0)
b = 10;
c = 10; // mistake if this
// was intended inside if 25 / 38
Control and repetition one line code blocks
If you forget to provide the open and close braces with
if, else, while, for, and do-while
Only the first next line is considered to be the code-block
Indentation has no meaning or effect (other than neat readability)
Missing braces is a serious source of confusion and mistakes
Becomes worse with nested loops and conditions
Can avoid mistakes by always using open and close braces to delimit code blocks
Note: a semi-colon is counted as a statement (an empty statement)
Common mistake: inserting a semi-colon directly after the if-condition
What would be the outcome of the first code block below if we add a
semi-colon after (a==0)?
i f ( a == 0) {
i f ( a == 0)
b = 10;
b = 10;
}
i f ( a == 0) {
i f ( a == 0)
b = 10;
b = 10;
c = 10; // braces protect from
c = 10; // mistake if this
// logical mistakes
// was intended inside if } 25 / 38
Input
Object cin from iostream handles acquiring input from keyboard
operator » works with built-in types and strings objects
function get returns one character at a time
function getline returns a full line including spaces
i n t x; double d; char c;
string s ;
cin >> x ;
cin >> d ;
(Create a cpp file and test the above
cin >> c ; code with various inputs.)
cin >> s ;
getline ( cin , s ) ;
26 / 38
Input — reading from files is similar
Declare input stream of type ifstream from library fstream
“initialize it” with a file name
Alternatively use function open(filename) to open a file
use declared input stream object as you do with cin
use function eof to check for end of file
use function close when you are done reading
#i n c l u d e < fstream >
#i n c l u d e < fstream > ...
... i n t i = 0;
string line ;
ifstream ifs ( " data . txt " ) ; ifstream ifs ;
ifs . open ( " data . txt " ) ;
ifs >> x ;
w h i l e (! ifs . eof () ) {
ifs >> d ;
getline ( ifs , line ) ;
ifs >> c ; // alternatively :
ifs >> s ; // while ( getline ( ifs , line ) ) {
getline ( ifs , s ) ; cout < < " line " <<i ++ < < " : " << line ;
ifs . close () ; }
ifs . close () ;
27 / 38
Output — writing to a file
Object cout from iostream allows printing to console
Object cerr is similar but used for error messages
operator « works well with built-in types and string
string name = " John " ;
i n t yob = 1999;
d o u b l e raise = 0.12;
cout << " hello " << name << endl ;
cout << " age : " << 2019 - yob << endl ;
cout << " salary : " << (1+ raise ) *1500 << " K . L . L . " << endl ; // Allah yir7am el - lira
28 / 38
Arrays — declarations
Syntax
type variable [constantsize];
type variable [constantsize]={value_1, ...,value_n};
type variable [] = {value_1, ...,value_n};
Semantics of type variable [constantsize];
Allocate constantsize type-objects consecutively in memory
let them start at address α
Allocate memory adequate to store an address and associate it with
variable
Store α in memory associated with variable
29 / 38
Arrays — declarations, memory diagram
i n t a [4]={1 ,2 ,4 ,8}; // allocate an array and initialize it
c h a r c [8]={ ’h ’ , ’e ’ , ’l ’ , ’p ’ , ’ \0 ’ }; // partial in itializat ion
d o u b l e d [] = {1.2 , 2.6 , 3.8}; // infer size from init - list
string s [2]; // allocate two consecutive strings
cout << " addres of a : " << a << endl ;
cout << " size of a : " << s i z e o f ( a ) << " bytes " << endl ;
cout << " size of c : " << s i z e o f ( c ) << " bytes " << endl ;
cout << " size of d : " << s i z e o f ( d ) << " bytes " << endl ;
name a
value α 1 2 4 8
address α
30 / 38
Arrays — indexing
a[i] on the right hand side (read-operation)
Example: target = (a[i] + x)/2;
returns the value of the i th element of array a
eventually returns the value at address a + (i ∗ sizeof (type))
where type is the type of a’s elements
a[i] on the left hand side (write-operation)
Example: a[i] = (x+y)/2;
store the value of the right hand side expression in the i th element of a
eventually store at address a + (i ∗ sizeof (type))
31 / 38
Arrays — using arrays with a size variable
Typically we allocate a fixed size array
We need to book-keep the number of used elements
The fixed size is typically described as the capacity
The number of used elements is typically described as size
c o n s t i n t CAPACITY =16; // constant used to specify array size
i n t a [ CAPACITY ]; // pre - allocate CAPACITY elements
i n t size =0; // book - keep number of used elements in a
cout << " How big is your set ? " ;
cin >> size ;
i f ( size > CAPACITY ) {
cerr << " set is bigger than fixed size array of 16 elements " << endl ;
} e l s e { // read the elements from the user
i n t i = 0;
w h i l e ( i < size ) {
cout << " Enter element : " ;
cin >> a [ i ];
i = i +1;
}
}
32 / 38
Declaration modifiers — optional
C++ allows modifiers for declarations as follows
unsigned modifies the numeral to be non-negative
short modifies the numeral to use only two bytes
long extends the size of the numeral to more bytes depending on the
machine
long long extends the size of the numeral to be the largest supported
numeral on the platform (typically 8 bytes)
#i n c l u d e < iostream >
#i n c l u d e < string >
u s i n g namespace std ;
> g++ -o a modifiers . cpp
i n t main () {
i n t x = -5; > ./ a
long i n t y;
long long i n t z; int :4
s h o r t i n t s; long int :8
u n s i g n e d i n t ux = -5;
cout << " int : " << s i z e o f ( x ) << endl ; long long int :8
cout << " long int : " << s i z e o f ( y ) << endl ; short int :2
cout << " long long int : " << s i z e o f ( z ) << endl ;
cout << " short int : " << s i z e o f ( s ) << endl ; int x : -5
cout << " int x : " << x << endl ; unsigned int ux :
cout << " unsigned int ux : " << ux << endl ;
4294967291
}
r e t u r n 0;
33 / 38
Interlude: Binary Representation
For example, 284 (in base 10) is read as 2 × 102 + 8 × 101 + 4 × 100 .
34 / 38
Interlude: Binary Representation
35 / 38
Bitwise operators
36 / 38
Shift operators
37 / 38
Bitwise and shift operators to control bits
Set the i th bit in an integer
Perform a bitwise or with a number of all zeros and 1 at i th bit
Create that number (mask) using the left shift operator
To reset (set to 0)
Perform a bitwise and with a number of all ones and 0 at i th bit
Create that number (mask) using the left shift operator and bitwise not
38 / 38