PHY4321 Summary Notes

Similar documents
PIC10B/1 Winter 2014 Exam I Study Guide

AN OVERVIEW OF C++ 1

Chapter 15 - C++ As A "Better C"

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Function Templates. Consider the following function:

Introduction to C++ Systems Programming

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

CS201 - Introduction to Programming Glossary By

Fast Introduction to Object Oriented Programming and C++

Short Notes of CS201

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

Object-Oriented Programming

Introduction to C++ Introduction to C++ 1

C++ Programming: From Problem Analysis to Program Design, Third Edition

CSE 303: Concepts and Tools for Software Development

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CS201 Some Important Definitions

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Absolute C++ Walter Savitch

Programming in C and C++

PIC10B/1 Winter 2014 Final Exam Study Guide

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

C++_ MARKS 40 MIN

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Chapter 3 - Functions

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Introduction to C ++

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

use static size for this buffer

EL2310 Scientific Programming

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

CS

W3101: Programming Languages C++ Ramana Isukapalli

CS304 Object Oriented Programming Final Term

CSE 333 Lecture 9 - intro to C++

Objectives. In this chapter, you will:

Problem Solving with C++

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Chapter 3. Numeric Types, Expressions, and Output

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

EL2310 Scientific Programming

10. Functions (Part 2)

Functions and Recursion

Professor Terje Haukaas University of British Columbia, Vancouver C++ Programming

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

Introduction to C++ (Extensions to C)

Working with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html

CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors

Documentation. Programming / Documentation Slide 42

C++ (Non for C Programmer) (BT307) 40 Hours

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

CS24 Week 3 Lecture 1

Programming with C++ as a Second Language

STRUCTURING OF PROGRAM

Engineering Problem Solving with C++, Etter/Ingber

File I/O Christian Schumacher, Info1 D-MAVT 2013

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

Window s Visual Studio Output

Intermediate Programming, Spring 2017*

CE221 Programming in C++ Part 1 Introduction

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CS3157: Advanced Programming. Outline

Working with Batches of Data

Cpt S 122 Data Structures. Introduction to C++ Part II

COMP6771 Advanced C++ Programming

UNIT- 3 Introduction to C++

C++ Tutorial AM 225. Dan Fortunato

Computational Physics

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Cours de C++ Introduction

Introduction to C ++

CS 231 Data Structures and Algorithms, Fall 2016

C++ Support Classes (Data and Variables)

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Lecture 5 Files and Streams

G52CPP C++ Programming Lecture 9

Informatik I (D-ITET) Übungsstunde 9, Hossein Shafagh

Your first C++ program

TEMPLATES AND EXCEPTION HANDLING

Chapter 3 - Functions

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Object Oriented Software Design II

COEN244: Class & function templates

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

6.5 Function Prototypes and Argument Coercion

Borland 105, 278, 361, 1135 Bounded array Branch instruction 7 break statement 170 BTree 873 Building a project 117 Built in data types 126

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

G52CPP C++ Programming Lecture 17

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Tutorial-2a: First steps with C++ programming

Transcription:

PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t contain every piece of information you might ever need. 2-3 Variables. Types and Names 4 Simple Maths 5 Maths functions 6 Pointers, references and Arrays 7 The stack and the heap (free store) 8-9 Functions 10 Simple I/O 11 Formatted Output 12-15 Classes 16 Strings 17 Random Numbers, Vectors 18 Iterators and Sorting 1

Variables, Types and Names Variables store information Variables have a type and a name float x = 10.0; Built-in simple types: int float double bool char Can be simple types: int x = 10; You can prevent variables being modified by declaring them const const int x = 10; Can be class types: std::string message = Hello, World ; Curly brackets denote a scope: { float x; } Variables declared inside a scope are created on the stack and deleted at the end of the scope. Variables declared outside a scope are global visible everywhere in the code and should be avoided 2

