First year computing

  • Upload
    kongooi

  • View
    230

  • Download
    0

Embed Size (px)

Citation preview

  • 8/7/2019 First year computing

    1/50

    Version 2.7

    Bl

    FirstCOMPU

    Head of 1st Year Comput

    Email: dkk.lee@imperia

    Office: Blackett 809

    ckett Laboratory

    Year LaboratoryING LABORATORY

    2008-9

    ing: Derek Lee

    .ac.uk

  • 8/7/2019 First year computing

    2/50

    Version 2.7 2

    Table of Contents

    1 Background information ............................................................................................................ 41.1 Course Aims ........................................................................................................................... 41.2 Laboratory Sessions ............................................................................................................... 41.3 Course Structure ..................................................................................................................... 51.4 Lab Books ............................................................................................................................... 51.5 Assessment ............................................................................................................................. 51.6 Useful Documentation and Online Help ................................................................................ 6

    2 Introduction to C++ .................................................................................................................... 72.1 What is C++? .......................................................................................................................... 72.2 Using Visual Studio ................................................................................................................ 7

    2.2.1 Creating a C++ program .................................................................................................. 72.2.2 Saving your program ....................................................................................................... 92.2.3 Ending a session .............................................................................................................. 92.2.4 Resuming work ................................................................................................................ 9

    2.3 C++ Program Structure .......................................................................................................... 92.4 Comments ............................................................................................................................. 112.5 Building and Running a Computer Program ........................................................................ 112.6 Arithmetic in C++ ................................................................................................................ 122.7 Branching ............................................................................................................................. 13

    2.7.1 if................................................................................................................................... 132.7.2 Comparing value ............................................................................................................ 142.7.3 if else ................................................................................................................ 152.7.4

    switch ......................................................................................................................... 16

    2.8 Loops .................................................................................................................................... 18

    2.8.1 while ........................................................................................................................... 192.8.2 do...while ............................................................................................................... 202.8.3 ..for ........................................................................................................................... 202.8.4 More on loops ................................................................................................................ 212.8.5 A program to calculate factorials ................................................................................... 212.8.6 Writing output to a file .................................................................................................. 23

    2.9 Variables ............................................................................................................................... 242.9.1 Variable names .............................................................................................................. 242.9.2 Variable types ................................................................................................................ 242.9.3 Caution with C++ arithmetic ......................................................................................... 25

    2.10 Structured Programming & Functions .............................................................................. 272.10.1 Standard functions ...................................................................................................... 272.10.2 Writing your own functions ....................................................................................... 282.10.3 Passing arguments to a function ................................................................................. 31

    2.11 Debugging and Good Practice .......................................................................................... 332.12 Series Expansion for sin(x) ............................................................................................... 342.13 Arrays and Vectors............................................................................................................ 36

    2.13.1 Using basic arrays ...................................................................................................... 362.13.2 The vector class .......................................................................................................... 372.13.3 Passing arrays and vectors to functions ...................................................................... 372.13.4 Multi-dimensional arrays ........................................................................................... 38

    2.14 Finite differencing an example using the simple pendulum .......................................... 39

  • 8/7/2019 First year computing

    3/50

    Version 2.7 3

    3 Short Computing Projects ........................................................................................................ 413.1 Fourier Series ....................................................................................................................... 42

    3.1.1 Fourier series for a square wave .................................................................................... 423.1.2 Fourier filtering .............................................................................................................. 423.1.3 Accuracy ........................................................................................................................ 43

    3.2 Numerical Integration ........................................................................................................... 443.2.1 Trapezium rule ............................................................................................................... 443.2.2 Simpsons rule ............................................................................................................... 453.2.3 Error analysis ................................................................................................................. 45

    3.3 Double Pendulum --- Chaos & Unpredictability .................................................................. 463.3.1 Motion of the Lower Pendulum ..................................................................................... 463.3.2 Investigating Chaos & Unpredictability ........................................................................ 47

    Appendix 1. The Preprocessor................................................................................................... 48Appendix 2. How to get out of a mess ....................................................................................... 49Appendix 3. Disk Files and Printing ......................................................................................... 50

  • 8/7/2019 First year computing

    4/50

    Version 2.7 4

    1 Background information

    1.1 Course Aims

    Scientific programming is an important part of the professional physicists toolbox.

    Experimentalists write programs to analyse large volumes of raw data and control their instruments.Theorists use the computer to perform numerical computations and to simulate physical models.

    Throughout your physics degree course, you will be using computers for lab and project work.

    This course is an introduction to the basics of scientific programming, giving you some idea of the

    way in which computers are used in science. The programming language we have chosen to use is

    C++. We hope that you will start building up good programming habits which will be a sound

    foundation for more advanced courses later.

    In this course, we aim to

    teach the basic elements of scientific programming using the C++ language

    introduce the concept of structured programming in code design

    introduce the concept of numerical methods to model physical systems

    By the end of the course, you should be able to

    understand the structure of C++ programs and write simple C++ programs

    understand the use of integer and floating point (double) variables, including issues of

    rounding error and machine accuracy

    make use of loops in a program using for and while blocks

    control program flow with conditional statements (if, if/else, switch)

    make use of one-dimensional arrays and understand array bounds (using basic C++ arrays

    or the vector class) make use of standard C++ libraries (input/output, mathematical)

    understand the concept of structured programming through the use of user-defined

    functions

    understand how to pass arguments to a function (by reference and by value)

    write functions to compute mathematical series, such as the Maclaurin or Fourier series

    use a finite-difference method to model one-dimensional ordinary differential equations, in

    particular, time evolution in Newtonian mechanics

    The course is designed such that a student with no programming experience at all should be able to

    follow the course. It provides the essentials of C++ but leaves some of its more powerful aspects(specifically Object Oriented Programming) to the 2nd

    year course.

    Some of you will have experience in programming. The projects in section 3 are designed to have

    an open-ended component which will give the experienced programmer more opportunities to

    explore numerical analysis. Note that C++ is different in important ways from other programming

    languages. Moreover, scientific programming and numerical computation involves a different set of

    skills to programming for other purposes (e.g. database design). To be sure that you are not falling

    into unforeseen traps, you would be well advised to work through the script sequentially.

    1.2 Laboratory Sessions

    The computing lab course consists of8 three-hour sessions spread over 4 weeks. Lab sessions

    will always be held in the computing suite on Level 3 of the Blackett Lab in the teaching section to

  • 8/7/2019 First year computing

    5/50

    Version 2.7 5

    the left of the entrance. The room is for the exclusive use for the students belonging to that lab

    session. Working at home on your PC can supplement but not replace the lab sessions because

    continuous assessment of your progress takes place during these sessions (see section 1.5).

    Each lab session will be staffed by 4 demonstrators. All four demonstrators will be willing to help.

    They are there to answer your questions. However, they are not there to do the lab for you.

    Each student will have a demonstrator assigned to assess their work. Your demonstrator will makehim/herself known to you on the first occasion that he/she is in the lab. It is essential that you know

    who your assigned demonstrator is. He/she will regularly check on your progress and is responsible

    for the continuous assessment component of your lab mark (section 1.5).

    1.3 Course Structure

    This lab course is divided into two parts:

    The first part (Section 2) introduces the essential parts of C++ for a beginner. The script

    takes you step by step through a series of short TASKS, introducing you to various

    elements of C++. You should complete all the tasks.

    The second part (Section 3) consists of three projects. They no longer lead you in a step-by-step way. They are designed to encourage you to think about how to plan a computation

    and how to design the code using the C++ you have learnt from the first part. You are

    encouraged to do as many of the projects as you can, but you must complete at least one of

    the projects and write it up to be assessed (see section 1.5).

    You should aim to complete the first part in about 4-5 lab sessions. That takes you to the start of

    week 3 of this four-week lab course. You will be very rushed if you have not started the second part

    by the end of week 3.

    1.4 Lab Books

    It is compulsory to keep a lab book for computing lab. Your lab book contributes to your markfor this course (see section 1.5).

    The key point is that the lab book should allow you to reconstruct in six months time what you have

    done and what you have learnt.

    The lab book should be a real-time record of your lab sessions. You should make notes directly

    into the lab book. Do NOT make notes on pieces of paper and write them up in your lab book later.

    (There are no marks for neatness.)

    You should include plans or flowcharts which describe how you plan the algorithms. You should

    have a record of the programs you have written and your progress in developing/running them.

    Stick copies of program listings into your book with notes on how the programs work. Also keep a

    record of your results and write down any conclusions. Make a note of the things you learn or haveasked the demonstrator. If youve made a mistake, note that down too: it may help prevent your

    repeating it. Remember to date everything.

    Your demonstrator will come and check your lab books regularly. He/she will be able to give you

    advice and feedback on the content. General points on how to keep a lab book can be found in the

    Course Materials section of the department website: follow the links to First Year Laboratory.

    1.5 Assessment

    Out of the marks for this computing course, 50% of the marks are awarded viacontinuous

    assessment of your progress in the lab. Marks are decided by your demonstrators on the basis of

    your performance in lab and by looking at the record of the tasks in your lab book. (The content of

    the lab book becomes part of the continuous assessment from session 5 onwards.)

  • 8/7/2019 First year computing

    6/50

    Version 2.7 6

    Marks are weighted by your attendance record. So, working at home can supplement but should

    not replace the lab sessions. This is so that you can make full use of the demonstrators, and the

    demonstrators can keep an eye on your progress.

    The other 50% of the marks will be awarded based on a project report to be written at the end of

    the four-week session. You have a week to write the report. The report should describe in detail

    one of the projects in sections 3.1 to 3.3. More details concerning what should be included in the

    report are given at the start of section 3.

    1.6 Useful Documentation and Online Help

    Electronic copies of this lab script and Introduction to the Computing Laboratory can be found on

    the department website: follow the links to Course Materials. They are also available on WebCT.

    They are accessible from anywhere. You will be prompted for your college username and password.

    You will also be given a copy ofIntroduction to C++ by Jordan Nash and Paul Dauncey which

    covers all the C++ you will need in the first year (and a little more). It is therefore a useful

    reference document for the core features of the C++ language. An electronic copy of this document

    can also be found on the department Course Materials website.Extensive online information on C++ is available within the Microsoft Visual Studio framework.

    While you are using Visual Studio, click on Help and then any ofContents, Search or Index. In

    the Active Subset box select Visual C++ Documentation; you can then use Contents, Index or

    Search to find the appropriate topic.

    If you find any errors in the script, or have any comments on how we can improve the course,

    please let me know. My email is:[email protected].

  • 8/7/2019 First year computing

    7/50

    Version 2.7 7

    2 Introduction to C++

    2.1 What is C++?

    C++ is a programming language. It enables you to write programs to pass instructions to thecomputer. It is one of the most widely used computer languages nowadays. Other languages

    commonly used for scientific computing include C, Fortran90, Pascal, Algol, MODULA-2, Basic,

    and Java. C++ forms the basis of many application programs, and experts in C++ and Java are

    much sought after in the financial sector. C++ is a more advanced form of C and includes more

    sophisticated concepts such as object-orientated programming. You will learn more about this in the

    2nd

    year computing lab.

    2.2 Using Visual Studio

    This section tells you how to use the Microsoft Visual Studio as an environment for you to write

    C++ programs.

    2.2.1 Creating a C++ program

    To perform a mathematical calculation on a computer you first create a list of commands (known as

    the program) which the computer can subsequently be told to follow (known as running or

    executing the program). In order to start programming, you have to start the Microsoft Visual C++

    programming environment and then create the project into which the C++ program will go. Frankly,this part is very tiresome, but you will get used to it.

    TASK 1. Follow the steps below to create a program.

    Setting up the Programming Environment

    On the Start menu under Programs, find Microsoft Visual Studio 2008. Hovering your mouseover it produces a submenu. Choose from the submenu the item Microsoft Visual Studio 2008.

    [ This step is for the first time you use Visual Studio. ] A Choose Default Environment window

    appears. Choose Visual C++ Development Settings. It takes a little while to configure the

    environment when you use it the first time.A Start Page appears.

    Visual Studio groups files into solutions and each solution can contain several projects. We do

    not need this level of sophistication. We will keep things simple: each task corresponds to one

    solution containing only one project.

    The following are instructions to create the right configuration for these projects for our purposes.

    IMPORTANT: You should create a new project for each new program you write.

    On the menu bar, click on File. A drop-down menu will appear. Then clickNew, andanother drop-down menu appears. Choose Project

    You will now see a new window entitled New Project. We have to choose which type of

    project to create. We want a Win32 Console project. Click on Visual C++ in the left-hand

    pane of the window. You should see a list of installed templates on the right-hand pane.

    Select Win32 Console Application in this pane. (You may have to scroll down the list of

    icons in the right-hand pane to find it.) NB: DO NOT select Win32 Project or Win32

    Smart Device Project.

    Choose a name for the solution and decide where to put the files for this solution. Type

    the name of the project/solution, in this case ncube, into the box labelled Name. The

    Solution Name box will be filled automatically with this name as well. Files should be

    stored on the H: disk (which is also called My Documents). We suggest that you put them ina folder called H:\firstyear (type this into the box labelled Location). Now, make sure the

  • 8/7/2019 First year computing

    8/50

    Version 2.7 8

    box Create directory for solution is not ticked. Now click on the OK tab to finish

    creating the project. A new folder called H:\firstyear\ncube has now been created inside the

    folder H:\firstyear

    A new window appears: the Win32 Application Wizard. Click on Application Settings tosee settings for this project. Click on the tick-box for Empty project. And then click on the

    Finish tab.

    You have now created a project workspace for Visual C++. This is the place where all filesconnected with a project are stored. You should see the relevant programming files in the

    Solution Explorer on the left-hand pane. The most important file is the C++ program you

    write (the source code), but there can be other files too, such as header files and files that

    Visual C++ generates automatically.

    One more step is necessary for setting up the project workspace. You have to decide where

    temporary files will go: you dont want them on your H disk as they would rapidly fill up

    your disk allocation and stop any programs running. At the top of the window, go to Project

    and choose Properties (the last entry in the drop-down menu). Under Configuration

    Properties on the left-hand pane, click on General. You should find entries called Output

    Directory and Intermediate Directory.For both of these entries, change them toC:\temp\your_username\Debug. Then, click on the OK tab to finish.

    You should see the Solution Exploreron the top left pane. (If you do not see it, go to Viewon the menu bar and select it in the drop-down menu.) This displays all the files that a

    programmer would need in developing the code for the project. The files are displayed as a

    tree under the project name, in this case ncube.

    Every project must have a file containing the program. This is called the source code. Let

    us now add a C++ source file (with the suffix .cpp) to the project. To do so, click on the

    Source Files tab in the tree under ncube. Then, right-click on the mouse to obtain a drop-

    down menu. Select Add and then New Item when a further drop-down menu appears.

    (Do notuse File | New | File from the menu bar which creates a new file but does not add it

    to your project automatically.) A window appears. Select C++ File (.cpp) in the list in theright-hand pane. Enter a name at the bottom, in this case ncube. ClickAdd to finish with

    this window. This creates a file called ncube.cpp under the H:\firstyear\ncube folder. The

    contents of this file appear on the right-hand pane of the main Visual C++ window (which is

    currently blank) under the name ncube.cpp. This file is where you will write the main

    program.

    In the white box headed ncube.cpp, now type in the following program. It is a simple program to

    calculate the cube of any integer entered by the user. Follow the punctuation carefully and note

    that C++ is case-sensitive (i.e. Include, INCLUDE or InClUdE are not the same as include.)

    // Program to calculate the third power of a number

    #include using namespace std;

    int main()

    {

    int n, ncube;

    cout > n;

    ncube = n * n * n; // Assign the value of n*n*n to ncube

    cout

  • 8/7/2019 First year computing

    9/50

    Version 2.7 9

    2.2.2 Saving your program

    You should now save the program you have just typed in: click on File and choose Save All. This

    will save the program file and other project files associated with it. (Use Save All and notSave. The

    latter only saves the file that is currently open in the Visual Studio window.) Alternatively, you can

    click on the icon on the menu bar which looks like 3 floppy disks on top of each other.

    IMPORTANT: make a habit of saving your work regularly. I save my work every 5 minutes.That way, the most I can lose (if I deleted a huge chunk of code by accident) is 5 minutes of work.

    2.2.3 Ending a session

    After saving your work, it is safe to use File | Exit to leave Visual Studio. Do this now as practice.

    2.2.4 Resuming work

    To resume your work, start Visual Studio 2008 again. Then, in the Visual Studio, click on File then

    Open then choose Project/Solution.... Do notuse File | Open | File. (i.e. choosing File, then Open

    in the submenu, then File in the drop-down menu.) The latter just opens the file as a text file for

    viewing. It does not add it to the Visual C++ environment for compiling and building.

    A file dialog window should appear. Browse through the directories to find your project. All the

    relevant folders should be at H:\firstyear\. Since we are looking for Task 1, click on the folder

    called ncube. Then the window should list two files called ncube. One is the Solution file and one is

    the project file. (Hovering the mouse over the file name tells you which type of file it is.) You can

    open either of them. You can now continue from where you left off previously.

    Alternatively, you can use the file browser in Windows to find the files. Go to My Documents and

    look for the folder H:\firstyear\ncube. It should list several files called ncube. Double click on the

    one labelled Microsoft Visual Studio Solution or the one labelled VC++ Project. Either should

    work. The computer will then launch the Visual C++ application and open the project in it.

    2.3 C++ Program Structure

    Now, let us return the program ncube in section 2.2.1.

    Its logic is simple. The program reads in an integer from

    the keyboard, calculates its cube and then outputs the

    result to the screen.

    This is depicted in the flowchart on the right. The

    flowchart is a useful tool in designing an algorithm. It

    makes you concentrate on the logic of the algorithm,

    rather than the syntax of your C++ code.

    IMPORTANT: Use a flowchart to design an algorithm

    before implementing it in C++.

    There is a convention that a rectangle contains a simple

    process and a trapezium represents an input/output step.

    (Later on, you will see that a decision step is represented

    by a rhombus.)

    Now, let us examine the syntax of the C++ program that

    you have typed in. The main part of the program which

    does the computation is within the section of code (a

    function) called main which lives between the curly

    brackets { and }. The lines above the main section can be regarded as a preamble that prepares the

    compiler for the commands used in the computation.

    In the program above, each line may be explained as follows:

    Calculaten*n*n

    End

    screen

    Read

    integer n

    Output

    result

    keyboard

    Start

  • 8/7/2019 First year computing

    10/50

    Version 2.7 10

    [Line 1] Everything between the // and the end of the line is ignored. See section 2.4 below onthe use of Comments. Visual C++ recognises these as comments and presents them in green.

    [Line 2] This makes the Visual C++ insert the contents of the C++ file iostream into the

    program. This file contains definitions that are necessary for you to use input and output

    statements (e.g. cout and cin).

    [Line 3] tells the Visual C++ that you will be using routines from a standard library. Recognisedkeywords in the C++ language, like include and using, are presented in blue.

    [Line 4] says that what follows is the main function. A C++ program may consist of many

    functions but there must always be one called main in which the program starts.

    [Lines 5 & 12] The { and the } define a section of code, in this case the function main. The

    ability to group lines of code like this is very useful.

    [Line 6] says that n and ncube represent integer variables, i.e. whole numbers. (For other types

    of variables, see section 2.9.2). Any quantity used in a C++ program must be declaredin such a

    statement before it is used. This is usually done at the top of the program. By declaring a

    variable, you have in fact told the computer to allocate space in its memory to store it (4 bytes =

    32 bits for an int integer). Then, you can use the variable name to refer to this variable (the

    content stored at this chunk of memory) in the rest of the main function. Note that no default

    value is assigned to a variable when it is declared: you have to do it explicitly. Notice that the

    end of the statement is marked by a semi-colon ;.

    [Line 7] cout n; This asks the computer to wait for the user to type a number on the

    keyboard (followed by carriage return). This number is read from the keyboard and assigned tothe variable n. Here the arrows >> signify the stream of data is into the program from the

    standard input channel cin (usually the keyboard). When reading in more than one number

    from the keyboard, the individual numbers can be separated by blanks or new lines. Each

    variable must be prefaced by >> e.g. cin >> a >> b >> c; to read in three numbers.

    [Line 9] * stands for multiply. ncube = n * n * n; multiplies n by itself twice, and

    assigns the result to ncube. Everything on this line after // is ignored by the computer. It is

    a comment for humans who read the code. (See section 2.4)

    [Line 10] This line writes out the values ofn and ncube. Note the tab character \t which is

    included to separate the values for n and ncube: we have to tell the computer explicitly to

    insert the tab spacing between the two numbers. You can also use a string of spaces: " ". (Forone character, we can use single quotes. For more characters, we need double quotes.) We also

    have to tell the computer to place an explicit line break: the keyword endl inserts this end-of-

    line code into the output stream.

    [Line 11] The return keyword is another key command in C++. When we run the program and

    the computer comes to this line, it stops the execution of the main function. (So, you will

    frequently find a return statement at the end of sections of code.) In this case, it means that the

    program is done. The line also gives a value of 0 to the function main. Don't worry about it for

    now; its use will become clearer later when functions are called from main or other functions.

    Note the semi-colon at the end of (nearly) every line. This can be thought of as the punctuation

    in the C++ language that defines the end of a statement.

  • 8/7/2019 First year computing

    11/50

    Version 2.7 11

    2.4 Comments

    If you come back to a program you have written 6 months earlier or if you want to use somebody

    else's program, it can be difficult to sort out how it works from the code alone. Therefore, you

    should always add comments to the program.

    Anything between // and the end of the line is ignored by the compiler, so comments can be on the

    same line as a C++ statement. Multiple lines, each preceded by //, are fine. A large block can also

    be commented out using /* and */, e.g.

    /* Here is a comment block with lines of comments,

    all ignored by the compiler.

    */

    It is usual to place a few comments at the beginning of a program and at the beginning of each

    function to describe its purpose, and probably who wrote it and when it was last edited. Further

    comments are usually added in the body of the program describing how it works, e.g. at the

    beginning of an important loop or branch.

    2.5 Building and Running a Computer ProgramTASK 2. Compile, build and run the program by following the instruction below.

    So far we have written a program in C++ code. In general, this should be independent of the

    operating system being used (in our case Windows). This has to be translated this code into a form

    that the central processing unit (CPU) understands. This process is called compilation. To do this,

    choose Build | Compile on the menu bar (by this, I mean choose Build from menu bar, and then

    choose Compile in the submenu). If you do not see the Compile item in the Build menu, it is

    usually because the application does not know what to compile --- click on the name of source code

    file (.cpp file) in the Solution Explorer so that it is highlighted.

    If the compiler notices any errors, they will be listed in the white panel at the bottom of the window.

    To identify the location of an error, double click on the error message and an arrow will appear in

    the code pointing to the offending line. At this stage, you can edit the program to remove these

    errors, and compile again to check that you have fixed the problem. Note that the compiler will

    include all files in the current project workspace. A successful compilation will result in an object

    code file ncube.obj being created (in the Debug folder).

    The next step is to buildor link the compiled code with any code libraries needed by the program.

    For instance, in the program above, the library iostream is used by the program for the input

    (cin >>) and output (cout

  • 8/7/2019 First year computing

    12/50

    Version 2.7 12

    If something else happens, your program has not worked, and further editing is needed. Programs

    hardly ever work first time. The (often lengthy) process of finding errors is known as debugging.

    One way to check if the program is doing what you expect is to systematically insert output

    statements at critical points in the code. If you have tried but cannot see the solution, ask for help.

    To summarise, the stages involved in creating and running a program are:

    Write code Compile Build (Link) Execute (Run)

    2.6 Arithmetic in C++

    Basic arithmetical operations use the symbols:

    + for addition - for subtraction

    * for multiplication / for division

    Variable names are names of locations in memory. The command m=n+k; means:

    Fetch from memory the numbers held in locations n and k.

    Add the two numbers together.

    Put the resulting answer into memory location m, overwriting its previous contents.

    In other words, the = sign is an assignment operator: it assigns the value ofn+k to m. It does not

    mean equal to. For instance, even though n can never be equal to n+1, the command n = n +

    1 is perfectly sensible: it calculates the value ofn+1 and then assigns the result back to n. In other

    words, it increases the original value ofn by 1.

    C++ has some useful abbreviations for such simple operations. The following four statements all

    produce the same result for n:

    n = n + 1;

    n += 1;

    n++;++n;

    It is also possible to use -=, *= and /= for the corresponding operators in subtraction,

    multiplication and division. For instance, n*=2 doubles the value ofn. Also, there is - for

    decrementing a number by 1, as in n--.

    CCHHEECCKKPPOOIINNTT You should have learnt and understood the following concepts.

    Structure of a C++ program: the role of the main function

    How to write, compile and run a C++ program in the Visual Studio environment

    Declaration and initialisation of integer (int) variables

    Simple arithmetic in C++: +, -, * , /, +=, -=, *=, /=, ++, -- Understand the meaning of the = operator

    How a program can take input from the keyboard and print output to screen.

    We will discuss issues that require care and attention in C++ arithmetic in section 2.9.3.

  • 8/7/2019 First year computing

    13/50

    Version 2.7 13

    2.7 Branching

    We would often want an algorithm to do different things at a

    certain point depending what has happened before.

    In a flowchart, this is often represented by a decision box. In

    the example on the right, the algorithm splits into twobranches, with one branch handling the case of a negative n

    and another branch for n zero or positive.

    In this section, you will learn to control program flow in C++

    using if and switch statement blocks.

    2.7.1 if

    Often we want a program to do something if a certain condition

    is satisfied. The general form is:

    if (condition) statement;

    Suppose we want to calculate the absolute value of a number.

    First of all, we ask for this number as an input from the keyboard

    and assign the value to an integer variable n. If it is a positive

    integer, then its absolute value is itself: nabs = n. If it is

    negative, then we will have to change the sign ofnabs. The

    logic is illustrated by the flowchart on the left.

    The decision to change the sign ofnabs ifn < 0 can be

    achieved by the statement:

    if ( n < 0 ) nabs = -nabs;

    which assigns n to nabs ifn is negative.

    The whole program would look like this:

    // Program to calculate the absolute value of an integer

    #include

    using namespace std;

    int main()

    {

    int n, nabs; // declare integer variables// n = input value; nabs = abs value

    cout > n; // get input from user

    nabs = n; // set nabs to n anyway

    if ( n < 0 ) nabs = -nabs; // fix the sign of nabs if needed

    cout

  • 8/7/2019 First year computing

    14/50

    Version 2.7 14

    {

    statement1;

    statement2;

    ...

    } // No semicolon needed here either

    The curly brackets { } are used to group these statements together into a block and can be treated

    as a compound statement. For example, in the above program, you may also want the program to

    inform the user if it has recognized a negative input. The if statement above can be replaced by:

    if ( n < 0 )

    {

    cout = 5 n greater than or equal to 5

    n < 5 n less than 5

    n

  • 8/7/2019 First year computing

    15/50

    Version 2.7 15

    2.7.3 if else

    Sometimes you want to do one thing if a condition is fulfilled and something else if it is not. You

    can do this using an if else construction.

    For instance, we can rewrite the program for absolute value as follows:

    int main()

    {int n, nabs;

    cout > n;

    if ( n < 0 )

    {

    nabs = -n;

    } else

    {

    nabs = n;

    }

    cout

  • 8/7/2019 First year computing

    16/50

    Version 2.7 16

    }

    else if (iopt == 2 )

    {

    do this if option 2 is chosen;

    }

    else

    {cout

  • 8/7/2019 First year computing

    17/50

    Version 2.7 17

    The default clause is optional but highly recommended. It serves as a catch all for anything

    which does not fulfill any of the other conditions. Often this is used to generate an error message to

    say that the value ofiopt is invalid. The current example is a primitive way to handle errors. C++

    does provide more sophitisticated error handling but that is beyond the scope of this course.

    [ Note that if any of the case clauses contains a variable declaration, the whole clause, except the

    break statement should be enclosed in braces, {}. Such usage only makes sense when thevariable declared is only used for that particular case clause; otherwise the declaration should

    precede the whole switch statement. ]

    NB: For the following task, remember to start a completely new project for the program. Look back

    at TASK 1 for the procedure. The reason for this is that each project should only contain one

    main() function which controls the flow of the program execution. If there are two such

    functions, the computer would not know where the program execution starts.

    TASK 4. Follow the discussion below to write a program which calculates the third or

    fourth power of an integer depending on user input. You can either use an if..else or

    switch statement. You should be able to use the above examples for if..else or switch

    as templates for your code. Start a new project called Task4, adding a source file Task4.cpp to the project. Look back at

    TASK 1 for the procedure to start a new project.

    Add a skeleton for the main program, containing a main function which is empty except

    for the last return line:

    // Calculate third or fourth power of an integer

    #include

    using namespace std;

    int main()

    {

    // [ We will add code here ]return 0;

    }

    We have to declare the variables we want to use in this program. We will need integer

    variables for the number n and the power m to which it will be raised, and the result for nm,

    say power. We need the statement:

    int n, m, power;

    This should go at the start of the main function, i.e. after the left curly bracket {. (See

    program in TASK 1.) The declaration of variables is very important. Forgetting to do it is a

    frequent source of error for beginners.

    We need to initialise n and m by requesting user input. Use the cin and cout lines in thencube program from section 2.3 as templates.

    Although you have written just a few lines, save your work now (and save regularly from

    now on)! See section 2.2.2 for instructions.

  • 8/7/2019 First year computing

    18/50

    Version 2.7 18

    If we use ifelse statements, then the logic of the program can be represented by the

    following flowchart:

    Try to implement this in C++. You will need to use the construction:

    if ( m==3 )

    { }

    else if ( m==4 )

    { }

    else{ // emit error message and stop }

    cout

  • 8/7/2019 First year computing

    19/50

    Version 2.7 19

    the loop. The problem then is making sure that the program stops after a required number of

    iterations. The three C++ constructions, while , dowhile and for, all provide ways to

    perform a task in a loop until a certain condition is satisfied.

    2.8.1 while

    Suppose we want to calculate the 3

    rd

    power of theintegers from 1 to 8. The flowchart on the right is

    one way of doing this using a loop. The important

    elements of the loop are highlighted in bold.

    We have an instruction block that has to be

    repeated. We use a variable n as a counter

    (sometimes called index) whose initial value is

    set to 1. Before starting the instruction block, we

    test if the counter is less than or equal to 8. If it is,

    we execute the instruction block once. In this case,

    the instructions are to calculate the cube of the

    current value of the counter and output it to screen.

    Then, we increment the value of the counter and go

    back to the test to check the value of the counter

    again. The program cycles around the loop until the

    counter n reaches 9. Then, the cycle stops and it

    exits the loop. In this case, we have reached the end

    of the program.

    In C++, this algorithm becomes:

    // Calculate 3rd power of n for all n in range 1

  • 8/7/2019 First year computing

    20/50

    Version 2.7 20

    The while statement causes all commands within the braces { } to be repeated until the condition

    in round brackets () is no longer satisfied. To be more precise, at the start of each cycle of the loop,

    the computer tests if the condition in () is satisfied. If it is satisfied, the program runs through the

    block of statements between the braces once. It then returns to the top of the block and tests for the

    condition again. This is repeated again and again in a loop, until the occasion when the program, on

    returning to the top of the block, finds that the condition is no longer satisfied. Then, the program

    will stop the loop. It will then proceed to the first statement after the while block (in this case

    simply return 0;) and will carry on from there.

    The compound statement following the while clause is repeated as long as the condition in the

    brackets following the word while is true i.e. n < 8. The expression n 8. ]

    You can write any logical test you like for the condition to terminate the while loop. You should

    be able to construct them using the relational operators given in section 2.7.2.

    2.8.2 do...whileA do...while loop has the structure:

    do

    {

    one or more statements

    }

    while ( condition );

    This differs from a while loop in that the

    condition is tested at the end of the loop (see

    flowchart). In particular, since the whilecondition is tested at the end of the block of

    statements, the statements inside the curly

    brackets are executed at least once.

    Note that, for the same condition, the while

    loop may be executed a different number of times

    than the do...while loop.

    To do the next task, remember to start a new projectfor this new program.

    TASK 5. Using the flowchart above as a guide, adapt the C++ program in section 2.8.1

    for the while loop to use the dowhileto calculate the first 8 cubes. Remember to write a

    comment on each line of the program explaining what it does. Compile, build and run the

    program to be sure it works. Try out different conditions for the termination of the loop.

    2.8.3 ..for

    Although the syntax is less intuitive than the previous two, this is probably the most commonly

    used of the three loop statements. A for statement consists of 3 parts separated by semi-colons:

    (1st part ; 2nd part ; 3rd part)

    the 1st part is executed once before the loop starts, usually initialising the loop index.

    Calculaten*n*n

    screenOutput

    result

    n = 1

    add 1 to n

    n

  • 8/7/2019 First year computing

    21/50

    Version 2.7 21

    the 2nd part is a conditional statement, calculated at the start of each cycle of the loop. If itis true (or non-zero), the loop is executed; otherwise, the loop is terminated.

    the 3rd part is executed at the end of each cycle of the loop, usually incrementing the loop

    index.

    Thus, the dowhile loop in your TASK 5 program could be replaced by:

    int nmax = 8, n;for ( n = 1; n

  • 8/7/2019 First year computing

    22/50

    Version 2.7 22

    factorials. One possible algorithm is represented by the flowchart on the right. It works as follows.

    Instead of working out each of the factorials from scratch, we use the factorial of N-1 to work out

    the factorial of N because N! = N * (N-1)! So, starting with N = 1, we have 1! = 1. Then, we can

    work out 2! = 2*1! = 2, then 3! = 3 * 2! = 6, then 4! = 4 * 3! = 24, and so on. In other words, we

    require a loop!

    We make use of 3 integer variables. The integer variable, nmax, stores the largest N we want toreach. The integer n is the loop index. It is also the number N whose factorial we are calculating.

    The third variable, nfact, is the factorial itself which is calculated every time we cycle through

    the loop.

    Now, we can implement this loop in C++.

    Start a new project called Factorial, adding a source file Factorial.cpp to the project.

    Add a skeleton for the main program, containing a main function which is empty except

    for the last return 0 line. (See TASK 4.)

    Declare the variables for this program by putting at the top of the main function:int nfact = 1, nmax = 10;

    We want to cycle through the loop nmax times. The variable nfact will store the value of

    the nth factorial. In addition to declaring the variable type (int), I have also set the initial

    values ofnfact to 1 and nmax to 10. The declaration and initialisation of variables are

    very important, and forgetting to do them is a frequent source of error for beginners.

    Let us now put in the for loop structure:for (int n = 1; n

  • 8/7/2019 First year computing

    23/50

    Version 2.7 23

    2.8.6 Writing output to a file

    So far, the results of the calculation have appeared on your screen. You may want to print them, or

    plot them, or simply keep them. In that case, it is often more convenient to write the output of your

    program to a disk file rather than to the screen. The facility to do this is contained in the fstream

    library. To use this library, you have to include the header file fstream, which contains the

    definitions of various commands that you need. The syntax is very similar to the cout syntax forprinting to the screen. Instead, you have to declare a new output stream (type ofstream) and

    identify this as output to a particular file with a given filename. This is achieved with the

    statements:

    #include

    int main()

    {

    ofstream stream1("any_filename_you_like");

    ...

    stream1

  • 8/7/2019 First year computing

    24/50

    Version 2.7 24

    2.9 Variables

    All variables must be declared by a type and a name. This is usually at the top of the program. In

    this section, we will learn more about variables. We will concentrate on numerical types and show

    you some common pitfalls with arithmetic in C++ involving integer and/or floating point variables.

    2.9.1 Variable names

    We have called the variables in the program by simple labels such as i, m, nmax, but variable

    names can consist of any number of characters. Each character can be either an upper or lower case

    letter or a number, except that the first character must be a letter. In addition, the underline

    character _ is also allowed in variable names. Upper and lower case letters are distinct in C++

    (unlike the file names of the Windows system). [NB: in the Visual Studio, only the first 32

    characters are meaningful.]

    It is highly recommended that you give your variables meaningful names. For example you may

    want to call variables radius, sum, speed, mass etc, which makes possible commands such as

    area = 0.5 * base * height;All the keywords of the C++ language are lower case: e.g. main, int, for, while , all

    these must be followed by a space. Some keywords are reserved, i.e. you cannot choose them for

    one of your variables; they include asm, auto, bool, break, case, catch, char,class, const, continue, default, delete, do, double, else, enum,

    extern, false, float, for, friend, goto, if, inline, int, long,

    new, operator, private, protected, public, register, return,

    short, signed, sizeof, static, struct, switch, template, this,

    throw, true, try, typedef, union, unsigned, virtual, void,

    volatile, while.

    2.9.2 Variable typesC++ has several built-in variable types. We have so far used only integer variables (int). It is

    useful to understand what they represent and how they are stored in the computer memory.

    char

    a character variable used to store text characters. The storage space used by a char variable is 1

    byte = 8 binary digits or bits. As there are 28

    (=256) ways to set 8 bits, the char variable may have

    values 128 to +127. There are conventions for how these values represent text characters.

    int

    an integer variable stored in 4 bytes = 32 bits. So it can represent numbers from 231

    to +(231

    -1), i.e.

    2147483648 to +2147483647.double

    a floating point representation of a real number (i.e. one with a decimal point) using 8 bytes (= 64

    bits) of memory. However, by making use of exponents, double variables can represent numbers

    much larger than 263

    , in fact positive or negative numbers in the range 1.7x10-308

    to 1.7x10+308

    with

    15 decimal places of precision. There is in fact a 4-byte float for floating point numbers too, but

    the precision is too low for meaningful scientific computation.

    const int, const double

    We can also put the qualifier const in front of variables to indicate that they are constants, i.e.

    their value cannot be altered in the program. For example, you may want to define a constant

    variable pi to contain the value of:

    const double pi=atan(1.0)*4; [using the fact that tan(/4)=1.]

  • 8/7/2019 First year computing

    25/50

    Version 2.7 25

    It is good programming practice to use const to avoid unforeseen consequences due to

    inadvertently changing quantities that should be kept constant. It also allows the compiler to

    optimise the executable to run faster. We will see other reasons for using this later (sections 2.10.3.3

    and 2.13.1).

    TASK 8. Type in the program below. Figure out what it does and comment it as

    appropriate. Compile, build and run it using the given values of a, b, c and d. Use Excel toplot the results (a graph ofpoly as a function ofx). It is important to devise simple reality

    checks to see that your results are at least roughly what you expect. Think of at least two

    simple checks for this task (which does not involve using a calculator) and show your

    demonstrator that the program does what you expect for your tests.

    // C++ Program

    #include

    using namespace std;

    int main()

    {

    ofstream myfile(polyval.txt);

    const double dx = 0.10, a = 0.0, b = 18.0, c = -11.0, d = 1.0;double x=0.0, poly;

    for (int i = 0; i < 100; i++)

    {

    x += dx ;

    poly = ((d*x + c)*x + b)*x + a;

    // why not use d*x*x*x + c*x*x + b*x + a ?

    myfile

  • 8/7/2019 First year computing

    26/50

    Version 2.7 26

    19.999999999999 or 20.000000000001. If it is the latter, the loop will notexecute the 20th

    time and

    20! will not be evaluated. Do not use floating point variables with relational operators unless

    you are sure that rounding errors will not cause problems in terms of precision or accuracy.

    2.9.3.3 Integer arithmetic

    The result of all operations between integers is another integer. For integer division, the result is

    truncated towards zero. Thus:int p = 11, q = 3, r;

    r = p / q;

    will truncate 11/3 = 3.6667 down to 3 and assign the value 3 to r. In general, it is unwise to divide

    integers unless you are absolutely sure that that is really what you want to do.

    C++ also has a symbol % which signifies the remainderafter the division of two integers. Thus,

    r = p%q assigns the value 2 to r for the values ofp and q above.

    2.9.3.4 Arithmetic with mixed variables types

    When floating point and integer numbers are mixed in the same expression, the integers will only

    be converted to floating point immediately before they are combined with a floating point number.Consider the following code fragment:

    int n =1, m = 2;

    double x = 1.0, y, z;

    y = (x * n) / m;

    z = x * (n / m);

    The result of this calculation is that y=0.5 but z comes out as zero! This is because, in the formula

    x*(n/m), the operation in brackets is performed first with the integerresult of 1 / 2 = 0. On the

    other hand, for (x*n)/m, x*n is calculated first as 1.0 * 1.0 = 1.0 and then divided by 2.0.

    2.9.3.5 Operator priorities and brackets

    Brackets can be used as in any conventional mathematical expression, e.g.y = (x + 4.0) * (x * x - 3.5) / (x + 6.4);

    When faced with ambiguous expressions, C++ performs all *, / and % operations before all + and -

    operations. Consequently:

    y = a * b + c * d; means y = (a * b) + (c * d);

    If the expressions are still ambiguous it starts at the left and takes each operation in turn. Without

    brackets, some expressions are ambiguous. So,

    y = a / b * c; means y = ( a / b ) * c;

    y = a / b / c; means y = ( a / b ) / c;

    The last one is of course equivalent to a /(b*c). Best practice is to play safe and insert bracketsif you are unsure.

    CCHHEECCKKPPOOIINNTT You should understand the implications for using int and double

    variables for representing numbers in C++, including consequences of machine precision,

    overflow, integer arithmetic and arithmetic with mixed types.

  • 8/7/2019 First year computing

    27/50

    Version 2.7 27

    2.10 Structured Programming & Functions

    There can be thousands of lines of code for serious computations. Different parts of the code might

    even be written by different people in a team. How do we cope such large projects? This is where

    structured programming becomes important. The first step is to understand how the computation

    can be split into a set of smaller specific tasks. Then, these tasks can be separated out into self-containedblocks of code. These are called functions in C++.

    A major advantage of functions is that they can

    be used many times within a program without

    the code being duplicated, thus making the

    program shorter. For example, if we need to

    calculate the cosine for many different angles in

    the same program, the cosine evaluation can be

    done within a function. In fact, there are many

    function libraries which provide commonly

    used mathematical and statistical functions. For

    the cosine, you do not have to reinvent thewheel: just use a library called cmath which

    contains the function cos. Whenever we want

    to evaluate a cosine, we simply call this

    function from the program with a line like:

    y = cos(x);

    Functions are self-contained in the sense that each function can be treated as a black box whose

    internal workings we do not need to understand. We only need to know the variable type of the

    inputs (arguments) to the function and the type of its output (return value).

    You can also write your own functions. Suppose, for example, we wanted to write a code which,

    given the positions and velocities of the planets at any point in time, would predict their positionsand velocities some short time later. We could either write a code with 9 sections (each doing the

    calculation for a different planet) or write a function, called trajectory say, which could be

    called by the main function 9 times with different physical parameters corresponding to different

    planets. Clearly the latter method is neater, less prone to error and immediately applicable when

    new planets are discovered.

    The need for repetition is not the only criterion for employing functions: smaller blocks of code are

    more manageable in that they can be written and tested independently. Taking the planetary code as

    an example, the task of reading the inputs containing the physical parameters of the solar system

    can be separated into a self-contained process. Similarly, we may want to separate out the task of

    the detailed formatting of how the results should be presented in the output. The key point is thatthey do not interfere with the core calculations of the planetary orbits.

    You have already used the function main which contains the code necessary to control the

    program. Other functions are defined outside the main code segment but can be used in (called

    by) it. Sometimes, the main function is the shortest piece of code that simply controls the overall

    logistics of the program flow while all the hard numerical work is done by a large set of functions.

    Structured programming is very important for any program longer than 50 lines, and you are

    strongly encouragedto use functions to structure your programs in the longer tasks in Section 3. It

    simplifies the job of writing and debugging the program immensely.

    2.10.1 Standard functionsIn C++ functions such as sine, cosine, exponential etc. are already provided and stored in the library

    cmath. In order to use these functions you have to insert the statement:

    y=cos(x)

    main

    Calculate

    cosine of x

    cos

  • 8/7/2019 First year computing

    28/50

    Version 2.7 28

    #include

    at the beginning of your program.

    Commonly used C++ functions:

    Function name Description Return value type

    sin(x) sine of x (x in radians) Doublecos(x) cosine of x (x in radians) Double

    tan(x) tangent of x (x in radians) Double

    asin(x) arcsine (in radians) of x

    between /2

    Double

    acos(x) arccosine (in radians) of x

    between 0 and

    Double

    atan(x) arctangent (in radians) of x

    between /2

    Double

    exp(x) ex

    Double

    log(x) logex Double

    log10(x) log10x Double

    abs(x) absolute value (modulus) of x int for integer x

    double for double x

    sqrt(x) Square root of x Double

    pow(x,y) [do not use, see note] xy

    int if both x and y integer

    otherwise double

    Note: It is a bad programming practice to use pow to raise numbers to small integer powers because

    it uses the log and exponential functions, making it quite slow. Repeated multiplication is much

    more efficient.

    Examples of the use of C++ functions might be:

    y = sin(2.0);

    y = exp(x) * ( a + b * tan(x));

    Information is passed to a function by means of its arguments (the variables given to the function in

    brackets). The function operates on the argument(s) and provides an answer which is called the

    return value. The arguments and the return value of the function must be of a particular pre-

    specified variable type. Thus, e.g. the function sin(x) takes a floating point argument x ofdouble type and gives as a return value a floating point number which is the sine ofx.

    The following is a short task to make use of the sin function. It is also needed later in TASK 13,

    TASK 10. Write a program to evaluate sin(x) in the range 0 x 14 in steps ofx= 0.1.

    Use a simple for loop with an integer counter. Plot your result in a graph in Excel. This

    program should be short (not more than 10 lines in the main function).

    If you dont know why you are asked to use an integer counter in this task, see section 2.9.3.2.

    2.10.2 Writing your own functions

    In this section, you will learn to design your own functions which you can use as black boxes in a

    program.

  • 8/7/2019 First year computing

    29/50

    Version 2.7 29

    2.10.2.1Function structure

    A function consists of a header followed by the body of the code in braces. For example, recall the

    polynomial we plotted in TASK 8:

    y = x3

    11x2

    + 18x.

    We can isolate the calculation of this polynomial from the main program by writing a function to

    calculate it for any given x:double poly(double x) //function header

    { //start of function body

    double y;

    const double a=0.0, b=18.0, c=-11.0, d=1.0;

    y = ((d*x + c)*x + b)*x + a;

    return y;

    } //end of function body

    The function header contains, in the order written:

    the type of the return value of the function, in this case double because the value of the

    polynomial is a floating point number the name of the function, in this case poly. NB: poly is nota variable in the function.

    in brackets, the function parameters (arguments) specified by type and name: in this case

    there is one parameter x of type double. In general, a function may have many arguments,

    separated by commas, e.g.folly(double x, double y, int m, char ch).

    (You will need this in TASK 11.)

    The function receives the values of the arguments from the program that calls it. So, if we have a

    line in the main program:

    p = poly(0.6);

    the value 0.6 will be assigned to x when the function poly is called by this line. We can also have:

    p = poly(z);

    In this case, the current value ofz in the calling program is assigned to x in the function. Note that

    z must be a double variable because the function has only been defined for double arguments.

    How does the program calling poly know the answer of the polynomial calculation? This is done

    by the statement return y;. This returns the value ofy to the point in the program from which

    the function was called. In general, the return statement is:

    return expression;

    where the expression is any expression that has the required return type. In fact, we could simplify

    the above function to a more concise form by dispensing with y and using as the return statement:

    return ((d*x + c)*x + b)*x + a;

    A function may also have no return value if, for example, its purpose is to print out some results. In

    this case the function type is void and no value is inserted in the return statement:

    void function_name(arguments)

    {

    ...

    return;

    }

    2.10.2.2Using a user-defined function: function prototype

    Before you can use a function in a program you have to warn the program that the function exists.You do this by inserting a statement called a function prototype before the main function:

    double poly(double);

  • 8/7/2019 First year computing

    30/50

    Version 2.7 30

    The prototype contains the information needed by the compiler to check that the function is used

    correctly. Essentially the function prototype contains the same information as the function header.

    Note that, in the prototype, the names of the arguments are omitted, because you can use the

    function on different occasions with different variables as arguments, as long as the variables are of

    the specified type. Variable names in the prototype are in fact allowed but ignored by the compiler.

    They are useful as a reminder to the programmer if there are many arguments of the same type, say

    3 doubles followed by 2 ints.

    Putting all the above information together, we can write a program that uses the function poly to

    do TASK 8:

    #include

    using namespace std;

    double poly(double); //function prototype, NB semicolon

    int main()

    { //start of main function body

    int i;ofstream myfile(polyval.txt);

    double dz = 0.10, z = 0.0;

    for (i = 0; i < 100; i++)

    {

    z += dz ;

    myfile

  • 8/7/2019 First year computing

    31/50

    Version 2.7 31

    using the sin function, there will be no side effects on your own program if, by chance, you

    happened to use variables with the same names as variables inside the sin function.

    In the same way, the variables x, y, a, b, c and d are referred to as local variables to the

    function poly. If you used a parameter b in the main (or any other) function, it would not conflict

    with the b used in the function poly. Moreover, we could have even renamed z in the main

    program as x without causing any interference with the x variable inside poly. In other words, thex in poly does not correspond to any variable that happens to be called x in main.

    Therefore, for a user of your function, all he/she needs to know is that it is called poly, that it

    expects a single argument of type double and that its return value is also of type double. This is

    the reason why these are the only pieces of information specified in a function prototype (section

    2.10.2.2).

    TASK 11. Adapt the program above to give the polynomials x3

    11x2

    + 18x and x3

    8x2

    +

    9x +18 in the range 0 x 10. Use only one user-defined function which could evaluate third-

    order polynomials for any set of coefficients, for example in the form: poly2(x,a,b,c,d).

    Remember that you need to declare the type of each of the five arguments in the function

    prototype.

    2.10.3 Passing arguments to a function

    In this section, we will see that there is more than one way to pass arguments to a function.

    2.10.3.1Passing by value

    In the program above, the poly function is called in the main function with the variable z. Inside

    the poly function, the value ofz from main is assigned to the local variable x. In other words, the

    content of the memory location storing z is copiedto the memory location storing x. We say that

    the data stored in z is passed by value to the function.

    Therefore, manipulating x within the function involves a different chunk of the computers memory

    than the chunk of memory storing z. So, changing the value ofx inside the function does not alter

    the value ofz in main. Let us check this in the following exercise.

    TASK 12. Start a new project and copy the poly function from section 2.10.2.2. Now,

    insert a line that changes the value ofx after it has been used to calculate the polynomial:

    double poly(double x) //function header

    { //start of function body

    double y;

    double a=0.0, b=18.0, c=-11.0, d=1.0;

    y = ((d*x + c)*x + b)*x + a;

    x = 0.0;

    return y;

    } //end of function body

    Now, write a short mainprogram that calls the poly function and check that the value of the

    argument passed to poly does not change after poly has been called:

    int main()

    {

    double z = 1.5;

    cout

  • 8/7/2019 First year computing

    32/50

    Version 2.7 32

    }

    2.10.3.2Passing by reference

    TASK 12 contd: Now change the function argument list to the following:

    double poly(double& x) //new function header with &

    { }

    Remember to make change the corresponding prototype for poly at the top of the cpp file by

    adding an ampersand & after double. Run the program again. What has changed?

    You should find that the value ofz has been set to zero in the main program after poly has been

    called. What has happened is that, in this new format, we are no longer copying the content ofz in

    main to x in poly. Instead, the main function has given the memory address ofz to the poly

    function so that x now refers to the same chunk of memory as z. This is called passing by

    reference. In this case, manipulating x in poly is the same as manipulating z in main.

    This is a very useful syntax for structured programming when you have several quantities that you

    want a function to calculate. Suppose you want to calculate the new position and velocity of a

    particle after a period of time. You decide to structure the program so that this calculation is

    performed by a trajectory function. You give the mass, time interval, the initial position and

    initial velocity to the function. Then, you can design the function so that, when it is finished, it has

    changedthe position and velocity to new values. The function header/prototype would look like:

    void trajectory(double& position, double& velocity, double time,

    double mass)

    The variables position and velocity are given their initial values before entering the

    function. When the function is done, the variables contain the new position and velocity after a

    period oftime has elapsed. Note that I have now used a void function that returns nothing: the

    changes have been made through the argument list.

    There are more sophisticated ways of passing arguments using memory addresses directly. Thisinvolves the use ofpointers. Refer to the handout Introduction to C++ for details.

    2.10.3.3Constant arguments

    Recall that we can declare variables as constant using the const qualifier. We can also use const

    to indicate that a function is not going to change the value of a variable. In the polynomial example

    above, we know that the variable x is not altered inside the poly function. So, we can declare the

    function with one of the following prototypes:

    double poly(const double x) // if we pass by value

    double poly(const double& x) // if we pass by reference

    Why do we want to do this? This is in fact good programming practice. If the compiler can be

    certain that the poly function does not alter x, it can in fact optimise better the speed of theprograms that calls this function.

    CCHHEECCKKPPOOIINNTT

    You should be able to

    use functions from standard libraries

    understand the concept of structured programming by writing and using your own funct ions

    (and know what is meant by the header and the prototype)

    understand how local variables defined in different functions are independent of each other understand the difference between passing arguments to a function by value and by

    reference

  • 8/7/2019 First year computing

    33/50

    Version 2.7 33

    2.11 Debugging and Good Practice

    You should now be in a position to write a C++ program of your own but this section offers a few

    helpful tips before you start.

    If your program does not work and you cannot find the cause of the problem, try writing out

    important variables at strategic points in the program. When you run the program, this will tell you

    how far it got before failing and give you values which you can check out for errors.

    If this doesnt help, try using the Debugger. On the Build menu clickStart Debug; you then have

    a choice of approaches: particularly useful is Step Into which takes you line by line down the code

    showing the current values of all the variables in the panel at the bottom of the screen. To avoid

    stepping into library routines (e.g. ofstream) use Step Over. To finish the debug clickStop

    Debugging on the Debug menu (which will temporarily have taken the place of the Build menu).

    Debugging can also be made easier by having a well-structured program. C++ has no restrictions

    on the layout of your program but there are aspects ofgood practice which you are strongly

    recommended to adopt:

    Only a single statement per line. Exceptions can be made for very short related statements.

    Compound statements should be written indented by a few characters and the braces should

    be written so that it is obvious which closing brace, }, corresponds to each opening brace, {.

    This makes it much easier to follow the logic of the program.

    Include lots of comments.

    Use a modular approach: use functions wherever a new program structure is used

    repeatedly, or can be generalised such that it can be used by many parts of the task.

    Define constant values at the start of a program so that you are not repeatedly typing in the

    same fixed value (e.g. double speedoflight = 3.0e8 ; ) This also has the advantage

    that if you need to change the constant you only need to amend one statement.

  • 8/7/2019 First year computing

    34/50

    Version 2.7 34

    2.12 Series Expansion for sin(x)

    This exercise requires more planning on your part. It applies what you have learnt so far about

    functions and loops to the evaluation of a power series. Apart from helping you understand the use

    of functions, it also directs you to think about how series evaluations can be performed efficiently.

    The Maclaurin expansion for sin x (x in radians) is:

    We know that this infinite series gives us the sine function for any finite value ofx. However, if we

    stop the series after Mterms, then it is only an approximation to the sine function. This exercise

    investigates how good this approximation is depending on how many terms you want to keep.

    (Read until the end of this section on the next page before you start the following task.)

    TASK 13. Find out how good the Maclaurin series approximates to the sine function for x

    between 0 and 14 if we evaluate it to M= 5, 10 and 15 terms. To do so, you should write a

    function which, for a given value ofx, will write out the sum of the first Mterms of the

    Maclaurin series. You should then call this function from a mainprogram so that you can use

    the function you have written for a whole series ofx values. (You can adapt the main

    program from TASK 10.) Find out how good these three truncated series approximate to the

    sine function for x between 0 and 14 by plotting your results on a graph.

    In the spirit of structured programming, let us separate out the evaluation of the Maclaurin series

    into a self-contained function. The prototype for this maclaurin function would be of the form:

    double maclaurin(double x, int nterms)

    where x is the argument for the series, nterms is the number of terms M, and the function returns

    a double value which is the value of this series truncated to only the first Mterms. (I am usingnterms instead ofM as a name because its meaning is easier to remember.)

    This function can be then be called from a main program to evaluate the series over a range ofx and

    for different values ofnterms. The main function should be something like:

    int main()

    {

    ofstream outfile(maclaurin.txt);

    double x=0.0, dx=0.1 ;

    for ( int i=0 ; i

  • 8/7/2019 First year computing

    35/50

    Version 2.7 35

    the value x and returns the value of the series truncated after nterms terms. Conversely, apart

    from the values ofx and nterms, this maclaurin function knows nothing else about the

    variables in main.

    Let us now decide on the algorithm to calculate this series. Then, you can translate the algorithm to

    clearly defined C++ instructions for the computer.

    The Maclaurin series is a sum over terms of higherand higher powers in x. We need a loop which adds

    a new term to a sum in each cycle of the loop,

    continuing until we have done enough terms. This

    is illustrated in the flowchart on the right, based on

    a for loop construction.

    We have a variable term which changes in each

    cycle of the loop and represents successive terms in

    the Maclaurin series: , , , etc. Wehave another variable sum which is the sum of all

    the terms so far. When we finally exit the loop, thisaccumulated sum will give us the Maclaurin

    approximation for sine for the desired number of

    terms.

    Here, I have initialised the variables term and

    sum so that the first term (which is just x) is

    already done and accumulated in sum.

    We also have to check that the loop terminates

    correctly. Check whether the continuation

    condition (n

  • 8/7/2019 First year computing

    36/50

    Version 2.7 36

    2.13 Arrays and Vectors

    The variables we have used so far, int and double, store single numbers. We will introduce two

    C++ constructions, arrays and vectors, which store whole sets of numbers. We will start with the

    basic array because it is a common element in many traditional programming languages. However,

    the vector class is a modern substitute that is easier to use.

    2.13.1 Using basic arrays

    Your program may produce a large list of numbers for subsequent use in an extended version of the

    program. To store them for later use within the program, you can use the basic array construction in

    C++. For example, the following calculates the factorials and stores them in an array called arr.

    int main()

    { // Calculate factorials and stores them in an array

    double arr[20]; // NB: square brackets

    double fact = 1.0;

    arr[0] = 1.0; // special case of 0!=1

    for (int n = 1; n < 20; n++ ){

    fact *= n;

    arr[n] = fact;

    }

    ...

    return 0;

    }

    The declaration double arr[20]; tells the computer to allocate to the array 20 spaces for

    floating point numbers in its memory. When the 20 array elements are actually used, the entries of

    the array are referred to as arr[0], arr[1], arr[2], arr[3], ..., arr[19].

    IMPORTANT: you must understand the C++ convention that array entries are numberedfrom zero. Note that the element arr[20] does notexist for an array declared to have 20

    elements. For this reason, in the for loop above, the loop index n has been defined to run from 0 to

    19 (i.e.n < 20 rather than n

  • 8/7/2019 First year computing

    37/50

    Version 2.7 37

    This restriction means that the array size nmax cannot be obtained as user input, e.g.cin >>

    nmax does not work because nmax is a const and cannot be altered. So, if you want to change

    the array size, you have to change it in the source code and re-compile it. One way to avoid this

    restriction is to use the vector class instead of this basic array. This is explained in the next section.

    Another way is to use dynamic memory allocation and pointers. This allows great flexibility in the

    handling of arrays but is a little tricky for beginners. (See Introduction to C++ for more details.)

    2.13.2 The vector class

    As mentioned above, the built-in C++ array construction has limitations. It is an element inherited

    from plain C language. The C++ language contains more powerful tools in the Standard Template

    Library (STL). One of these is the vector class which can be used as a replacement for the built-in

    array. You will learn more about classes in the second-year computing course when you are

    introduced to object-oriented programming.

    To use the vector class, we need to include the vector header file at the top of the source code:

    #include

    To declare a vector called vec with nvec components of floating point type, we need:vector vec(nvec); // NB: round brackets

    To use the elements of the vector, the syntax is the same as that for arrays. The elements are

    numbered from 0 to nvec-1: vec[0], vec[1], , vec[nvec-1].

    One advantage of using the vector class is that the size of the vector nvec can be any int variable,

    and does not have to be a const int. So, you do not have to re-compile your program if you

    decide to change the size of your vector. Moreover, you can calculate the size based on user inputs.

    Another advantage is that the vector knows its own size. The number of components of the vector

    vec is given by vec.size(). In fact, size() is a function with no arguments (hence the empty

    brackets) that has been pre-defined for objects which have been declared as vectors. (The basic

    array does not know its own size: you need a separate int variable that remembers the size.)

    TASK 14. We can use a vector to store the Cartesian components of a three-dimensional

    vector (x, y, z). Write a short program which asks the user to input the 3 components of the

    vector and then calculates its magnitude .2.13.3 Passing arrays and vectors to functions

    We have already discussed how to pass simple variables (e.g., int, double) to a function by

    value or by reference (section 2.10.3). You can do the same things with vectors. The syntax for

    arrays is slightly different as you will see below.

    With a vector, you can pass on the vector by value or by reference in the syntax introduced insection 2.10.3. For instance, the following is a function that computes the dot product (or scalar

    product) of two vectors a and b (of the same size):

    double dotprod(vector a, vector b)

    {

    double dot = 0.0;

    for ( int i=0; i

  • 8/7/2019 First year computing

    38/50

    Version 2.7 38

    vector v1(nvec),v2(nvec);

    x = dotprod(v1,v2);

    In this form, the vector is passed to the function dotprod by value. All the elements of the

    vectors in the program calling this function are copied to a and b which are local variables in the

    function dotprod. (Check that you understand why the code computes the dot product.)We can alternatively pass the arguments by reference. As in section 2.10.3.2, we just add an

    ampersand & after the variable type in the function header:

    double dotprod(vector& a, vector& b)

    {

    double dot = 0.0;

    for ( int i=0; i

  • 8/7/2019 First year computing

    39/50

    Version 2.7 39

    2.14 Finite differencing an example using the simple pendulum

    Many problems in physics are modelled by differential equations. Classical motion of a point

    particle is governed by Newtons second law, which is a second-order differential equation for the

    position. Atomic physics is described by Schrodingers equation which is a three-dimensional

    partial differential equation in time and space coordinates. We can use the computer to assist us in

    solving these problems. Many techniques have been developed in computational physics to solvedifferential equations.

    For an equation that does not have an analytical solution, the computer represents differentiation by

    taking a difference over a small finite interval. There are numerous approaches to this. We will

    discuss the simplest of them. For example, we can represent the differential by

    i.e. the difference in the values of the function y between two positions spaced by a small distance

    x divided by that distance. This is just another way of expressing the idea of the differential being

    the slope of the function at x. We will see how this technique can be applied to calculating the

    motion of a simple pendulum.Imagine a mass m swinging on the end of a rigid rod of

    length r. Let the rod make an angle (t) with the verticalat time t. Gravity acts vertically downwards on the

    mass and the component of the gravitational force in the

    direction of motion of the mass is mg sin. FromNewton's Second Law, its acceleration in this direction

    is g sin . Thus its motion is described by twoequations:

    where is the angular velocity around the fixed end of the rod. Check that you know where these

    equations come from.

    If the oscillation amplitude is small, the period of oscillation should be:

    If you do not know this already, you will learn this in the first year Mechanics course under the

    name ofSimple Harmonic Motion. The analytical derivation of this expression depends upon the

    assumption that sin for small . Notice that the expression for the period apparently does notdepend on the amplitude of the oscillations. This is in fact only approximately true: for larger

    amplitudes, the period will change with the amplitude. With the help of the computer, we can

    simulate the motion of the pendulum and deduce how the period depends on the amplitude. Can you

    guess whether the actual period will be larger or smaller than the simple harmonic approximation?

    The equations of motion above tell us that, if we knowand at time t, we know their rate of

    change in time. Hence, the values ofand at a short time tlater can be predicted by using afinite-difference version of the differential equations. There are different finite-difference schemes

    with different degrees of accuracy. We will use one of the simplest methods:

    If we apply these equations repeatedly, we can calculate the motion of the pendulum at successive

    times.

    r

    m

  • 8/7/2019 First year computing

    40/50

    Version 2.7 40

    Suppose we start the bob at rest from an initial angle of = 0.1 radians. Since this will be thehighest point of the oscillations, this is the amplitude of the subsequent oscillations. We can

    calculate numerically the subsequent angular displacements by a loop of the form:

    double theta = 0.1, omega = 0.0;

    do // use an integer counter if you need accuracy

    {

    t += dt;

    theta += omega * dt;

    omega -= p * sin(theta); // where p = dt * g/r

    } while (t < tmax)