1 / 15

Introduction to C++

Introduction to C++. Dr M.S. Colclough, research fellows, pgtas . 5 weeks, 2 afternoons / week. Primarily a lab project. Approx. first 5 sessions start with lecture, followed by non-assessed exercises in lab. Later sessions devoted to a programming project (choose your own, or select from

cian
Download Presentation

Introduction to C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to C++ Dr M.S. Colclough, research fellows, pgtas 5 weeks, 2 afternoons / week. Primarily a lab project. Approx. first 5 sessions start with lecture, followed by non-assessed exercises in lab. Later sessions devoted to a programming project (choose your own, or select from list). Assessment based on project. Hand-in dates as for lab: Phase 1: Fri 10 Dec 2010 (4pm) Phase 2: Fri 28 Jan 2011 (4pm) Labs equipped with Quincy editor and gcc Consult me if you wish to use your own system. Initial exercises are console (text) mode; graphical libraries later. Projects may or may not have graphical features. Teaching Support Office

  2. Project Substantial, finished individual program High quality code: easy for others to understand / maintain / extend: clear logic, naming, data structures. Display sophistication in programming techniques: e.g. appropriate classes, use of external libraries, graphical interface, good algorithms. Good quality user interface: usable by others It's impossible to learn these skills in advance. Credit for acquiring these skills. Write a 1-2 page informal proposal for your project for approval by demonstrator. Does not have to be a physics calculation.

  3. Resources Course web pages: www.cm.ph.bham.ac.uk/cpp Email: m.s.colclough@bham.ac.uk (Teach yourself/learn) (C++/Bengali) in (30 Days/21 Days/24 Hours/10 Minutes) - all exist! See the web pages for references to web sites and books, including several good free online ones e.g. Thinking in C++ Eckel Numerical recipes in C Press An introduction to C++ Chivers C++: A dialog Steve Heller If you don't already know C, avoid books that (i) assume you do, or (ii) teach C before C++. OK at this level: Programming with C++ Hubbard (Schaum's) C++ By Example Donovan (beware misprints) Accelerated C++ Koenig & Moo (intensive) Reference handbook: C/C++ Programmer's Reference Schildt

  4. About C++ C was developed closely with the UNIX operating system (~1973) Mostly deals with ‘low-level’ data bytes, integers, floating point numbers, addresses (memory locations) Higher level than machine code (but not much) C++ was invented to make writing large scale software projects easier (~1983) the name C++ is an in-joke (++ in C/C++ = ‘the next one’) It is an ‘object oriented’ language can define high-level objects Originally conceived as ‘C with objects’ but the feature set expanded rapidly ISO standard finalised ~1998 We will only cover some of the most common and important features Using gcc/mingw 3.2 About Me: Steve Hillier (S.J.Hillier@bham.ac.uk)

  5. Hello World #include <iostream> using namespace std; int main() { cout << "Hello World" << endl; } main is our first example of a function main is a very special function that the operating system calls when you start executing a program all programs must have a main no arguments – followed by () {}surround instructions to be performed Instructions consist of a number of statements followed by a semi-colon (one in this case) cout refers to the standard output stream (screen) endl jumps output to the next line << means ‘insert right-hand thing into left-hand thing’ #include <iostream> provides definition of cout, endl (called header file)

  6. Streams and spacing There are several ways to do the same thing: #include <iostream> using namespace std; cout << "Last " << "night " << "I " << "dreamt"; cout << "Last "; cout << "night "; cout << "I "; cout << "dreamt"; cout << "Last night I dreamt"; Also spacing is (usually) unimportant for the compiler (‘whitespace’ is equivalent): #include <iostream> using namespace std; int main(){cout<<"Hello World"<<endl;} This would work just as well, but isn’t nice to look at – hence formatting conventions

  7. Comments There are two styles – C++ style preferred // marks a comment that extends to // the end of the line. This is the // usual C++ style cout << endl; // Can be used here too /* This style makes a C-style comment that extends over several lines until the closing */ Comments are highly recommended Obligatory in assessed work Level of detail can be difficult to judge Try to say what or why, not how, eg // Calculate Julian date from // calendar date using algorithm from // Press et al.: Numerical Recipes

  8. Strings First example of a data type. Declares a variable to contain characters and words As with streams, needs a header file: #include <string> // To create an empty string "" string firstName; // To create one with contents string secondName("Hillier"); // String of 25 question marks string bigQuery(25,’?’); firstName = "Steve"; // Change it // Join strings together... name = firstName + " " + secondName; // Read in from keyboard... cin >> name; // >> = extract lhs to rhs cout << name; Name.size(); // function returning length Strings have many other functions and operations

  9. Variables and their names Just introduced the idea of a variable Declared to name an object that the program uses Declaration obligatory Can be of many types (including user defined) Variables can be changed Variable Names Initial letter + letters and digits: any length underscore is a letter: oh_yes_it_is case sensitive ie me, Me, mE, ME all different function names follow same rules several conventions used for names eg ALLCAPS traditionally used for constants: PI, MU0, … Some guidance: Must avoid reserved words eg static, else, throw… Should be highlighted by editor Good choice of names helps to make your program clearer

  10. More Variables - Numerical Computers are good at working with numbers, so not surprisingly there’s lots of language support // Integers (±2,000,000,000) int i; // Declare i as an integer or int i=25; // declare and assign value or int i(25); // C++ style declare and assign // single precision floating point // (1e38, 6 digit precision) float x, y, z; // Declare three at once // double precision (more common) // (1e308, 15 digit precision) double a, b, bigNumber; Exact limits depend on compiler/operating system. These are typical values. Basic arithmetic operations are built into language int total; // assign new value as result of expression total = i + j*k +p/q;

  11. Expressions In arithmetical expressions, the usual precedence rules apply (* before + etc). Expressions involving mixed types invoke type promotion (int to float to double). Integer division ignores remainder 3/4 = 0 (integer division) 3.0/4 = 0.75 (float division) double s, u, t, a; s = u*t + 0.5*a*t*t; There are some new operators: int i(7); int j(4); int remainder = i%j; // result is 3; i += 5; // Is equivalent to... i = i+5; // so i is now 17 j = i++; // now j is 17 (old i), i is 18 j = ++i; // now j is 19 (new i), i is 19 i++; // increment i, now 20 i--; // decrement I, now 19 again

  12. Choices, choices… if A program can’t be very intelligent if it always Executes the same instructions. Therefore need choices and program control Probably the simplest is the if...else construct if ( cash > 50 ) { party; party; } else { work; } Note on structure blocks of code surrounded by {} else optional if condition in () Many other ‘comparison’ operators <, >, <=, >=, ==, != Take care with == (test for equality)

  13. For loops Extremely powerful and flexible control structure. Used for repeating instructions (iteration). Typical loop: counts sums, and sum of squares of integers from 1 to 10. int sum(0); int sumSquares(0); for ( int i=1 ; i<=10 ; i++ ) { sum += i; sumSquares += i*i; } Syntax similar to if, but ‘condition’ consists of three parts: int i=1 // initialisation i<10 // condition, end loop if false i++ // perform at end of each loop In this case the loop counter, i, starts at 1, and the loop is performed for i = 1, 2, 3, … 9, 10. Initialisation, end action, can be more complex

  14. Calling external functions For mathematical manipulations more complex than multiply, divide etc, need external functions. Many functions declared in <cmath> header. geometric – sin, cos, etc exponential – exp, ln others – pow, sqrt Examples: #include <cmath> double s, a, b, c; // pythagoras s = sqrt( pow(b,2) + pow(c,2) ); // triangle area area = pow(b,2) + pow(c,2) - 2*b*c*cos(a);

  15. Formatting Output There are many formatting functions for cout. Used to ‘tidy up’ output. // 4 digit floating point numbers cout.precision(4); // 10 character space cout.width(10); // Fill blank characters with # cout.fill(‘#’); Shorthand for all above using ‘manipulators’: #include <iomanip> cout << setprecision(4); cout << setw(10); cout << setfill(‘#’); Note width setting is for next item only: cout << setw(10) << 3.2; Many other options (scientific notation, justification)

More Related