Introduction C o Why use C ANSI standard




















![Arrays (II) C++ Multi-dimensional arrays specified by: double elements[100][100]; // about 8 Mb! for Arrays (II) C++ Multi-dimensional arrays specified by: double elements[100][100]; // about 8 Mb! for](https://slidetodoc.com/presentation_image/5de9b16b1742560edfbd074be90988b5/image-21.jpg)



![C++ Pointers (III) The name of an array is also a pointer: float e[10], C++ Pointers (III) The name of an array is also a pointer: float e[10],](https://slidetodoc.com/presentation_image/5de9b16b1742560edfbd074be90988b5/image-25.jpg)














- Slides: 39

Introduction C++ o Why use C++? ANSI standard Compilers available on every platform All libraries (to my knowledge) have C and/or C++ API o Is C++ better than Fortran? Structure Object orientation Reusable code and library creation Excellent error checking at compile time Fortran becomes more like C++ with every release o Microsoft Visual C++ Development environment Create console (DOS) applications Can develop full-blown Windows applications

C++ Course layout Week 1 Learn about C, the subset of C++ (not all C covered, some C++ stuff used) Week 2 C++ proper; classes and objects Quick question and answer session after each section

C++ Sections 1) Form of a C++ program 2) Data types 3) Variables and scope 4) Operators 5) Statements 6) Arrays 7) Pointers 8) Functions 9) Structures 10) Console I/O 11) File I/O 12) Pre-processor instructions 13) Comments 14) Compiling examples under Unix Lecturer may pop out for a smoke after some sections

C++ Form of a C++ program pre-processor statement function #include <iostream. h> arguments int main(int argc, char* argv[]) { cout << “Hello Worldn”; return 0; semi-colons } braces enclosing function All C++ programs must have one, and only one, main function Example: helloworld

Some differences with Fortran C++ o C++ is case sensitive: x != X o You can write it all on one line - statements separated by ‘; ’ o There are NO built-in functions but lots of standard libraries o There is NO built-in I/O but there are I/O libraries o There about 60 keywords - need to know about 20? o C++ supports dynamic memory allocation o All C++ compilers are accompanied by the C pre-processor o You can potentially screw up the operating system with C++

C++ Including header files and library functions C++ programs try to be ‘lean and mean’; programmer chooses what to include in the executable Header files declare the functions to be linked in from libraries… #include <iostream. h> #include <math. h> #include “D: andy. h” read & write functions sqrt, log, sin, abs, etc My stuff that I use frequently and don’t want to recreate If header is in “” the filename must be full (or relative); if in <> pre-processor searches in pre-defined folders

Microsoft Visual C++ o o o o C++ Each program is created within a ‘project’ A project can only contain ONE ‘main’ function Basically each individual project is a program Each project is stored in a folder To open a project, double-click the ‘. dsw’ file in the folder Click Help>Index and type a query - massive documentation Or select (highlight) a keyword and press F 1 on keyboard VC++ is a big application: a separate course! run build

Example programs and VC++ Look at http: //www. liv. ac. uk/~aeh o Get VC++ installation disks from Alan (sign license for Mr Gates) o Projects can be downloaded - they are zipped (Power. Zip/Win. Zip) o You might need to go to Project>Settings and click Debug tab and set your own path to where the project is stored (I suggest M: C++ as the folder to unzip the examples into) o Experiment with the examples - compilation errors appear in the window below the source window(s)… double-click on the error message to go to the line containing the error. o You can highlight a keyword (or whatever) and press F 1 to get help o The documentation is huge - and not just about VC++; be selective!

Data types C++ is a programmer’s language - need to know the basics… There are 6 atomic data types: 1) char - character (1 byte) 2) int - integer (usually 4 bytes) 3) float - floating point (usually 4 bytes) 4) double - double precision floating point (usually 8 bytes) 5) bool - true or false (usually 4 bytes) 6) void - explicitly says function does not return a value and can represent a pointer to any data type Size of the data types depends on machine architecture e. g. 16 bit, 32 bit or 64 bit words Other data types are derived from atomic types e. g. long int Can use ‘typedef’ to alias your own data type names; defining C++ classes creates new types

