Today’ s arrangements C++ for Physics Your teacher is: Your demonstrators are: We finish at: You should have: Class notes Copies of slides IT Learning Group IT Learning Programme Your safety is important Today's Topics Where is the fire exit? C++ and OOP? Flow Control First Program S equence Beware of hazards Fundamental data types S election Tripping over bags and coats string class Repetition Please tell us if anything does not work Functions Arrays Let us know if you have any other concerns Vectors Classes Function Templat es Member functions Pointers Data members What is OOP? S o, what is OOP? O bj ect O riented P rogramming Combined variable type that includes functions A way of modelling individual obj ects in the real world Class S tudents Member functions/ methods Vehicles represent real obj ect - behaviour Buildings Member variables/ data members ATM’ s represent real obj ect - state etc, etc IT Learning Programme Oxford University Computing Services
S tandard C++ Library First Program • Collection of classes and #include <iostream> functions Include contents of the header file in the program • Result of conformance to ISO using namespace std; standard cin is standard input stream obj ect of istream class t hat • Incorporates what was STL allows input from keyboard cout is standard output stream obj ect • Class definitions for standard data structures int main() • Collection of algorithms used to In every C++ program, funct ion manipulate these and other structures First Program Functions int aNum = 0; Used to encapsulate data and operations Can simplify coding variable (memory location called aNum ) to hold number of type integer ( int ) Functions for discrete tasks Not hundreds of lines of code << stream insertion operator Only need to know cout <<“ Enter a number:- ” ; Input data Output data >> stream extraction operator Functions can be reused cin >>aNum; First program Functions Functions Need a prototype Defining a function (no return value) Tells the compiler what is coming Return type void readChar() Function name { Parameter list (what is being passed in) char aChar; cout << "Enter a CHARACTER: " ; void readChar(); cin >> aChar; int getNumber(); cout << “Character is " << aChar << endl; double numDoubled(int); return; } IT Learning Programme Oxford University Computing Services
Functions Functions Calling a function Pass by Reference With no return type Previously, pass by Value readChar(); Copy of value passed to function With return type int Pass by Reference int myNum = 0; Address of value passed to function myNum = readNumber(); cout << “The integer returned is “<< myNum; FuncRef.dev CharNumStringFunc.dev Classes and Obj ects Classes and Obj ects A class is a definition of a compound variable type Member functions An object is an instance of that class Called by objectName.functionName() From a student class Peter.displayName(); Create many objects of type student Peter.setCourseName(); Peter Peter.setYears(); Sarah Thomas Jane Data Members (variables of obj ect) Create an instance (object) of class student Member functions used to access the data members student Peter ; student Sarah ; Classes and Obj ects Classes and Obj ects class StudentCourse Data Members { private: string courseName; Access specifiers public: private : only accessible via member functions of the void setName(string name) class { protected : only accessed via member funct ions of the class and member functions of a derived class courseName = name; public : can be accessed from any (non-member) } function, anywhere the obj ect is visible }; OxStudents.dev IT Learning Programme Oxford University Computing Services
Classes and Obj ects Classes and Obj ects Constructors Separate class files for reusability Default constructors, provided by compiler Class files with main() means the class cannot be Create your own & initialise data members reused. StudentCourse (string cName) Only have one main() function { Separate class into own file with .h suffix CourseName = cName; Use pre-processor directive to add the file when } compiled Destructors #include “myClass.h” Class name preceded by tilde ~ Constructor.dev ~ StudentCourse (); Basic Control Flow Basic Control Flow Selection Sequence switch multiple selection statements What we have been doing already Test must be constant integer value, 1, 10, ‘A’, ‘x’. Not 10.56, 5.2. Selection switch ( aNumb ) if… else statements { Two possible marks, 49 or 50 stored in score case 1 : cout<<“ Number1” ; if (condition is true) if (score >= 50) break ; cout<<“ Passed” ; cout<<“ Passed” ; default: else else cout<<“ NOT Number1” ; cout<<“ Failed” ; cout<<“ Failed” ; } IfSwitch.dev Basic Control Flow Basic Control Flow Repetition Repetition while statement The ‘for’ loop while(some condition is true) for (i = 1; i<= 5; i++) do the statements; { while (counter < 4) do this statement; { now do this statement; cout<<"Ent er mark "; } cin >> mark; Note: = is an assignment total +=mark; <= is a relat ional operator counter ++; == is an equality operator } IT Learning Programme Oxford University Computing Services
Basic Control Flow Exercises Repetition do… while loop Complete exercises in sections 1-8 do { statements } while(the condition is true) do { cout<<“ Mark number " <<mark <<endl; mark ++; } DoWhile.dev while (mark <=10); Arrays Arrays Data structure containing same type of data (int, int inNumbers[20]; double, string, char, object) an array of 20 integers Series of elements each containing one item of char inName[5]; data (contiguous memory locations) an array of 5 characters Cannot change size double examMarks[] = {1.2, 3.9, 9.5} Element 0 1 2 3 4 5 initialise and set size to 3 elements of type double Experiment Result 34.67 31.78 31.89 34.67 36.23 32.78 Arrays Arrays Adding data to arrays. Outputting data from an array double examMarks[5] = {0}; for(int i = 0; i <5; i++) { for(int i = 0; i <5; i++) cout<<"Exam Mark "<<i + 1<<"is "<< examMarks[i] <<endl; { } cout<<"Enter Exam Mark "<<i + 1<<" "; cin >> examMarks [i]; } Array.dev IT Learning Programme Oxford University Computing Services
Vectors Vectors vector<int> vec(20,0); Container class, part of Standard Template Library, similar to arrays for(int i = 0; i<vec.size(); i++) Can hold objects of same type of data (int, vec[i] = (i); double, string, char, object) Can resize, grow, shrink as elements are added or removed from the end for(int i = 0; i<vec.size(); i++) Algorithms to manipulate data { Iterators (like pointers) to cycle through all cout<< vec[i]<<" "; elements in vector } Vectors Vectors Adding an extra element Vector m em ber Function Effect at(elem ent num ber) Gets the value con tain ed in the specified elem ent cout<<"Enter an Extra Value "; back() Gets the value in the fin al elem ent cin >> aNum; begin() Points to the first elem ent in vecto r clear() Erases the vector vec.push_back(aNum); em pty() Returns true (1) if the vecto r is em pty, or false (0 ) otherwise end() Points to the last elem en t in vecto r fron t() Gets the value in the first elem en t Print vector of 21 numbers pop_ back() Rem oves the fin al elem en t push_ back(value) Adds an elem en t to the end o f the vector, con taining the specified value size() Gets the num ber of elem en ts for(int i = 0; i<vec.size(); i++) reverse(); An algorithm (global function) that reverses the values in a vecto r (v) { reverse(v.begin() v.end()) v.begin() and v.end() are iterato rs sort(); An algorithm (global function) that sorts the vecto r (v) cout<< vec[i]<<" "; sort(v.begin(), v.end()) v.begin() and v.end() are iterato rs } VectorPushBack.dev Lists Lists list<double> mylist(2,); Another container class also part of standard library. mylist.push_back(7.8); Can hold objects of same type of data (int or double or string or objects). mylist.push_back(23.2); Can resize, grow, shrink as elements are added or removed. mylist.push_front(67.62); Links to preceding & following elements. mylist.push_front(2.73); Efficient insertion and removal of elements anywhere in the container. mylist.pop_back() mylist.pop_front() IT Learning Programme Oxford University Computing Services
Recommend
More recommend