44
First Year Computing First Year Computing Introduction to C++ Introduction to C++

First Year Computing Introduction to C++. Getting Started

Embed Size (px)

Citation preview

First Year ComputingFirst Year Computing

Introduction to C++Introduction to C++

Getting StartedGetting Started

UG1 Computing | Introduction to C++ | Getting Started

Stages in programmingStages in programming

Designalgorithm

Writecode/software

Compile machine code

Link inother utilities

Run programDo results

make sense?

No

ResultsYes

UG1 Computing | Introduction to C++ | Getting Started

Programming

Programming Language• we use basic elements of C/C++• standard library functions (e.g. input/output,

mathematical functions) Microsoft Visual Studio

• provides an environment to develop software• compiler: translates C++ code to machine

instructions• run program with error diagnostics• debugger: run program step-by-step

UG1 Computing | Introduction to C++ | Getting Started

// Calculate the cube of an integer#include <iostream>using namespace std;

int main( ){ int n, ncube; cout << "Enter a number:"; cin >> n; ncube = n * n * n; cout<< n << “\t” << ncube << endl;

return 0; }

A simple program

Header

main function

input n

output n3

declare the variables we need

ask for user input from keyboard

output result to screen

calculate cube

end of main() functionreturn control to computer

library for input/output

comment: ignored by compiler

defines standard keywords

UG1 Computing | Introduction to C++ | Getting Started

Variables

Variables must be declared before being used:

int ncube;• space is allocated in the computer memory to

store an integer variable called ncube• variable type int takes up 4 bytes = 32 bits• manipulating ncube changes content of those

4 bytes of memory Variables may need initial value

int n=10, m=99;

UG1 Computing | Introduction to C++ | Getting Started

C++ arithmetic

Usual arithmetical operatorsa+b a-b a*b a/b

Also: a++ increments a by 1a-- decrements a by 1a += 3 adds 3 to aa -= 3 subtracts 3 from aa *= 3 multiplies a by 3a /= 3 divides a by 3

Assignment operator =c = a assigns the current value of a to cIt does not mean that the variable c is equal to a from now on.

UG1 Computing | Introduction to C++ | Getting Started

Semicolons

The semicolon marks the end of a lineint ncube;b = c + a;cin >> n;

Line wraps are ignoredcout << “one long line in C++: ”

<< “n = ” << n << “m = ” << m << endl;

UG1 Computing | Introduction to C++ | Getting Started

Course Structure

Short Tasks (Section 2)• follow step by step• do all the tasks in Section 2 (4 or 5 sessions)• keep a record of your work in lab book• ask demonstrators for help

Projects (Section 3)• choose one task for a report (50%)

UG1 Computing | Introduction to C++

Assessment

Continuous assessment (50%)• Technical performance: effective use of C++• Personal performance: motivation,

participation, initiative• weighted by attendance: absences due to

sickness require self certification (form available from UG office)

Project assessment (50%)• Report on one project in section 3

UG1 Computing | Introduction to C++

Getting Started

Read Section 1 Task 1: set up Microsoft Visual Studio

carefully! Assign demonstrator to students

• make sure you know who your assigned demonstrator is before you leave today

• please remain in the same seat for rest of the sessions

Session 2Session 2

Branches & LoopsBranches & Loops

UG1 Computing | Introduction to C++ | Branching

Conditional statements

The if statement

Is j > i?

previous step

j = j - 2

Yes

No

next step

if ( j > i ){ j = j – 2;}

Don’t need semicolon here

No semicolon here

UG1 Computing | Introduction to C++ | Branching

Conditional statements

The if…else statement

Is j > i?

previous step

j = j - 2

Yes

No

next step

if ( j > i ){ j = j – 2;}else{ j = j + 6;}

j = j + 6

UG1 Computing | Introduction to C++ | Branching

True or false? n > a n greater than a? n >= a n greater than or equal to a? n < a n less than a? n <= a n less than or equal to a? n == a n equal to a? (not single =) n != a n not equal to a? (n==a) && (b>a) n==a AND b>a (n==a) || (b>a) n==a OR b>a

Relational operators

(1 or 0)

UG1 Computing | Introduction to C++ | Branching