C++ Variables and scope int a, b, c; a = 1; b = c = 0 x 3 F; float i. Am. AFloat = 1. 234; double i. Am. ADouble = 1. 2 e 34; { int i, a; ‘b’ declared inside braces; ‘b’ is in scope inside braces ‘a’ declared outside loop braces for (i=0; i<10; i++) { a = i; ‘a’ used inside braces, OK int b = i; } b = 2; } ‘b’ is unknown outside braces: ‘b’ is out of scope, ERROR

C++ Operators Obvious: Shorthand: Modulus: Decrement: Increment: Relational: Logical: +, -, *, / +=, *=, -=, /= % -++ ==, !=, <, >, <=, >= !, &&, ||, &, |, ^, ~ int a, b; a++; b--; means the same as a = a + 1; b = b - 1; 5%3 evaluates to 2 (the remainder of division)

C++ Statements A statement is a part of the program that can be executed Statement categories: 1) Selection 2) Iteration 3) Jump 4) Expression 5) Try (exception handling; look it up) Statements specify actions within a program. Generally they are responsible for control-flow and decision making: e. g. if (some condition) {do this} else {do that}

C++ Selection: ‘if’ General form is: if (expression) { statement; } else if (expression) { statement; }. . . else { statement; } bool flag; int a, b; if (a>0 && b>0) { a = 0; b = 0; } else if (flag) { a = -1; } else { b = -1; } ‘expression’ is any condition that evaluates to ‘true’ or ‘false’ ‘statement’ could be another ‘if’ i. e. nesting…

A note on conditional expressions C++ A condition is one or more expressions that evaluate to true or false Expressions can be linked together by logical operators bool flag; double a; evaluates ‘true’ if flag is ‘false’ (!flag) (a>0. 0 && flag) (a==0. 0 || !flag) (a<0. 0 || (flag && a>0. 0)) evaluates ‘true’ if a is zero or flag is false

Selection: ‘switch’ C++ This statement only works with integers and chars it only checks for identical values (not less or more than). Good for using with menu choices… ch of type ‘char’ (could be ‘int’) control jumps here if ch equals ‘b’ control jumps to end brace switch (ch) { case ‘a’: This is a label, do. Menu. Option. A(); and so has break; a ‘: ’ after it case ‘b’: do. Menu. Option. B(); break; . Note! As in ‘if’, there. is NO ‘; ’ after braces. } Example: menuchoice

C++ Iteration: ‘for’ loop Huge amount of variation allowed, very flexible: generally for (initialisation; condition; increment) { statements } Initially i is set to zero int i, a[10]; int sum = 0; Keeps looping while i is less than 10 (i. e. condition is ‘true’) for (i=0; i<10; i++) { a[i] = i; sum = sum + i; } i increments by one on each iteration

C++ Iteration: ‘while’ loop General form is while (condition) { statements } #include <iostream. h> char c = ‘ ’; use console I/O initialise the char variable while (c != ‘q’) { cout << “Type a key (q to finish): “; cin >> c; } The loop body will execute forever - until “q” is pressed cout << “Finishedn”; Example: typeq

C++ Jump: ‘goto’, ‘return’, ‘break’ and ‘continue’ Personal bigotry: using ‘goto’ just shows bad design; do not use ‘return’ is used to exit a function, usually with a value int a = 0; infinite loop int count = 0; int i; while (true) { for (i=0; i<10; i++) { a++; if (i<3 || i>6) { if (a >= 10) { continue; break; } } count++; Jump to beginning } jump out of loop } of loop and begin (if loops nested, only next iteration jump out of inner)

C++ Expressions An expression statement is anything that ends with a ‘; ’ func(); function call a = b + c; ; empty statement - perfectly valid float root = (-b + sqrt(b*b - 4. 0*a*c)) / (2. 0*a); int flagset = 0 x 0001 | 0 x 0100; bool check = (flag & 0 x 0001); bitwise OR of two integers bitwise AND of two ints; result is true or false