Types can be converted: implicitly: int x = 10; float y = x; explicitly: int x = 10; float y = float(10); Useful for forcing or preventing integer division: int i = 1; int j = 2; float k = i/j; // integer division k=0 k = float(i)/j; // floating division k = 0.5 Namespaces can be used to avoid naming conflicts: namespace MyNameSpace { float x; } Fully qualified name is then: MyNameSpace::x Bring names into global namespace (so you don t need fully qualified name: using namespace MyNameSpace; Or using MyNameSpace::x; 3

Simple Maths Basic operator summary pre increment / decrement post increment / decrement Multiply Divide Modulo (remainder) add subtract Less than Less than or equal Greater than Greater than or equal Equal to Not equal to Assignment = and += etc ++ a and -- a a++ and a-- a * b a / b a % b a + b a - b a < b a <= b a > b a >= b a == b a!= b a = b; a+=b; etc. Highest precedence at the top. Equal precedence in each box If in doubt use brackets! 4

Maths Functions Standard library contains a wide range of maths functions These are in the std namespace though for historical reasons many also appear in the global namespace Maths functions declared in the cmath header file 5

Pointers and References Pointers store memory addresses, they are used to point to other variables float x = 15; float * p = &x; float * = pointer to a float & = address-of 4 3 Access the thing pointed to using the dereference operator * float z = * p; r 2 1 x Arrays act like pointers: float f[3]= {1.,2.,3.}; float * p = f; p points to the first element of f 0 p References make new labels for existing variables float & r = x; They must be initialised to something when declared Most commonly used in function arguments and return values 6

Free store and the stack A stack is a type of data structure implementing a last-in first-out policy Fast efficient way to handle variables inside a scope and in function calls But limited in size Last-in first-out To access all memory and allocate large objects use the free store: Big arrays: float * array = new float[10000]; Large objects: 4 3 2 1 0 d c b a PhoneBook * obj = new PhoneBook(); If you allocate with new you must deallocate with delete delete[] array; delete obj; 7

Functions Functions package up a collection of instructions They must be declared: int myfunction(int arg1, int arg2); And defined: int myfunction(int arg1, int arg2) { return arg1+arg2; } And called using () : myfunction(5,10); You cannot define functions inside of other functions! You can use default values for arguments in the declaration: int myfunction(int arg1, int arg2=1); But the order matters: int myfunction(int arg1=0, int arg2); int myfunction(int arg1, int arg2=1, int arg3); Overloading functions: same name different arguments int add(int a, int b); float add(float a, float b); 8

Arguments passed-by-value a local copy is made that exists only within the scope of the function To modify arguments use a reference: int myfunction(int & arg1, int & arg2); To avoid copying large objects use a const reference int myfunction( const LargeObject & obj); inline functions use inline keyword to give the compiler a hint Non inline version: Functions.hpp double myfunc(double x, double y); Functions.cpp double myfunc(double x, double y) { return x+y; } Inline version: Functions.hpp inline double myfunc(double x, double y) { return x+y;} No need for functions.cpp Functions inside a class declaration automatically inline 9

Simple I/O Much input and output in C++ handled via streams Reading and writing from/to the console via two objects: std::cin std::cout Similar objects for files: std::ifstream fin( filename ); std::ofstream fout( filename ); Read and write from a stream using >> and << std::cout << Hello ; int i; std::cin >> i; Stream state: good() : previous operation succeeded, next one might work fail(): previous operation failed, next one will fail bad(): stream corrupted eof() : end of file/stream observed std::ifstream fin( file.txt ); bool isgood = fin.good(); iostream header for basic i/o std::cout, std::cin, std::endl etc fstream header for basic file i/o 10