A list of options

if…else if… else// opt is option number from a menuif ( opt == 1 ) { do this for option 1 }else if ( opt == 2 ) { do this for option 2 }else if ( opt == 3 ) { do this for option 3 }else { do this if none of the above }

Try also theswitch statement

Try also theswitch statement

Conditions testedsequentially

UG1 Computing | Introduction to C++ | Loops

Loops / Iterations

Loop repeats 10 times Loop counter n

• starts at 1• test value at start of each

cycle• if n > 10, stop loop • if n ≤ 10, do this• incremented after each

iteration

stop

n = 1

do this

n → n + 1

Is n ≤ 10?

Yes

No

UG1 Computing | Introduction to C++ | Loops

The while loop

int n=1;

while (n<=10)

{

cout << n*n*n << endl;

n++ ;

}

Try also thedo..while loop

Try also thedo..while loop

stop

n = 1

do this

n → n + 1

Is n ≤ 10?

Yes

Noinitialise counter

update counterat end of cycle

continuation condition

UG1 Computing | Introduction to C++ | Loops

The for loop

int n;

for (n=1 ; n<=10 ; n++)

{

cout << n*n*n << endl;

}

continuation conditionat start of cycle

initialise counterupdate counterat end of cycle

stop

n = 1

do this

n → n + 1

Is n ≤ 10?

Yes

No

UG1 Computing | Introduction to C++

More about semicolons

The following will not do what you want

for (n=1; n< 10; n++);

{ do this }

while (n<10);

{ do this }Semicolons have terminated

the for/while statements

UG1 Computing | Introduction to C++ | Loops

More on loops

Use integer loop counters if possibledouble t; // real number while (t < 8.0) { …t += 0.01;

} Can declare counter in loop

for (int n=1 ; n<=10 ; n++ ) { … }but n only exists within the for statement

Different results for a=7.999999 and a=8.000001

Task 10Task 10

Session 3Session 3

FunctionsFunctions

UG1 Computing | Introduction to C++ | Functions

What are functions?

Standard library functions• “Black boxes” of useful things: no need to

re-invent the wheelo Input/output <iostream>, <fstream>o Mathematics <cmath>

User-defined functions• Tasks repeated with different parameters• Structured programming: divide up large

computation into smaller self-contained tasks

UG1 Computing | Introduction to C++ | Functions

#include <cmath>

int main()

{

y = sin(x);

}

Using standard functions

y = sin(x)

mai

n()

Calculatesine

x

sin(x)

“black box”input

output

What do we need to know about the black box?

rememberheader

UG1 Computing | Introduction to C++ | Functions

Function prototype

Input (argument)• one double variable

Output (return value)• one double variable

Calculatesine

x

sin(x)

“black box”input

output

argumenttype

returntype

functionname

Function prototype: double sin(double)

Info already supplied by#include <cmath>

Info already supplied by#include <cmath>

UG1 Computing | Introduction to C++ | Functions

double mysine(double);int main(){ …

y = mysine(x); …

return 0;}

double mysine(double);int main(){ …

y = mysine(x); …

return 0;}

callsfunction

Writing C++ functions

double mysine(double angle)

{

double sine;

..calculate sin(angle) as sine

return sine;

}

double mysine(double angle)

{

double sine;

..calculate sin(angle) as sine

return sine;

}

function definition

function prototype

argument

return value

Your own sine function: mysine

UG1 Computing | Introduction to C++ | Functions

Local variables

Variables declared inside a function are local to the function

double mysine(double angle)

{

double sine;

..calculate sin(angle) as sine

return sine;

}

double mysine(double angle)

{

double sine;

..calculate sin(angle) as sine

return sine;

}

angle and sine have no meaningback in main()

UG1 Computing | Introduction to C++ | Functions

Arguments

You can have multiple arguments• Calculate first n terms of a Maclaurin series

expansion for sine(x)

double maclaurin(double x, int n) { … }

which will be called from the main program with a line like:

y = maclaurin(x, 10);Task 13Task 13

UG1 Computing | Introduction to C++ | Functions

…y = mysine(x);

…y = mysine(x);

Arguments: pass by value

Passing by value: value of x in main() is copied to local variable angle in mysine()