C++ Arrays (I) o In C++ arrays can be either fixed or variable length; there is a very close link between arrays and pointers o An array can be of any data type, including your own o C++ arrays are indexed from 0; the last element at N-1 first element at 0, last at 4 int a[5]; for (i=0; i<10; i++) { a[i] = i; } may crash when i>4; no bounds checking by default Example: bubble
![Arrays II C Multidimensional arrays specified by double elements100100 about 8 Mb for Arrays (II) C++ Multi-dimensional arrays specified by: double elements[100][100]; // about 8 Mb! for](https://slidetodoc.com/presentation_image/5de9b16b1742560edfbd074be90988b5/image-21.jpg)
Arrays (II) C++ Multi-dimensional arrays specified by: double elements[100][100]; // about 8 Mb! for (i=0; i<100; i++) { for (j=0; j<100; j++) { for (k=0; k<100; k++) { elements[i][j][k] = init. Element(i, j, k); } } function that returns a ‘double’ } Arrays can be initialised with contents: float coeff[] = { 1. 2, -5. 456 e-03, 200. 0, 0. 000001 }; compiler sizes array automatically

C++ Arrays (III) Character strings are arrays of type char Many functions dedicated to manipulating strings <string. h> C++ offers the standard ‘string’ class Many library functions require you to use char* variables char my. Name[128]; int len; A n d y strcpy(my. Name, “Andy Heath”); char* fullname = my. Name; len = strlen(fullname); char* surname = &my. Name[5]; len = strlen(surname); char* argv[]; H e a t h ? ? ? terminator length is 10 length is 5 array of strings passed from command line Example: cstring

Pointers (I) C++ o A pointer is a variable; just like any other type of variable o The variable contains the memory address of a certain data type o The address is in either stack memory or heap memory o Any atomic or user-defined data type can be pointed to o The value of the pointer’s data type can be obtained o Obtaining the value pointed to in memory is called dereferencing o Two unary operators are used frequently with pointers: * and & o Using pointers incorrectly will almost certainly crash things o Pointers are the most useful feature of C++ (in my opinion)

C++ Pointers (II) stack memory address float a = 3. 142; float* pa = &a; pa = 1000 3. 142 1000 1004 double b = 1. 2 e 12; double* pb = &b; double bb = *pb; 1. 2 e 12 bb = 1. 2 e 12 int c = 7; int* pc = &c; int* pc 1 = pc + 1; *pc 1 = 22; potentially disastrous: something important may be at address 1028! 1008 1012 1016 1020 7 1024 ? 22? 1028
![C Pointers III The name of an array is also a pointer float e10 C++ Pointers (III) The name of an array is also a pointer: float e[10],](https://slidetodoc.com/presentation_image/5de9b16b1742560edfbd074be90988b5/image-25.jpg)
C++ Pointers (III) The name of an array is also a pointer: float e[10], *pe; pe = &e[0]; Can use a pointer as index into array: for (int i=0; i<10; i++) { *pe = float(i); pe++; } Stack memory is allocated at compile time, when the size of an object (e. g. an array) is already known. Unless declared ‘static’, stack memory is freed when object is no longer in scope. E. g. when a function returns, the memory it’s variables occupied will be reused.

Pointers (IV) C++ The best thing about pointers: they can refer to ‘new’ objects that persist in the ‘heap’ memory and do not disappear when scope changes float* p. Elements = new float[10]; The only way to free up this sort of memory is to ‘delete’ it: delete[] p. Elements; Do NOT use p. Elements after it has been deleted - almost certain crash, but probably not at the time you refer to it! Pointers are used with C++ class objects, structures, functions, library functions, system calls - just about everything…

C++ Functions (I) A function is a distinct body of code that returns a value even if the value is nothing at all // this is some function int func(double a, double b) { if (a < b) { return -1; } else { return 1; } } // this is the main function int main(int argc, char* argv[]) { return func(1. 0, 2. 0); }

C++ Functions (II) This is the same function - the code is written in a different order int func(double, double); // this is the main function int main(int argc, char* argv[]) { return func(1. 0, 2. 0); } // this is some function int func(double a, double b) { if (a < b) { return -1; } else { return 1; } } Prototype (this is what is in header files)

Functions (III) C++ o A function returns a value (except if it is of type ‘void’) o The value is specified with the ‘return’ keyword o The value returned must be the same type as the function double logit(double z) { return log(z); } int add. Ints(int a, int b, int c) { return a + b + c; } A function call itself - recursion int factorial(int n) { if (n > 0) { return n*factorial(n-1); } else { return 1; } } Example: factorial

C++ Functions (IV) Arguments passed to functions in one of three ways: 1) By value (default) 2) By reference 3) Thru a pointer to the argument { { { float x = 2. 0 f; func(x); func(&x); cout << x; } } } void func(float x) { x = pow(10, x); } void func(float& x) { x = pow(10, x); } void func(float* px) { *px = pow(10, *px); } C++ default Like Fortran Thru a pointer