Formatted Output Floating point numbers 3 formats: general : precision defined number of digits scientific : exponent notation, precision = digits after point fixed : integer part + precision = decimal places If the number doesn t fit it is rounded Use function calls on the stream object or manipulators: Scientific: std::cout.setf(std::ios::scientific, std::ios::floatfield); std::cout.precision(2); Fixed: std::cout.setf(std::ios::fixed, std::ios::floatfield); Reset to default: std::cout.unsetf(std::ios::floatfield); Manipulators: std::cout << std::scientific << std::setprecision(2); Set the field width with: std::cout << std::setw(4); or std::cout.width(4); Only applied to next field that gets printed Header: iomanip 11

Classes Classes add new types to the C++ language They are a collection of variables and functions A class is the description of the new type An object is variable of that type Like functions classes need a declaration: class MyClass { public: MyClass() {;} // constructor ~MyClass() {;} // destructor int publicdata; int function() const ; protected: int privatedata; private: }; And a definition: int MyClass::function() const { return privatedata; } Access controlled encapsulation: public: visible to all protected: visible only to this class and inherited classes private: visible only to this class 12

Constructors can have initialisers to setup the data members: MyClass(int d) : privatedata(d) {;} Destructor needed when there is something to clean up such as memory allocated on the free store: ~MyClass() { delete somememoryallocation; } Member functions that do not modify the object should always be declared const int function() const {return privatedata;} Access class members using dot notation: MyClass obj; int v = obj.function(); Or using pointer notation: MyClass * p = new MyClass(); int v = p->function(); When executing a member function the special variable this points to the object on which the function was called int MyClass::function() const { return this->privatedata; } 13

More on classes C++ allows the redefinition of the standard operators for new class types Two forms can be used, member or non-member: Example for a binary operator Use this for your own classes MyClass MyClass::operator+( const MyClass & obj) const; Use this to extend existing classes MyClass operator+(const MyClass & obj1, const MyClass & obj2); Members can be shared across instances of a class by labelling them with the static keyword Call static functions with: MyClass::DoSomething(); class MyClass { //.. Some code // static float staticdatamember; static void DoSomething() {} // static function }; Also need to define the storage for static data members somewhere (typically in the class cpp file) outside any scope float MyClass::staticDataMember; 14

Inheritance and Polymorphism Define inheritance relationship between two classes: class Child : public Parent { // some class declaration }; Child inherits everything from the Parent. But only protected and public members are visible Initialise the base class by calling the constructor: Child() : Parent() {;} Polymorphism enabled through pointers and virtual functions class Parent { // some code virtual void DoSomething() { // //} }; Virtual means that you can use pointers to the parent class but when you call the virtual function it will call the appropriate method in the derived class rather than in the parent 15

Strings C-style strings are just arrays of char terminated with a 0 char c[20] = Hello World ; Many standard library functions and classes make use of them C++ style strings are a new type or class : std::string std::string str( Hello World ); std::strings have lots of useful properties: length: Header str.size(); // = 11 string character access: str[3]; // = l can be appended-to str.append(! ); // = Hello World! str+=(! ); // = Hello World!! Substrings: std::string sub = str.substr(6,5); // = World Get a c-style string: str.c_str(); 16

Random Numbers Generate pseudo-random integers with std::rand() Seed the random number generator with std::srand( an integer ); Get a random number between 0 and RAND_MAX int r = std::rand(); Header cstdlib Vectors Smart replacement for arrays Header vector std::vector< type > myvector; Add myvector.push_back(value); Remove myvector.pop_back(); Size myvector.size(); Access myvector[i]; // no range checking myvector.at(i); // with range checking Clear myvector.clear(); // empty the vector 17

Iterators Used for looping over collections such as vector Header Get an iterator to the start of the collection with: vector vec.begin(); An iterator pointing one spot beyond the last element with: vec.end(); Go to the next element with: ++iter; Get the value of the element with: *iter; std::vector<int> myvec; for( std::vector<int>::iterator iter = myvec.begin(); iter!=myvec.end(); ++iter) { int x = *iter; } Very useful with standard algorithms such as sort std::sort( begin, end); Header algorithm Will sort a collection where begin is an iterator pointing to the beginning and end is an iterator pointing to one element beyond the end 18