double mysine(double angle)

{

double sine;

..calculate sin(angle) as sine

return sine;

}

double mysine(double angle)

{

double sine;

..calculate sin(angle) as sine

return sine;

}

main()

Changing the value of angle inside mysine

does not affect x

UG1 Computing | Introduction to C++ | Functions

Structured programming

Use functions to divide your program into smaller self-contained tasks• Each task can be tested and debugged

independently• Simpler layout clarifies the logic of the code• Reduced chance of interference between

different parts of your code• Collect together useful functions for similar

projects

UG1 Computing | Introduction to C++ | Functions

Structuring your program

Simulate position and velocity from time t=0 to tmax in steps of dt

Use a function to compute new position and velocity at each time stepevolve(pos, vel, t, dt);

stop

Set initial positionand velocity

t=0.0

Compute newposition and

velocity

t → t + dt

t ≤ tmax?

Yes

No

evolve

UG1 Computing | Introduction to C++ | Functions

double pos=pos0,vel=vel0,t=0.0;...for (int n=0; n<nmax ; n++){ evolve(pos,vel,t,dt); …}

double pos=pos0,vel=vel0,t=0.0;...for (int n=0; n<nmax ; n++){ evolve(pos,vel,t,dt); …}

Arguments: pass by reference

int evolve(double& x, double& v, double& t, double dt)

{ …

x = … ;

v = … ;

t += dt;

return 0;

}

int evolve(double& x, double& v, double& t, double dt)

{ …

x = … ;

v = … ;

t += dt;

return 0;

}

x, v and t refer to the same variables

as pos, vel and tin main()

main()

Memory locations of the arguments are

copied to the function

Alternative: use structures

Alternative: use structures

How to return updated position and velocity??

UG1 Computing | Introduction to C++

Passing Arguments

Passing by value• Values of arguments copied to local

variables in function• Calling the function cannot change arguments

Passing by reference• Memory locations copied: local variables

refer to the same variable in calling function (even if different names)

• Calling the function can change the arguments

Task 12Task 12

UG1 Computing | Introduction to C++ | Functions

Structured programming

Use functions to divide your program into smaller self-contained tasks• Try this out in Task 15 on the simple

pendulum• You are expected to structure your code for

the projects in Section 3

ProjectsProjects

UG1 Computing | Introduction to C++

Assessment

Continuous assessment 50%• Personal performance: participation, effort,

motivation, effective use of demonstrators, lab book• Technical performance: C++• Weighted by fraction of lab sessions attended

Project report 50%• Choose one project (with demonstrator)• Hand in one week after last session to Level 4 lab

office• Late reports are heavily penalised

UG1 Computing | Introduction to C++

Project

Understand the physical/mathematical basis to the project

Effective use of basic computational techniques• Correct use of loops to perform repeated calculations

Structured programming • use functions to structure your program by dividing it

into self-contained tasks

Understand sources of numerical error Document your work in the lab book Present your results in a professional way

UG1 Computing | Introduction to C++

Report: content

Structure the report into logical sections Summarise your problem and your findings in a

short abstract (<100 words) Introduction to the problem you are studying Outline the algorithm employed (e.g. with a

flowchart) • do not describe actual C++ code in the report • a well-commented C++ listing as an appendix

Discuss and interpret your results Discuss errors: accuracy of approximations,

convergence of series

UG1 Computing | Introduction to C++

Report: professional style

Graphs should have properly labelled axes Figures should have numbered captions

Fig 1. Phase plot of the double pendulum.

Equations should be numbered, especially if they are referenced later in the report

x = 4 t (2.1)

UG1 Computing | Introduction to C++

Report: bibliography

All reading material (including web resources) should be cited in the bibliography.

Figures from the web must be properly cited.

It is plagiarism if you do not do these things!

UG1 Computing | Introduction to C++

Report: deadline

Hand in report to Level 4 Lab Office by 4pm on R2 date• 20% deducted for late reports and more if

more than 3 days late

Leave plenty of time for printing and hardware problems: many people will be printing their reports at the same time!

UG1 Computing | Introduction to C++

Further Info

Lab website

http://www.imperial.ac.uk/physicsuglabs/