C++ Functions (V) The name of a function is also a pointer to it, so you can pass the function into another function… e. g. quick sort ‘qsort’ routine in the standard library <stdlib. h> ‘qsort’ uses a clever and efficient algorithm to order an array: You define the function which compares array elements because only you know how to do the comparison! int my. Cmp(const void* e 1, const void* e 2) { // return -1, 0 or 1 depending on <, == or > } int Call ‘qsort’ like this: qsort(my. Array, n. My. Array, size. Element, my. Cmp); void* int (int*)(const void*, const void*) Example: varfunc Example: qsort

C++ Structures (I) A structure is a way of grouping together different types of data to create a new type of data object struct my. Record { char* surname; char* first. Name; int n. Days. Off; float salary; }; Define the type ‘struct my. Record’ int main(int argc, char* argv[]) { struct my. Record rec; rec. surname = “Heath”; rec. salary = 1000. 0; } rec is a variable of type ‘struct my. Record’ A dot is used to specify individual fields in the structure

C++ Structures (II) o Can have arrays of a structure type o Can access a structure thru a pointer o Can have structures nested within another structure void func(struct my. Record* p. Rec) { p. Rec->surname = “Gates”; p. Rec->salary = 1. 0 e 10; } int main(int argc, char* argv[]) { struct my. Record gates; func(&gates); } Use -> to access fields thru pointer to a structure gates is of type struct my. Record Use the ‘&’ operator to pass a pointer to gates into function func Example: structure

Structures (III) C++ o Structures are a C concept o Replaced in C++ with the ‘class’ concept o Objects of a class can be completely defined as a new data type class Andy { // definition of stuff }; a, b and c are of type Andy int main(int argc, char* argv[]) { Andy a, b, c; If we choose to, we can give ‘Andy’ a = b + c; objects the ability to do addition, cout << a; and to write themselves to the console } but that’s for NEXT WEEK…

C++ Console I/O o The console is a command window (DOS or terminal) o C++ uses the ‘<<’ and ‘>>’ operators to write and read o C++ recognises what sort of data you want to read or write and acts accordingly o Use “manipulators” to format I/O - look it up! #include <iostream. h> int main(int argc, char* argv[]) { char* name = “Andy Heath”; float number = 1. 2345; int menu. Choice; read an ‘int’ token from the keyboard - tokens separated by white-space (space, newline, tab) cin >> menu. Choice; cout << name << “ “ << number << “n”; return 0; } write variables and constants to screen; use newline (‘n’) to finish line

C++ File I/O o Similar to console I/O o Different types of stream for input and output o File streams defined in <fstream. h> ifstream in. File; ofstream out. File; float number; in. File. open(“readme. txt”); out. File. open(“writeme. txt”); while (!in. File. eof()) { in. File >> number; out. File << number; } in. File. close(); out. File. close(); Keep going until the end of file is reached These are methods of the base classes ‘ios’ and ‘fstream’… ‘inheritance’ covered next week! Example: copy. File

Pre-processor instructions C++ Pre-processor instructions allow the programmer to choose what source code the compiler sees - very useful for writing programs that are portable between Unix and Windows #ifdef WIN 32 #include <some. Windows. Header. h> void my. Func(/* Windows data types */); #else #include <some. Unix. Header. h> void my. Func(/* Unix data types */); #endif Can use verbose output in a function to help with debugging #ifdef _DEBUG cout << “Debug: at end of ‘func 1’ x = “ << x << “n”; #endif Look at Project>Settings and the “C/C++” tab for Pre-processer defs

Comments C++ Two types of comments: /* blah */ // blah /* * this function computes the square root of infinity */ double sqrt. Inf() { double infinity = Na. N; // is infinity a number? return 1. 0; // near enough since I haven’t got a clue } VC++ colours comments green by default

C++ And finally… To build an example on Unix (Linux, Solaris, whatever) o Copy the example. cpp file on to Unix machine o Rename the file with the command ‘mv example. cpp example. C’ o Compile the program with ‘g++ -o example. C’* o Run the program by typing ‘example’ *There is a possibility that g++ is not installed on some people’s systems Bye bye…