note2-CPP Programming Review
note2-CPP Programming Review
Algorithms
C++ Programming Review
1
Outline In the lecture, we won’t cover each page
but these are good reference for you.
n Standard Libraries
n Basic Data Types
n Arithmetic, Bitwise, Logical Operators
n Control Structures
n Pointers
n Arrays
n Composite Structures
n Parameter Passing in Functions
n Standard I/O
n Pseudo Code
n Suggestion for Good Programming Practice
2
Let us start from an example (1)
#include <cstdio> Header file
4
Example 2 (self-defined header file)
5
Main Function
n There are two declarations of main that must be allowed:
n int main() // without arguments
n int main(int argc, char** argv) // with arguments
n The return type of main must be int.
n Return zero to indicate success and non-zero to indicate failure.
n You are not required to explicitly write a return statement in main(). If
you let main() return without an explicit return statement, it's the same
as if you had written return 0;.
n int main() { } // equivalent to the next line
n int main() { return 0; }
n There are two macros, EXIT_SUCCESS and EXIT_FAILURE, defined
in <cstdlib> that can also be returned from main() to indicate success
and failure, respectively.
6
Command Line Arguments
nC:\> assign1.exe dat1.txt data2 … xxx
Where’s the
location of
your Your compiled program 1st argument 2nd argument … nth
compiled
program? argv[0] argv[1] argv[2] … argv[n]
… argv: value
}
7
Example 3
8
Command Line Arguments
int main(int argc, char *argv[]) {
printf(“argc = %d\n”, argc);
for (int i = 0; i < argc; i++)
printf("argv[%d] = %s\n", i, argv[i]);}
argc = 3
argv[0] = ex1_2.exe //name of the program
argv[1] = 123 //string, not integer
argv[2] = abc
9
The Building Process
C Source Programs C Source Headers
(.cpp) (.h)
.o object Compilation
.a archive Compile time errors:
.obj object (MS) e.g. syntax errors
Object Files/Libraries
.lib library (MS)
(.o, .a, .obj, .lib)
.so shared object
.dll dynamic-link library (MS)
(Static) Linking
Runtime errors:
Dynamic Linking e.g. stack overflow,
in Runtime null pointer exception,
10
array out of boundaries
Common Standard Library Header
n <cstdio>
n Standard I/O facilities: printf(), scanf(), getchar(),
fopen(), fclose(), etc
n <cstdlib>
n Standard utility functions: malloc(), free(), rand(), etc
n <cstring>
n String functions: strcpy(), strcmp(), memset(), etc
n <iostream>
n Perform both input and output operations with the
stream objects: cin and cout
11
Comments
/* Block comment 1 */
/*
* Block comment 2
*/
// Line comment
12
Primitive Data Types in C++
Data type Size Interpretation/representation Range of values
(byte)
bool 1 Boolean (not available in C) false or true
char 1 signed number (2’s complement) -128 to 127
unsigned char unsigned number 0 to 255
int signed number (2’s complement) -231 to 231-1
4
unsigned int unsigned number 0 to 232-1
short signed number (2’s complement) -215 to 215-1
2
unsigned short unsigned number 0 to 216-1
long signed number (2’s complement) -231 to 231-1
4
unsigned long unsigned number 0 to 232-1
long long signed number (2’s complement) -263 to 263-1
unsigned 8
unsigned number 0 to 264-1
long long
4 IEEE 32-bit floating point number ±1.4´10-45 to ±3.4´1038
float
8 IEEE 64-bit floating point number ±5´10-324 to
double ±1.798´10308
pointer 4 memory address 0 to 232-1
13
Operators in C++
Operator Symbol Description
Assignment =
Arithmetic +, -, *, /, %
Increment, ++, --
decrement
Unary minus -
Comparison ==, !=, <, <=, >, >=
Logical !, &&, ||
Bitwise ~, &, |, ^, <<, >>
insertion, cout << s insertion to an output stream
extraction cin >> i extraction from an input stream
Member and x[i] subscript (x is an array or a pointer)
pointer *x indirection, dereference (x is a pointer)
&x reference (address of x)
x->y structure dereference
(x is a pointer to object/struct; y is a member of the
object/struct pointed to by x)
x.y structure reference (x is an object or struct; y is a
member of x)
14
Use of Variables
n Declaration
n Given an identifier (variable name), you specify the
data type of it and hence implicitly reserve the
required memory space.
n Initialization
n Variables should be initialized before being used.
int a;
cout << a; // prints dummy value
15
Arithmetic Operators
nAddition
int a, b, c;
a = 1;
b = 2;
c = a + b;
printf(“%d\n”, c);
18
Arithmetic Operators
nRemainder (Modulus Operator)
int a, b, c;
a = 5;
b = 2;
c = a % b;
printf(“%d\n”, c);
=
nLogical OR c 00000111
int a, b, c;
a = 5;
b = 3;
c = a || b;
printf(“%d\n”, c);
20
Bitwise & Logical Operators
nBitwise AND
int a, b, c; a 00000101
a = 5;
AND
b = 3;
c = a & b; b 00000011
printf(“%d\n”, c);
=
nLogical AND c 00000001
int a, b, c;
a = 5;
b = 3;
c = a && b;
printf(“%d\n”, c);
21
Bitwise Operators
nExclusive OR
int a, b, c; a 00000101
a = 5;
b = 3; XOR
c = a ^ b; b 00000011
printf(“%d\n”, c);
=
nWhen to use it? c 00000110
22
Bitwise Operators
nLeft Shift (x2)
int a, b; a 00000101
a = 5;
b = a << 1;
printf(“%d\n”, b); b 00001010
23
Variable Assignments
nExample 1
int a, b, c;
a = b = c = 5;
printf(“%d\n”, a);
nExample 2
int a = 5, b = 5, c = 5;
a = b == c;
printf(“%d\n”, a);
nExample 2 - Explicit
int a;
float b = 10.5;
a = (int) b; // still precision loss but NO warning
printf(“%d %f\n”, a, b); // 10 10.5
25
Typecasting
nExample 3
int a = 3;
int b = 2;
int c = 4;
cout << a / b * c << endl; // output is 4 !!
cout << a * c / b << endl; // output is 6
27
If-then-else
n? : (ternary operator)
nequivalent to if-then-else
nexpression ? true instruction : false instruction;
if (a < b)
min = a;
else
min = b;
min = a < b ? a : b;
28
For-Loop and While-Loop
n for-loop and while-loop are interchangeable
initialization;
while (loop_test) {
//loop-body
loop_counting;
}
29
Jump Statements
n Jump statements allow the early termination of loops
30
Breaking Out Loops Early
while (…) {
…
if (…) continue; //to skip the rest part of current iteration,
//and continue for next iteration
…
}
31
Bad Styles of Loop
// DON’T use != (Not equal) to test the end of a range
for (i = 1; i != n; i++) {
//loop body
}
// How does the loop behave if n happens to be zero or negative?
// DON’T modify the value of the loop-counter inside the loop body of a for-loop.
for (i = 1; i <= n; i++) {
//main body of the loop
if (testCondition)
i = i + displacement;
int func(…) {
…
if (…) return 0; //to break out the function, and
//return a value to the calling function
…
}
33
Breaking Out Programs Early
void func(…) {
…
if (…) exit(0); //to terminate the program, and
//return normal exit value 0 to operating
… //system!
}
int main(…) {
…
if (…) exit(1); //to terminate the program, and
//return abnormal exit value 1 to
… //operating system!
return 0; //normal completion of the program
34
}
Loop Design
n Find the maximum value in an array of integers.
n Any mistake in this program?
35
Pointers and Arrays
36
Note: The actual size of integers and
Pointers pointers are 4-byte long
00101 ?????
a: value of a (i.e. 5)
2 000 ???
&a: address of a (i.e. 0xFF00)
*a: ? a 0xFF00 p 0xFF04
a = &x;
b = &y;
printf(“%d %d %d %d\n”, x, y, *a, *b); 1 2 1 2
c = a; // swap a with b
a = b;
b = c;
printf(“%d %d %d %d\n”, x, y, *a, *b); 1 2 2 1
38
Creation of Array
1
1 int a[5];
????? ????? ????? ????? ?????
a[0] = 5; ??? ??? ??? ??? ???
a[1] = 8;
a[2] = 3; a 0xFF00 0xFF04 0xFF08 0xFF0C 0xFF10
a[3] = 6;
2 a[4] = 9; 2
1 H e l l o \0
p 41
0xFF06
2D Arrays
Multi-dimensional arrays are mapped to
int a[2][3]; //2 rows, 3 columns the linear address space of the
computer system.
45
Typedef
nTo rename a type to a new name
typedef int NUM;
int func(int x) { NUM func(NUM x) {
return x*x; return x*x;
} equivalent }
int main(…) { int main(…) {
int a, b; NUM a, b;
a = 1; a = 1;
b = func(a); b = func(a);
… …
} }
46
Structures
nTo define a composite structure
struct name{
data_type1 member1;
data_type2 member2;
…
};
47
Structure weight price
6 4.0
1
struct Product{ orange 0xFF00
int weight;
float price; 5 3.5
2
}; apple
0xFF08
int main(…) {
1 Product orange = {6, 4.0}; A structure can be initialized by
Product apple; using {}
apple.weight = 5; Or use the . (dot) operator to
2 apple.price = 3.5; access the member of a
printf(“%d\n”, apple.weight); structure
…
} 48
Pointer to Structure weight price
6 4.0
1
struct Product{ orange 0xFF00
int weight; 0xFF00 3
float price;
2 ????
}; p
0xFF08
int main(…) {
1 Product orange = {6, 4.0};
2 Product *p; Use the arrow -> operator to
3 p = &orange; access the member of pointer-
printf(“%d\n”, p->weight); to-structure
printf(“%d\n”, (*p).weight);
…
} 49
Parameter Passing in
Functions
50
Parameter Passing in Functions
n Pass by value
n Involve copying the value of parameters
n Pass by pointer
n Just pass the address of the parameters, without copying the
value of them
n Usually used in passing large-size data structures, e.g. arrays,
structures, objects, lists, etc
n Pass by reference
n C++ reference is similar to pass-by-pointer but without the
hassles of pointers’ (&)reference/ (*)dereference syntax
n You can specify a formal parameter in the function signature as
a reference parameter
51
Pass by Value
void plus_one(int x, int y) {
x++; y++;
}
int a = 5, b = 3;
plus_one(a, b);
6 4
5 3 5 3
int a = 5, b = 3; addresses
plus_one(&a, &b);
6 4
01 04
5 3 0xFF 0xFF
int a = 5, b = 3;
plus_one(a, b);
6 4
01 04
5 3 0xFF 0xFF
r = 4;
printf(“%d %d\n”, i, r);
// output: 4 4
55
Reference vs. Pointer
1. Pointers can point nowhere (NULL), whereas reference always
refers to an object.
2. References must be initialized as soon as they are created.
3. A pointer can be re-assigned any number of times while a
reference cannot be re-seated after binding.
4. You cannot take the address of a reference like what you can do
with pointers. Any occurrence of its name refers directly to the
object it references.
5. There is no reference arithmetic but you can take the address of an
object pointed by a reference and do pointer arithmetic on it
(because of #4).
56
Pseudo Code
n We need a language to express program development
n English is too verbose and imprecise.
n The target language, e.g. C/C++, requires too much details.
n Pseudo code resembles the target language in that
n it is a sequence of steps (each step is precise and unambiguous)
n it has similar control structure of C/C++
n Pseudo code is a kind of structured English for describing algorithms. It allows the
designer to focus on the logic of the algorithm without being distracted by details of
language syntax.
x = max{a, b, c} x = a;
if (b > x) x = b;
if (c > x) x = c;
n Problem:
n Given an m×n matrix, determine if there exists one or more saddle
points.
58
Pseudo Code Solutions
// high-level pseudo code solution
for each row {
j = index of the smallest element on row i;
if (A[i][j]) is the largest element in column j)
A[i][j] is a saddle point;
}
59
Suggestions for Good Style
n Use informative and meaningful variable names
n Insert useful comments (i.e. assertions) in the source program
n Format the source file with proper indentation of statements and align the braces so
that the control structures can be read easily
n Do not use goto statement, especially backward jump
n Use single-entry single-exit control blocks, or at most one break statement inside a
loop
n Avoid ambiguous statements e.g. x[i] = i++;
n Minimize direct accesses to global variables, especially you should avoid modifying
the values of global variables in a function
n Always make a planning of the program organization and data structures before start
writing program codes
n Should avoid using the trial-and-error approach without proper understanding of the
problem to be solved
n Avoid side effects (see example in next page)
60
Standard Input / Output
61
cin & cout
n Default input/output stream objects
n A stream is a sequence of bytes (characters)
that can be read from or written to
n cin is a stream on the keyboard input
n cout is a stream on the screen output
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
65
scanf() Examples
scanf() will stop reading when it meets enter, space or tab (whitespace)
Space
66
More on Input
n When looking for the input value in the stream, the >> operator skips any
leading whitespace characters and stops reading at the first character that
is inappropriate for the data type (whitespace or otherwise).
n You can use the get() function to input the very next character in the input
stream without skipping any whitespace characters:
char someChar;
cin.get(someChar);
n The ignore() function is used to skip characters in the input stream:
cin.ignore(200, ‘\n’);
n The first parameter is an int expression; the second, a char value. This
skips the next 200 characters or until a newline character is read, whichever
comes first
Output Manipulators
n Manipulators change the output format of your data. To use them, you will
need to include this header in your C++ source code.
#include <iomanip>
n setw() sets the width of the field to be printed to the screen
n cout << 5 << setw(4) << 6 << 7; // output:5 67
n setprecision() sets the decimal precision to be used to format floating-point
values:
n cout << setprecision(5) << 3.14159; // 3.1416
n cout << setprecision(1) << 3.14159; // 3
n To specify the number of digits after the decimal point:
n cout << setiosflags(ios::fixed); // not use scientific notation
n cout << setprecision(2) << 12.1234; // 12.12
n Other floating point output flags:
n setiosflags(ios::scientific); // use scientific notation
n resetiosflags(ios::floatfield) // restores default (use fixed
// or scientific notation based
// on the precision)
File Input/Output
n In a similar way C++ provides streams which can manipulate files
n C++ provides 2 file streams
ifstream input file stream
ofstream output file stream
Must #include <fstream> to use them
n Example:
#include <fstream>
int number;
ifstream in("in.dat");
ofstream out("out.dat");
in >> number;
out << number;
Input File Streams (ifstream)
n Allows data to be read from a file
n An input file stream can be defined as follows:
ifstream stream_var(filename);
Example:
ifstream inFile("test.dat");
n Important: Effects of reading data from file which has failed to open
is undefined
Input File Streams (ifstream)
n When file opened successfully, data can be read using normal
extractor functions
int n;
char c;
ifstream inFile("test.dat");
inFile >> n;
inFile.get(c);
inFile.ignore(100, 'A');
inFile.close();
n Note:
n If the file already exists its contents will be deleted
n If the file does not exist, a file with the same name is created
n Data can be appended to a file by using constructor with two arguments
ofstream outFile("temp.data", ios::app);
Example on How to Write to a File
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main ()
{
float first, second, sum; // Declaring variables
ofstream outFile("out.dat"); // Opening file for output
cout << "Enter two numbers" << endl;
cin >> first >> second; // Reading in the two numbers
sum = first + second;
outFile << setiosflags(ios::fixed); // Formatting the output
outFile << setprecision(2);
outFile << sum << endl; // Writing into the file
return 0;
}