Topics this week Computer Programming Computer Programming Programming Life-Cycle Phases Programming...

Preview:

Citation preview

TopicsTopics this week this week

Computer ProgrammingComputer Programming Programming Life-Cycle PhasesProgramming Life-Cycle Phases Creating an AlgorithmCreating an Algorithm Machine Language vs. High Level Machine Language vs. High Level

LanguagesLanguages Compilation and Execution ProcessesCompilation and Execution Processes Problem-Solving TechniquesProblem-Solving Techniques

What is Computer Programming?What is Computer Programming?

It is the process of planning It is the process of planning and and implementing implementing a sequence of steps a sequence of steps (called instructions) for a computer to (called instructions) for a computer to follow in order to solve a problem.follow in order to solve a problem.

STEP 1

STEP 2

STEP 3 . . .

99.99% of Programs99.99% of Programs

Getting some information into the Getting some information into the programprogram

Doing something with the Doing something with the informationinformation

Displaying resultsDisplaying results

Nearly all of programs you write will involve:Nearly all of programs you write will involve:

Previously we spoke about: Previously we spoke about: Programming Life CycleProgramming Life Cycle

1 Problem-Solving PhaseProblem-Solving Phase• Analysis and SpecificationAnalysis and Specification• General Solution (Algorithm)General Solution (Algorithm)• Test/Verify (Desk check)Test/Verify (Desk check)

2 Implementation PhaseImplementation Phase• Concrete Solution (Program)Concrete Solution (Program)• Test/VerifyTest/Verify

3 Maintenance PhaseMaintenance Phase• UseUse• Maintain (update, maintain)Maintain (update, maintain)

A Tempting Shortcut?A Tempting Shortcut?

GOAL

THINKINGProblem solving

CODEImplementation

REVISEREVISE

REVISEDEBUG

DEBUG

DEBUG

TEST

CODEShortcut?

No thinking

Problem-Solving PhaseProblem-Solving Phase

ANALYZEANALYZE the problem and the problem and SPECIFYSPECIFY whatwhat the solution must do. the solution must do.

Develop Develop and write down on a piece and write down on a piece of paperof paper GENERAL SOLUTIONGENERAL SOLUTION (ALGORITHM) to solve the problem(ALGORITHM) to solve the problem

VERIFYVERIFY that your solution really that your solution really solves the problemsolves the problem. .

How will you know whether your How will you know whether your solution is correct?solution is correct?

ExampleExample

A programmer needs an algorithm to A programmer needs an algorithm to determine an employee’s weekly wages. determine an employee’s weekly wages.

First think:First think: How would the calculations be done by How would the calculations be done by

hand?hand? Is there anything that is fixed or constant?Is there anything that is fixed or constant? Is there anything that changes/varies Is there anything that changes/varies

every time I do the sum? every time I do the sum?

Analysis: One Employee’s Wages Analysis: One Employee’s Wages

Assumptions/Known:Assumptions/Known:

40 hours is a normal week40 hours is a normal week

Normal Hourly Rate of pay Normal Hourly Rate of pay £4.00/hour£4.00/hour

Overtime rate of pay £6.00/hourOvertime rate of pay £6.00/hour

Variables/Things that changeVariables/Things that change

Actual hours worked in one week: Actual hours worked in one week:

If HoursWorked are more than 40.0 thenIf HoursWorked are more than 40.0 then

wages = (40.0 * NormalRate) + (HoursWorked - 40.0) * wages = (40.0 * NormalRate) + (HoursWorked - 40.0) * OvertimeRateOvertimeRate

otherwise,otherwise,

wages = HoursWorked * NormalRate wages = HoursWorked * NormalRate

Processes/Algorithm: Calculate Weekly WagesProcesses/Algorithm: Calculate Weekly Wages

Desk Check Calculations (use for testing algorithm)Desk Check Calculations (use for testing algorithm)Use 2 examples of 30 hours and 50 hoursUse 2 examples of 30 hours and 50 hours

Why? Why?

Case 1: 30 hours worked30 x £ 4.00 = £120.00

___________

£ 120.00Case 2: 50 hours worked40 x £ 4.00 = £160.0010 x £6.00 = £60.00___________

£ 220.00

What are the employee’s wages in each case?

IPO ChartIPO ChartInputs-Process-OutputsInputs-Process-Outputs

InputsInformation the

computer needs

ProcessesThings computer needs to do with Inputs

OutputsResults computer must display

NormalHoursHoursWorkedNormalRateOvertimeRate

If HoursWorked are more than 40.0 then wages = (40.0 * NormalRate) + (HoursWorked - 40.0) * OvertimeRateotherwise, wages = HoursWorked * NormalRate

Wages

General Algorithm to Determine an General Algorithm to Determine an Employee’s Weekly WagesEmployee’s Weekly Wages

1.1. InitialiseInitialise employee’s NormalRate and employee’s NormalRate and OvertimeRate.OvertimeRate.

2.2. Get the HoursWorked this week from Get the HoursWorked this week from useruser

3.3. Calculate the wages Calculate the wages

4.4. Display the answerDisplay the answer

It is written in English!We call this pseudocode:

ImplementationImplementation We cannot simply write this pseudocode We cannot simply write this pseudocode

algorithm as a program.algorithm as a program. It is merely a program DESIGNIt is merely a program DESIGN YOU have to convert the DESIGN to your YOU have to convert the DESIGN to your

chosen chosen programming languageprogramming language (ours at (ours at present is C++)present is C++)

A good design is one that can be easily A good design is one that can be easily converted into code not just C++.converted into code not just C++.

A poor design is difficult to convertA poor design is difficult to convert A design should be “language” independentA design should be “language” independent

• i.e. We can write the code in Java, VB etci.e. We can write the code in Java, VB etc

So what is a Programming Language?So what is a Programming Language?

It is a language with strict It is a language with strict grammatical rules, symbols, and grammatical rules, symbols, and special words used to construct a special words used to construct a computer program.computer program.• Syntax = grammarSyntax = grammar• Semantics = meaning Semantics = meaning

Why a programming language? What is Why a programming language? What is wrong with English?wrong with English?

Computers do not understand Computers do not understand English!English!

English is a English is a natural languagenatural language and and requires each of us to understand requires each of us to understand meaning by context.meaning by context.

For Example For Example • Lung Cancer in Women explodes Lung Cancer in Women explodes • Red Tape Holds Up New Bridges Red Tape Holds Up New Bridges • Hospitals are sued by 7 Foot Doctors Hospitals are sued by 7 Foot Doctors • Star's Broken Leg Hits Box Office Star's Broken Leg Hits Box Office • Villagers Grill Gas Men Villagers Grill Gas Men

Computers are really stupid!Computers are really stupid! Computers do not understand anything!Computers do not understand anything!

• well not quite they understand what a well not quite they understand what a 1 and a 0 is.1 and a 0 is.

Computers follow instructionsComputers follow instructions• Instructions have to be written in 1s Instructions have to be written in 1s

and 0sand 0s• Such instructions are called machine Such instructions are called machine

code.code.• We do not write in machine codeWe do not write in machine code

Machine languageMachine language Machine languagesMachine languages

11000000 000000000001 00000000001011000000 000000000001 000000000010

Add contents of memory location 1 to Add contents of memory location 1 to contents of memory location 2contents of memory location 2

Not easy to write programs in!Not easy to write programs in!AssemblyAssembly ADD 1ADD 1 22

Needs an assembler to translate to machine Needs an assembler to translate to machine language (an assembler is software that language (an assembler is software that converts the program into machine code) converts the program into machine code)

Opcode

Levels of Levels of Programming LanguagesProgramming LanguagesLevels of Computer Languages:Levels of Computer Languages: Low (a long way from English)Low (a long way from English)

• machine language, assembly languagemachine language, assembly language• not portablenot portable

High (Closer to English)High (Closer to English)• COBOL, Pascal, FORTRAN, Logo, BasicCOBOL, Pascal, FORTRAN, Logo, Basic, ,

Visual Basic, Prolog, Visual Basic, Prolog, C, C++ and JavaC, C++ and Java

High level languagesHigh level languages

Deliberately terse (concise). Deliberately terse (concise). Must be unambiguous.Must be unambiguous. Must be flexible enough to easily Must be flexible enough to easily

implement algorithms.implement algorithms. Fairly portableFairly portable

Creating Creating machine (machine (executableexecutable) code from) code from C+ C+++ source code : source code : Compilation and linkingCompilation and linking

source codesource codecompiler

object codeobject code linked to libraries

.exe file.exe file

Implementation Phase: TestImplementation Phase: Test

TESTING your program means running TESTING your program means running (executing) your program on the computer, (executing) your program on the computer, to see if it produces correct results. to see if it produces correct results. (Verification)(Verification)

if it does not, then you must find out what is if it does not, then you must find out what is wrong with your program or algorithm and wrong with your program or algorithm and fix it--this is called debuggingfix it--this is called debugging ..

Compilers do not fix logic errors. Compilers do not fix logic errors.

Maintenance PhaseMaintenance Phase USE and MODIFY the program to meet USE and MODIFY the program to meet

changing requirements or correct errors changing requirements or correct errors that show up when using itthat show up when using it

maintenance begins when your program maintenance begins when your program is put into use and accounts for the is put into use and accounts for the majority of effort on most programsmajority of effort on most programs

You will not be concerned very much You will not be concerned very much with this phase while you learn. with this phase while you learn.

But when you are in industry this is a But when you are in industry this is a massive part of your job!massive part of your job!

The Basic Control StructuresThe Basic Control Structuresin programmingin programming

a a sequencesequence is a series of is a series of statements that execute one after statements that execute one after anotheranother

selectionselection (branch) is used to (branch) is used to execute different statements execute different statements depending on certain conditions depending on certain conditions (Boolean conditions)(Boolean conditions)

IterationIteration (repetition) is used to (repetition) is used to repeat statements while certain repeat statements while certain conditions are met. Often requires conditions are met. Often requires the use of loops.the use of loops.

Organising StructuresOrganising Structures(functions in C++)(functions in C++)

Stepwise refinement Stepwise refinement • Breaking big problems into smaller bitsBreaking big problems into smaller bits

““Natural” problem solving strategyNatural” problem solving strategy Most common approach in programmingMost common approach in programming Different people can work on different “bits” Different people can work on different “bits” Nearly all high level languages support thisNearly all high level languages support this

Stepwise refinementStepwise refinement

the breaking down of problems into a the breaking down of problems into a series of single-function tasks and series of single-function tasks and single-function subtasks. single-function subtasks.

We previously discussed functions. We previously discussed functions.

SEQUENCESSEQUENCES

Statement Statement Statement . . .

1. Get the user to input a number

2. Calculate the result e.g. number * 10

3. Display the result

Note the logical order!

SELECTION (branch)SELECTION (branch)

IF Condition THEN Statement1 ELSE Statement2

Statement1 Statement

Statement2

Condition . . .

True

False

1. Get the user to input a number

2. IF the number is greater than 0 then

1. Calculate the result = number * 10

3. ELSE

1. Calculate the result = number * (-10)

4. Display the result

LOOP (repetition)LOOP (repetition)

Statement1

Condition. . .

False

True

WHILE Condition DO Statement1

So Statement1 is executed as long as the condition is true.

Loop (repetition) ExampleLoop (repetition) Example1. Repeat While there are more

numbers to process

1. Get the user to input a number

2. IF the number is greater than 0 then

1. Calculate the result = number * 10

3. ELSE (otherwise)

1. Calculate the result = number (- 10)

4. Display the result

2. End repeat

functionfunction

FUNCTION1 . . .

FUNCTION1 a meaningful collection of SEQUENCE, SELECTION, LOOP STATEMENTS &/OR FUNCTIONS

Subprogram CalculateResultSubprogram CalculateResult

Precondition: Needs a number to work with

Postcondition: returns a result depending on the number

1. if the number is greater than 0 then

1. Calculate the result = number * 10

2. else

1. Calculate the result = number * (-10)

3. return the result

Use of subprogramUse of subprogram

1. Get the user to input a number

2. Repeat While there are more numbers to process

1. result =CalculateResult(number)

2. Display the result

3. Get the user to enter next number

3. End repeat

1. Get the user to input a number

2. Repeat While there are more numbers to process

1. IF the number is greater than 0 then

1. Calculate the result = number * 10

2. ELSE (otherwise)

1. Calculate the result = number * -10

3. Display the result

4. Get the user to enter next number

3. End repeat

#include <iostream>

using namespace std;

double CalculateResult(double number);

int main() {float n;float answer;

cout << "Please enter a number: "; //1) get the user to enter a numbercin >> n;while (n != 0) { //2) loop use the value 0 to stop loop

answer = CalculateResult(n); //2.1) call function

cout << "The answer is " << answer << endl; //2.2) display answer

cout << "Please enter a number: "; //2.3) ask for next numbercin >> n;

} // 3) end loop

return 0;}

double CalculateResult(double number) { // subprogram/function definitionfloat result;

if (number > 0)result = number * 10.0;

elseresult = number * -10.0;

return result;

}//see calculate1.cpp

Problem Solving TechniquesProblem Solving Techniques

OVERCOME MENTAL BLOCK -- by rewriting the OVERCOME MENTAL BLOCK -- by rewriting the problem in your own wordsproblem in your own words

DRAW A FIGURE/DIAGRAMDRAW A FIGURE/DIAGRAM ASK QUESTIONS – ASK QUESTIONS –

• What is the data, What sort of data is it? What would What is the data, What sort of data is it? What would be good identifiers (names) for the data.be good identifiers (names) for the data.

• How much data is there, where does it come from? Is How much data is there, where does it come from? Is it given? Do you get it from the user? Do you calculate it given? Do you get it from the user? Do you calculate it? Do you get it from a file?it? Do you get it from a file?

• Can you identify what is input and what is to be Can you identify what is input and what is to be output?output?

• What are What are the processesthe processes? ? Do you need to repeat stepsDo you need to repeat steps

• What are the conditions?What are the conditions? Do you need to do different things in different situations?Do you need to do different things in different situations?

• What are the conditionsWhat are the conditions

Problem Solving TechniquesProblem Solving Techniques

LOOK FOR FAMILIAR THINGS -- certain LOOK FOR FAMILIAR THINGS -- certain situations arisesituations arise again and again. E.g. creating again and again. E.g. creating tables, adding up lists of numbers, reading tables, adding up lists of numbers, reading from files.from files.

Do you know any equations?Do you know any equations?• Find the area of a room, find the stopping distance of Find the area of a room, find the stopping distance of

a car.a car. SOLVE BY ANALOGY -- it may give you a place SOLVE BY ANALOGY -- it may give you a place

to start.to start. In a broader sense than looking for In a broader sense than looking for familiar things. familiar things. • E.g. Finding the student with the highest and lowest E.g. Finding the student with the highest and lowest

score is analogous to finding the highest and lowest score is analogous to finding the highest and lowest temperature.temperature.

Problem SolvingProblem Solving

USE MEANS-ENDS ANALYSIS USE MEANS-ENDS ANALYSIS • Where you often know start conditions and know Where you often know start conditions and know

what the end goal is.what the end goal is.• Identify intermediate goals then think how you Identify intermediate goals then think how you

get from the start to any intermediary goalsget from the start to any intermediary goals• E.g. How do you find your way to the canteen/bar E.g. How do you find your way to the canteen/bar

from here?from here? Setup intermediary goals: get to reception, past Setup intermediary goals: get to reception, past

bookshop, security and lifts then canteen.bookshop, security and lifts then canteen. Get to stairs, get to reception, go down the stairsGet to stairs, get to reception, go down the stairs

More Problem Solving TechniquesMore Problem Solving Techniques Stepwise refinement -- break up large Stepwise refinement -- break up large

problems into manageable units.problems into manageable units. SIMPLIFYSIMPLIFY

• Can you solve a simpler but related Can you solve a simpler but related problem?problem?

• E.g. Bobs DIY:- Do not attempt to solve the E.g. Bobs DIY:- Do not attempt to solve the general problem but solve the simpler cases general problem but solve the simpler cases

BUILDING-BLOCK APPPROACH -- can you BUILDING-BLOCK APPPROACH -- can you solve small pieces of the problem? And solve small pieces of the problem? And then join them upthen join them up• E.g. a large application like a word processor has E.g. a large application like a word processor has

many functions. (Text manipulation, Tables, many functions. (Text manipulation, Tables, drawing)drawing)

• Do not try to solve all at once.Do not try to solve all at once.

Result of Problem solvingResult of Problem solving

1.1. One or more pages of rough work that sketches One or more pages of rough work that sketches your ideas of problem requirements, of user your ideas of problem requirements, of user inputs, of outputs, of constants, of conditions inputs, of outputs, of constants, of conditions for repetition and selection, of assumptions.for repetition and selection, of assumptions.

2.2. A formal written design that includes:A formal written design that includes:1.1. inputs, Processes, Outputs, assumptions. inputs, Processes, Outputs, assumptions.

Create an IPO chartCreate an IPO chart2.2. Write steps to process input unambiguously Write steps to process input unambiguously

using a semi formal notation (PDL, Flowchart using a semi formal notation (PDL, Flowchart or structure diagram?) Can you translate or structure diagram?) Can you translate each step of the plan into C++ easily?each step of the plan into C++ easily?

3.3. Verification/testing procedures documented Verification/testing procedures documented (A test table).(A test table).

What we are aiming for is a What we are aiming for is a Structured Structured Systematic Systematic Approach to Approach to ProgrammingProgramming

Advantages:Advantages: Not one giant step, but breaks in to smaller Not one giant step, but breaks in to smaller

and smaller chunks.and smaller chunks. Programmer concentrates on details Programmer concentrates on details Easy to do in teamsEasy to do in teams Easy to keep track of developmentEasy to keep track of development Creates more reliable and robust programs.Creates more reliable and robust programs.

• These terms are a bit ambiguous, different These terms are a bit ambiguous, different programmers give different definitions hereprogrammers give different definitions here

Makes more possible reuse and extensibility. Makes more possible reuse and extensibility.

Structured ProgrammingStructured Programming

Errors isolatedErrors isolated Design written in code Design written in code Improves reliabilityImproves reliability Minimizes risk of FailureMinimizes risk of Failure Faster developmentFaster development Full documentationFull documentation

• MaintainabilityMaintainability

So find a solution, write it down in So find a solution, write it down in English.English.

Write it down more formally in Pseudo-Write it down more formally in Pseudo-code (PDL), or as a structure diagram or code (PDL), or as a structure diagram or a flow chart.a flow chart.

Start your programming environment and Start your programming environment and convert your pseudo-code to C++convert your pseudo-code to C++

Tell the computer to convert the C++ to Tell the computer to convert the C++ to machine language (compile)machine language (compile)

Tell the computer to load the machine Tell the computer to load the machine language into memory and execute language into memory and execute (Run).(Run).

SummarySummary

NoteNote Learning C++ syntax by heart is Learning C++ syntax by heart is

useless!useless! Experience is essentialExperience is essential

You will need to build up a virtual You will need to build up a virtual scrapbook of techniques to be scrapbook of techniques to be successfusuccessfull

““Get some information in,Get some information in,

Do something with it,Do something with it,

Display the result.”Display the result.”

““Get some information in,Get some information in,

Do something with it,Do something with it,

Display the result.”Display the result.”

TopicsTopics

Structure of a simple C++ ProgramStructure of a simple C++ Program TYPES of informationTYPES of information

• Simple and ComplexSimple and Complex Variables, Constants and LiteralsVariables, Constants and Literals Identifiers: to Name memoryIdentifiers: to Name memory DeclarationsDeclarations Getting information into your Getting information into your

programprogram Operator basicsOperator basics

Shortest C++ ProgramShortest C++ Program..A Skeleton programA Skeleton program

int main ( ) {

return 0;

}

//already run and discussed

type of returned value name of function

What happens?What happens? The operating system (Windows )The operating system (Windows ) “ “Loads” the programLoads” the program Think of it as WINDOWS calling the “main” Think of it as WINDOWS calling the “main”

function.function. Instructions “in main” are carried out one at a Instructions “in main” are carried out one at a

time.time. Notice the “int” in front of “main” this line is like a Notice the “int” in front of “main” this line is like a

contract to the operating system contract to the operating system • ““I will send you a piece of information in the form of an I will send you a piece of information in the form of an

integer.”integer.”• Hence the NEED for a return instruction. return 0 sends a Hence the NEED for a return instruction. return 0 sends a

zero to windows XPzero to windows XP

Discussion of structureDiscussion of structure Your program must have a function called Your program must have a function called

“main”“main” Note that Main, MAIN, mAiN will cause an Note that Main, MAIN, mAiN will cause an

errorerror The round brackets ‘(‘ and ‘)’after main The round brackets ‘(‘ and ‘)’after main

tells the computer that main is a tells the computer that main is a functionfunction rather than a variablerather than a variable

The curly brackets (parentheses) ‘{‘ and The curly brackets (parentheses) ‘{‘ and ‘}’ mark the beginning and end of ‘}’ mark the beginning and end of instructions that form the instructions that form the body body of main.of main.• i.e. They are i.e. They are blocksblocks

The semi-colon ‘;’ after return 0 is an The semi-colon ‘;’ after return 0 is an instruction terminator or separator.instruction terminator or separator.

#include <iostream>

using namespace std;

int main ( ) { cout << “Hello World” << endl; return 0;

}

//already run

The “Hello World” ProgramThe “Hello World” Programuses complex information i.e. the display (cout) uses complex information i.e. the display (cout)

needs more effortneeds more effort

Instructions to tell computer thatI want to use standard complexOBJECTS for input and output

Discussion of Hello World ProgramDiscussion of Hello World Program

There are now two instructions in mainThere are now two instructions in main• we added a display information instruction using a we added a display information instruction using a

complex OBJECT coutcomplex OBJECT cout• cout represents the display screen. That is why it is cout represents the display screen. That is why it is

complex. It hides all the complicated business of complex. It hides all the complicated business of displaying things from you. All you need to know is displaying things from you. All you need to know is how to send information to cout.how to send information to cout.

• cout receives information using the “<<“ send to cout receives information using the “<<“ send to operator.operator.

• So we literally send the string “Hello World” to the So we literally send the string “Hello World” to the display!display!

• endl is also sent to the display, this is interpreted endl is also sent to the display, this is interpreted by cout as a new-line command.by cout as a new-line command.

Discussion of Hello WorldDiscussion of Hello World So cout OBJECT represents our screen.So cout OBJECT represents our screen. Screens are hardware. Screens are hardware. Sending information to screens varies Sending information to screens varies

greatly from machine to machine.greatly from machine to machine. So cout became “standard”. So cout became “standard”. Customised cout’s were created for all the Customised cout’s were created for all the

major types of computer in the world. major types of computer in the world. So that you can write one piece of code So that you can write one piece of code

that should compile on all the main types that should compile on all the main types of computer in the world.of computer in the world.

Discussion of Hello WorldDiscussion of Hello World Because cout is NOT “BUILT IN” we need to tell Because cout is NOT “BUILT IN” we need to tell

the computer that we want to make use of the the computer that we want to make use of the “standard” facilities for input and output“standard” facilities for input and output

HENCE the lines HENCE the lines

#include <iostream>#include <iostream>

using namespace std;using namespace std;

This is one of the original reasons for C++’s popularity i.e., its relative ease of porting from one type of computer to another

Some DefinitionsSome Definitions

StatementsStatements• A statement is what programmers often call an A statement is what programmers often call an

instruction.instruction.• Your code consists of many instructionsYour code consists of many instructions• Your code consist of many statementsYour code consist of many statements• Statements must end with a semi-colonStatements must end with a semi-colon

blocksblocks• Any section of code which is surrounded by Any section of code which is surrounded by

curly brackets is a curly brackets is a block { }block { }

Example Example A Block of A Block of 44 statementsstatements

{{

cout <<"A fraction: "<<5.0/8.0 <<endl;cout <<"A fraction: "<<5.0/8.0 <<endl;

cout <<"Big # : "<< cout <<"Big # : "<<

7000.0*7000.0<<endl;7000.0*7000.0<<endl;

cout <<8 + 5 <<" is the sum of 8 & 5\n";cout <<8 + 5 <<" is the sum of 8 & 5\n";

cout << “Hello world”;cout << “Hello world”;}}

Block denoted byCurly braces

TYPES of information computers useTYPES of information computers use

Simple (needs little or no effort to use)Simple (needs little or no effort to use)• To hold whole numbers (integers)To hold whole numbers (integers)• To hold numbers with fractions (float and To hold numbers with fractions (float and

double)double)• To hold individual characters (char)To hold individual characters (char)

Complex (needs a little more work to use)Complex (needs a little more work to use)• StringsStrings• RecordsRecords• cin and coutcin and cout

Simple InformationSimple Information

integer (whole numbers)integer (whole numbers)• For counting thingsFor counting things• To represent values which only have To represent values which only have

whole numberswhole numbers Pounds, Pence?Pounds, Pence? Grades, Scores (Chelsea 10 : United 0)Grades, Scores (Chelsea 10 : United 0) CategoriesCategories

int

Simple InformationSimple Information

Floating points numbersFloating points numbers• For representing numbers that may For representing numbers that may

contain fractionscontain fractions• Averages, measurements.Averages, measurements.• pi, e, phipi, e, phi

float double

Simple informationSimple information

Single charactersSingle characters Can represents your initialsCan represents your initials Can represent single key responses Can represent single key responses

to questionsto questions• ‘‘y’ for yes and ‘n’ for noy’ for yes and ‘n’ for no

Not much elseNot much else

What about StringsWhat about Strings In some languages this is a simple piece In some languages this is a simple piece

of informationof information In C++ it is not. A string is complex in In C++ it is not. A string is complex in

that it is made up of lots of chars.that it is made up of lots of chars. In C++ we use the “standard” string In C++ we use the “standard” string

facilitiesfacilities

#include <string>

string

Recap!Recap! Your programs will initially entailYour programs will initially entail

• Getting information into the computerGetting information into the computer This information will either be whole numbers, This information will either be whole numbers,

floating point numbers, single characters or floating point numbers, single characters or strings.strings.

More complex information we will cover at a later More complex information we will cover at a later date.date.

• Doing something (operate on) with the Doing something (operate on) with the information (int, float, double, char or string)information (int, float, double, char or string)

• Displaying results Displaying results

Constants, Variables and Constants, Variables and LiteralsLiterals

Remember at school Remember at school

Area of a circle is Area of a circle is ππrr22

Circumference of a circle is 2Circumference of a circle is 2ππrr

ππ is a is a constantconstant representing the number representing the number 3.14159253.1415925……....

r is a r is a variablevariable representing the radius of a representing the radius of a circlecircle

2 literally represents itself, it is a 2 literally represents itself, it is a literalliteral

Fundamental building blocks of programs

Key programming conceptKey programming concept

Programs use, variables, constants Programs use, variables, constants and literals to store information and literals to store information needed to solve problemsneeded to solve problems

Remember the bank problem or Remember the bank problem or Bobs DIY (looked at) we used Bobs DIY (looked at) we used variables to hold values for wall variables to hold values for wall height and widths etc.height and widths etc.

Fundamental task isFundamental task isGetting information in to the computerGetting information in to the computer

Key ideasKey ideas• We enter values of We enter values of literalsliterals directly into directly into

code.code.• We enter values of We enter values of constantsconstants directly into directly into

code code • We have a choice on how we enter values of We have a choice on how we enter values of

variablesvariables. . We can enter values directlyWe can enter values directly Values can be set interactively with a user.Values can be set interactively with a user. Values can be set interactively with a file on disk.Values can be set interactively with a file on disk.

Using literalsUsing literals char, string, integer, float and char, string, integer, float and

double values are referred to by double values are referred to by value not by a name.value not by a name.

We type these directly into codeWe type these directly into code

#include <iostream>

using namespace std;

int main() {

cout <<“The sum of one plus three is “ << 1 + 3 << endl;return 0}

string literal

2 integer literals

Char literalsChar literals#include <iostream>

using namespace std;

int main() {

cout <<“First letter of the alphabet is “ << ‘A’ << endl;return 0;}//see char1.cpp

char literalsin SINGLE QUOTES

floating point literalsfloating point literals

floating point number can contain floating point number can contain fractions.fractions.

floating point literals are doublesfloating point literals are doubles

#include <iostream>

using namespace std;

int main() {

cout <<“one point one plus three point two is “ << 1.1 + 3.2 << endl;return 0;}//this is Float1.cpp

2 doubles

DiscussionDiscussion You can enter information directly into code using You can enter information directly into code using

literalsliterals This is obviously very limiting if a program wanted This is obviously very limiting if a program wanted

to reuse a value we need to keep typing in its to reuse a value we need to keep typing in its value every time.value every time.

Also if a program makes use of a value many Also if a program makes use of a value many times it is hard work to change all the CORRECT times it is hard work to change all the CORRECT references in a long program, especially if the references in a long program, especially if the number, say 10 refers to a count in one part of the number, say 10 refers to a count in one part of the program and the number 10 means a grade in program and the number 10 means a grade in another. another.

How can we differentiate between them?How can we differentiate between them? It can also be very confusing for another person to It can also be very confusing for another person to

understand what the numbers meanunderstand what the numbers mean..

SolutionSolutionVariables and ConstantsVariables and Constants

These are NAMED areas of memory. These are NAMED areas of memory. The programmer instructs the The programmer instructs the

computer to reserve space for the computer to reserve space for the kind of information he/she wants and kind of information he/she wants and at the same time tell the computer at the same time tell the computer the name that will be used to refer to the name that will be used to refer to that bit of information.that bit of information.

This kind of instruction is called a This kind of instruction is called a DECLARATIONDECLARATION

DECLARATIONDECLARATION

We can declareWe can declare• integersintegers• floating point numbers (doubles)floating point numbers (doubles)• charschars• stringsstrings

Constants and Variable Constants and Variable DeclarationsDeclarations

When a When a variablevariable is declared the is declared the computer marks the bit of memory computer marks the bit of memory reserved so that it allows its contents reserved so that it allows its contents to change (vary) at any time. In to change (vary) at any time. In particular at run timeparticular at run time

When a When a constantconstant is declared the is declared the computer effectively locks the computer effectively locks the memory reserved and prevents the memory reserved and prevents the contents being updated.contents being updated.

Creating Constants and Creating Constants and VariablesVariables

#include <iostream>

using namespace std;

int main() {const double Pi = 3.142;double radius;double Area, Circumference;

Area = Pi*radius*radius;Circumference = 2*Pi*radius;

return 0;}//see constants.cpp //also calculates phi

Declarations are instructions to reserve memoryspace big enough to store our information.It also creates an identifier (a name) for us to refer to this memory space

Rules for Creating ConstantsRules for Creating Constants

const type identifier = value;

<type>choose one ofintcharfloatdoublestring

<identifier>You create a name. It must obey the rules for identifiers (see rules in a minute)

<value>You provide the constant value

e.g. for Pi value was 3.141592

ExamplesExamples

const int maxnumber = 10;

const double Pi = 3.142;

const char AGrade = ‘A’;

const string MyName = “Vas”;

Rules for Creating VariablesRules for Creating Variables

type identifier;

or

Type identifier = value;

or

type identifier, identifier, …;

ExamplesExamplesint number;double Result;char response;string UserName;

int n1, n2, n3, n4;

Declare a double variable and set its initial value

double x = 5.6;

Rules for Creating IdentifiersRules for Creating Identifiers

AAn identifier must start with a letter or underscore, n identifier must start with a letter or underscore, and be followed by zero or more letters and be followed by zero or more letters

(A-Z, a-z), digits (0-9), or underscores (A-Z, a-z), digits (0-9), or underscores

VALIDVALID

age_of_dogage_of_dog taxRateY2KtaxRateY2K

PrintHeadingPrintHeading ageOfHorseageOfHorse

NOT VALID (Why?)NOT VALID (Why?)

age# 2000TaxRateage# 2000TaxRate Age-Of-Cat Age-Of-Cat

Age of CatAge of Cat

Meaningful IdentifiersMeaningful Identifiers

Age-Of-Cat Age-Of-Cat Age of CatAge of CatILLEGAL!!

Use underscore to link words or run words together and capitalise the start of each word

Age_Of_Cat Age_Of_Cat AgeOfCatAgeOfCatLEGAL!!

More About IdentifiersMore About Identifiers C++ is case sensitive soC++ is case sensitive so

NUMBER NUMBER Number number Number number

are all legitimate but DIFFERENT identifiersare all legitimate but DIFFERENT identifiers

BE CONSISTENT in your code!BE CONSISTENT in your code!

It is NOT good practice to have long identifiers It is NOT good practice to have long identifiers Why?Why?

Long Identifier NamesLong Identifier Names Some C++ compilers recognize only the Some C++ compilers recognize only the first 32 first 32

characters characters of an identifier as significantof an identifier as significant

then these identifiers are considered the same:then these identifiers are considered the same:

age_Of_This_Old_Rhinoceros_At_My_Zooage_Of_This_Old_Rhinoceros_At_My_Zooage_Of_This_Old_Rhinoceros_At_My_Safariage_Of_This_Old_Rhinoceros_At_My_Safari

Also it is very annoying to keep typing in!Also it is very annoying to keep typing in!

Meaningful IdentifiersMeaningful Identifiers

It is common sense to try to create It is common sense to try to create identifiers that are:identifiers that are:

Meaningful:- they describe the Meaningful:- they describe the information they refer toinformation they refer to• E.g. Height, Count, BloodPressure, E.g. Height, Count, BloodPressure,

CarSpeedCarSpeed Terse:- They are only as long as Terse:- They are only as long as

necessary to convey meaning.necessary to convey meaning.

Reserved WordsReserved Words

• Identifiers CANNOT be a reserved word.Identifiers CANNOT be a reserved word.• Reserved words are built in wordsReserved words are built in words that have that have

special meanings in the language.special meanings in the language.• They must be used only for their specified They must be used only for their specified

purpose. Using them for any other purpose purpose. Using them for any other purpose

will result in a error.will result in a error.

• e.g. doe.g. do ifif switchswitchwhilewhile elseelse returnreturn

*

Reserved WordsReserved Words

C++ is case sensitive. C++ is case sensitive. ALL reserved ALL reserved words are lower casewords are lower case

WHILE While while

Are all different identifiers only the last isa reserved word

OperatorsOperators

All the data types we have seen (int, float, All the data types we have seen (int, float, double, char and string) have a set of double, char and string) have a set of operators that can be applied to themoperators that can be applied to them

E.g. Numerical data uses the familiar + - / E.g. Numerical data uses the familiar + - / for add subtract and divide.for add subtract and divide.

The asterisk * is used for multiplicationThe asterisk * is used for multiplication

These work in the usual mannerThese work in the usual manner

string operatorsstring operators arithmetic is not meaningful when applied to arithmetic is not meaningful when applied to

stringsstrings You do not multiply first names!You do not multiply first names! strings operators do other thingsstrings operators do other things

E.g. The + operator applied to strings joins E.g. The + operator applied to strings joins them (concatenates) togetherthem (concatenates) together

We will see other operations we want to do We will see other operations we want to do with strings; like searching a string for a with strings; like searching a string for a substring or comparing strings.substring or comparing strings.

ExpressionsExpressions

A VALID arrangement of variables, A VALID arrangement of variables, constants, literals and operatorsconstants, literals and operators

Expressions are evaluated and Expressions are evaluated and compute a VALUE of a given typecompute a VALUE of a given type

E.g. Expression 9 + 4E.g. Expression 9 + 4

computes to 13computes to 13

A special OPERATORA special OPERATOR

The assignment operator=

Causes much confusion!IT DOES NOT WORK LIKE

EQUALS IN MATHS

variable = expressionvariable = expression

number = 4;number = 4;

result = 10 * number;result = 10 * number;

number = number + 1;number = number + 1;

expression simply consists of the literal int 4. number “takes the value of” 4

Interpretation of =

“Takes the value of”

KEY POINT: expression is evaluated BEFORE it is applied

expression evaluates to 40. result “takes the value of” 40

expression evaluates to 5 number “takes the value of” 5

Using assignments to get Using assignments to get information into the computerinformation into the computer

int myage;int myage;

string myname;string myname;

double mysalary;double mysalary;

myage = 21;myage = 21;

myname = “Vas”;myname = “Vas”;

mysalary = 1000.00;mysalary = 1000.00;

Interactive input formally covered Interactive input formally covered later later

using cin and coutusing cin and cout using data filesusing data files

Programming in C++Programming in C++

Lecture 2bLecture 2b

Types, Operators, ExpressionsTypes, Operators, Expressions

OverviewOverview

TypesTypes• Binary arithmeticBinary arithmetic

OperatorsOperators• Arithmetic, logical, assignmentArithmetic, logical, assignment

Expressions/StatementsExpressions/Statements• DeclarationsDeclarations• AssignmentsAssignments• Other one-line operationsOther one-line operations

More program examplesMore program examples

TypesTypes

““Type” in C++ refers to the kind of data or Type” in C++ refers to the kind of data or information that is to be stored in the information that is to be stored in the variablevariable

A variable is a quantity that can be A variable is a quantity that can be changed during a programchanged during a program

Functions have return types, i.e. can Functions have return types, i.e. can return expressions to the calling functionreturn expressions to the calling function

Arguments to functions each have their Arguments to functions each have their own type (these are passed to the own type (these are passed to the function)function)

Variables have typesVariables have types

Why Type?Why Type? Why do we have to specify types of variables, Why do we have to specify types of variables,

functions, arguments?functions, arguments? Has to do with computer memoryHas to do with computer memory Different kinds of data require different amounts of Different kinds of data require different amounts of

memory to storememory to store• A single character can have only one of 128 A single character can have only one of 128

values (a-z,A-Z,0-9,punctuation, some others)values (a-z,A-Z,0-9,punctuation, some others)• An integer (in the mathematical sense) can have An integer (in the mathematical sense) can have

an infinite number of values, on a computer an infinite number of values, on a computer however this is limited to ~65,000 values, however this is limited to ~65,000 values, depends on how many bits are used depends on how many bits are used

• Therefore, more memory is needed to store an Therefore, more memory is needed to store an integer than a characterinteger than a character

Computer MemoryComputer Memory

Memory in computers is made up of Memory in computers is made up of transistorstransistors

Transistor: just a switch that can be either Transistor: just a switch that can be either on or off, easier to have just two electrical on or off, easier to have just two electrical states rather that 10 (i.e. to represent 0-9)states rather that 10 (i.e. to represent 0-9)

““on” state corresponds to the value 1, on” state corresponds to the value 1, “off” state corresponds to the value 0“off” state corresponds to the value 0

Everything in memory has to be made up Everything in memory has to be made up of 0s and 1s – i.e., has to be stored as a of 0s and 1s – i.e., has to be stored as a number in base 2 (binary)number in base 2 (binary)

Important to understand different basesImportant to understand different bases

Reminder:Converting Between Reminder:Converting Between BasesBases

To convert numbers in some other base To convert numbers in some other base into base 10 (decimal) values:into base 10 (decimal) values:• For each position, starting with position 0, the For each position, starting with position 0, the

least significant digit (rightmost), take the digit least significant digit (rightmost), take the digit in that position and multiply it by the base in that position and multiply it by the base raised to the power of that position; add the raised to the power of that position; add the values togethervalues together

• 10 in base 2 = 1x210 in base 2 = 1x211 + 0x2 + 0x200 = 2+0 = 2 = 2+0 = 2• 100101 in base 2 = 1x2100101 in base 2 = 1x255 + 1x2 + 1x222 + 1x2 + 1x200 = 32 + = 32 +

4 + 1 = 374 + 1 = 37

Converting Between BasesConverting Between Bases Hexadecimal (base 16) uses the digits 0-9 Hexadecimal (base 16) uses the digits 0-9

+ A-E (A=10, B=11,…E=15) and prefix 0x + A-E (A=10, B=11,…E=15) and prefix 0x to differentiate from decimal //a zero 0 not to differentiate from decimal //a zero 0 not an oan o

To convert binary to hexadecimal, group To convert binary to hexadecimal, group binary digits in groups of 4, convert each binary digits in groups of 4, convert each group of 4 into decimal, and use the group of 4 into decimal, and use the appropriate hex digit for that group of 4appropriate hex digit for that group of 4

100101 in base 2 = 0010 0101100101 in base 2 = 0010 0101first hex digit = 0010 or 2first hex digit = 0010 or 2second hex digit = 0101 or 5second hex digit = 0101 or 50x25 = 2x160x25 = 2x1611 + 5x16 + 5x1600 = 32 + 5 = 37 = 32 + 5 = 37

See See OctalandHex.cppOctalandHex.cpp

Converting Between BasesConverting Between Bases

Octal (base 8) numbers prefixed with 0 Octal (base 8) numbers prefixed with 0 (zero)(zero)

052 in base 8 = 5x8052 in base 8 = 5x811 + 2x8 + 2x800 = 40+ 2 = 42 = 40+ 2 = 42 Octal conversion to binary: same as hex, Octal conversion to binary: same as hex,

but group digits into groups of 3but group digits into groups of 3 100101 in base 2 = 100 101100101 in base 2 = 100 101

first octal digit = 100 or 4first octal digit = 100 or 4second octal digit = 101 or 5second octal digit = 101 or 5045 = 4x8045 = 4x811 + 5x8 + 5x800 = 32 + 5 = 37 = 32 + 5 = 37

See OctalandHex.cppSee OctalandHex.cpp

Common BasesCommon Bases

Binary, octal (base 8), hexadecimal Binary, octal (base 8), hexadecimal (base 16) all common bases in (base 16) all common bases in programmingprogramming

Useful because powers of 2 and easy Useful because powers of 2 and easy to convert between to convert between

Computer memory almost always in Computer memory almost always in powers of 2powers of 2

Back to TypesBack to Types Types typically defined in pieces of memory that are Types typically defined in pieces of memory that are

powers of 2powers of 2 Smallest piece of memory: 1 bit (Binary DigIT)Smallest piece of memory: 1 bit (Binary DigIT)

• Can hold 0 or 1 (equivalent to 1 transistor)Can hold 0 or 1 (equivalent to 1 transistor) 8 bits = 1 byte, 4 bits is a nibble8 bits = 1 byte, 4 bits is a nibble

• 1 byte can have any value between 0000 0000 and 1 byte can have any value between 0000 0000 and 1111 1111 – i.e., between 0 – 255. 1111 1111 – i.e., between 0 – 255.

• 1111 1111 binary1111 1111 binaryhex digit: 1111 = 8+4+2+1 = 15 = Ehex digit: 1111 = 8+4+2+1 = 15 = E0xEE = 15x160xEE = 15x1611 + 15x16 + 15x1600 = 240 + 15 = 255 = 240 + 15 = 255

• More than number of values needed for characters – More than number of values needed for characters – 1 byte typically used for character type1 byte typically used for character type

Numeric TypesNumeric Types

16 bits = 2 bytes can have any value from 16 bits = 2 bytes can have any value from 0000 0000 0000 0000– 1111 1111 1111 1111 0000 0000 0000 0000– 1111 1111 1111 1111 or 0 – 65,535. (Shortcut: 65,535 = 2or 0 – 65,535. (Shortcut: 65,535 = 21616-1)-1)• Was used for a long time for integer valuesWas used for a long time for integer values• If used to store negative integers, could only store If used to store negative integers, could only store

up to +/- 32,768 (approx) why?up to +/- 32,768 (approx) why? 32-bit integers now more common32-bit integers now more common

• Ever heard of 32-bit operating system? Means that Ever heard of 32-bit operating system? Means that main data types used are 32-bitmain data types used are 32-bit

Amount of memory given to each type Amount of memory given to each type dependent on the machine and operating dependent on the machine and operating systemsystem

Type SizesType Sizes

Many different types in C++ (more to Many different types in C++ (more to come)come)• char: a single characterchar: a single character

Often 1 byte, 128 valuesOften 1 byte, 128 values

• int: an integer valueint: an integer value Often 32 bits/4 bytes, 4 billion valuesOften 32 bits/4 bytes, 4 billion values

• float: a floating-point numberfloat: a floating-point number Often 4 bytesOften 4 bytes

• double: a double-precision floating-point double: a double-precision floating-point numbernumber

Double the size of a float, often 64 bits or 8 bytesDouble the size of a float, often 64 bits or 8 bytes

OperatorsOperators

Arithmetic: + - * / % -(unary e.g. -Arithmetic: + - * / % -(unary e.g. -(x+y)) (x+y))

Increment/decrement: ++ --Increment/decrement: ++ -- Relational: > >= < <=Relational: > >= < <= Equality: == !=Equality: == != Assignment: = += -= *=Assignment: = += -= *= Logical: || && Logical: || && Reference/Dereference: & * -- for laterReference/Dereference: & * -- for later

ExpressionsExpressions

Built up out of constant values (e.g., Built up out of constant values (e.g., 5 or 10.7), variables (x, y, etc) and 5 or 10.7), variables (x, y, etc) and operatorsoperators

Number and type of variables has to Number and type of variables has to match what the operator expects – match what the operator expects – like a functionlike a function

Some exceptions when working with Some exceptions when working with numerical variables!numerical variables!

Type conversions (coercion)Type conversions (coercion)

Some types can automatically be Some types can automatically be converted to othersconverted to others

int, float, double can often be treated the int, float, double can often be treated the same for calculation purposessame for calculation purposes• int values will be converted up into floats for int values will be converted up into floats for

calculations.calculations. But major differences between integer and But major differences between integer and

floating-point arithmetic!floating-point arithmetic!• Fractions just dropped in integer arithmeticFractions just dropped in integer arithmetic• Use modulus (%) operator to get remaindersUse modulus (%) operator to get remainders• Integer much faster to performInteger much faster to perform

Expression ExamplesExpression Examples

See/code examplesin.cpp See/code examplesin.cpp Many examples followMany examples follow x, y, z are integer variablesx, y, z are integer variables f and d are float variablesf and d are float variables

ArithmeticArithmetic

y = 5;y = 5; // y is now 5// y is now 5x = y + 3; // x is now 8x = y + 3; // x is now 8f = 2 * 4; // f is now 8.0f = 2 * 4; // f is now 8.0g = f / 3.0; // g is now 2.6…67g = f / 3.0; // g is now 2.6…67y = x / 3; // y is now 2y = x / 3; // y is now 2z = x % 3; // z is now 2z = x % 3; // z is now 2

See ExamplesinCpp.cppSee ExamplesinCpp.cpp

Increment/DecrementIncrement/Decrement

x = 5;x = 5;f = 2.5;f = 2.5;x++; x++; // x is now 6// x is now 6f--;f--; // f is now 1.5// f is now 1.5++f;++f; // f is now 2.5// f is now 2.5--x;--x; // x is now 5// x is now 5

y = ++x – 2; // x = 6, y = 2y = ++x – 2; // x = 6, y = 2g = f-- + 2; // f = 1.5, g = 4.5!g = f-- + 2; // f = 1.5, g = 4.5!//see //see ExamplesinCpp2.cppExamplesinCpp2.cpp

RelationalRelational

x = 5;x = 5;f = 6.0;f = 6.0;y = (x > f); // y = 0 (false)y = (x > f); // y = 0 (false)g = (x <= f); // g = 1 (true)g = (x <= f); // g = 1 (true)

// usually used in conditionals// usually used in conditionalsif (x > f) { if (x > f) { // do something // do something

}}See conditional1.cppSee conditional1.cpp

Relational conditions:Common Relational conditions:Common errorserrors

if (x = 5);if (x = 5);if ((x=5)&&(y=7))if ((x=5)&&(y=7))if ((x>0)&&(x<=))if ((x>0)&&(x<=))

Must use if (x==4) Must use if (x==4) Or if (y!=10)Or if (y!=10)

Equality & AssignmentEquality & Assignment

x = 5; // sets value of x to 5x = 5; // sets value of x to 5if (x == 5) // returns true/falseif (x == 5) // returns true/false{{x += 3; x += 3; // x is now 8 // x is now 8if (x != 5) {if (x != 5) {cout << “x is not 5\n”;cout << “x is not 5\n”;

}}

x *= 2; // x is now 16x *= 2; // x is now 16See conditional2.cppSee conditional2.cpp

LogicalLogical

x = 5;x = 5;y = 2;y = 2;

if ( (x >= 5) && (y < 2) )if ( (x >= 5) && (y < 2) ){{cout << “Both true.\n”;cout << “Both true.\n”;

} else if ( (x >= 5) || (y < 2) ) {} else if ( (x >= 5) || (y < 2) ) {cout << “One is true.\n”;cout << “One is true.\n”;

} else {} else {cout << “Both false!\n”;cout << “Both false!\n”;

}}

Programming in C++Programming in C++

Lecture 2cLecture 2c

Elements of a ProgramElements of a Program

Overview of LectureOverview of Lecture Overview of Computers & ProgrammingOverview of Computers & Programming

• Assembly language vs. C/C++Assembly language vs. C/C++• Compiled vs. interpreted languagesCompiled vs. interpreted languages• Procedural programming vs. Object-oriented Procedural programming vs. Object-oriented

programmingprogramming Elements of a ProgramElements of a Program

• StatementsStatements• FunctionsFunctions• VariablesVariables

TypesTypes• Computer memory & binary arithmeticComputer memory & binary arithmetic• C++ typesC++ types

What Is A Computer?What Is A Computer?

CPU/processor just does a few basic CPU/processor just does a few basic things:things:• Arithmetic unit (adds, subtracts, multiplies, Arithmetic unit (adds, subtracts, multiplies,

divides), sometimes called the ALU the divides), sometimes called the ALU the ArithmeticArithmetic and and Logic UnitLogic Unit

• Memory control (loads and stores integer and Memory control (loads and stores integer and floating-point values from memory) floating-point values from memory)

• Think of address and data buses etcThink of address and data buses etc Everything a computer does is Everything a computer does is

accomplished with these simple operationsaccomplished with these simple operations

Assembly LanguageAssembly Language Computer processors each have their own Computer processors each have their own

built-in assembly language, this is code that built-in assembly language, this is code that the CPU understandsthe CPU understands• E.g., Intel CPUs have their own language that differs E.g., Intel CPUs have their own language that differs

from the language of Motorola Power PC CPUsfrom the language of Motorola Power PC CPUs These have a limited range of commands, These have a limited range of commands,

LOAD, ADD, SUB, MOV etcLOAD, ADD, SUB, MOV etc Each command typically does very littleEach command typically does very little

• Arithmetic commands, load/store from memoryArithmetic commands, load/store from memory Code not totally unreadable, but close, Code not totally unreadable, but close,

fortunately we do not generally write in fortunately we do not generally write in assembly language any more, but it is good to assembly language any more, but it is good to know about it. know about it.

C++ versus AssemblyC++ versus Assembly Here is some simple C++ code:Here is some simple C++ code: assume x, y and z have been definedassume x, y and z have been definedas integersas integers || means the logical || means the logical oror operator operatorx = y + 2;x = y + 2; if ( (x > 0) || ( (y-x) <= z) )if ( (x > 0) || ( (y-x) <= z) )

x = y + z;x = y + z; We will also see three similar lines of code in We will also see three similar lines of code in

Intel x86 assembly language in a moment...Intel x86 assembly language in a moment...

Truth table for Logical orTruth table for Logical or

AA BB A || BA || B

FalseFalse FalseFalse FalseFalse

TrueTrue FalseFalse TrueTrue

FalseFalse TrueTrue TrueTrue

TrueTrue TrueTrue TrueTrue

Truth table for Logical or Truth table for Logical or continuedcontinued

The The predicate A predicate A is: It is is: It is TuesdayTuesday

The The predicate B predicate B is: It is is: It is rainingraining

A || BA || B

FalseFalse FalseFalse FalseFalse

TrueTrue FalseFalse TrueTrue

FalseFalse TrueTrue TrueTrue

TrueTrue TrueTrue TrueTrue

Truth table for And (&&)Truth table for And (&&)

AA BB A && BA && B

FalseFalse FalseFalse FalseFalse

TrueTrue FalseFalse FalseFalse

FalseFalse TrueTrue FalseFalse

TrueTrue TrueTrue truetrue

MOV AX, y // put y into AXMOV BX, x // put x into BXMOV CX, z // put z into CXADD AX, x // add to the contents of AX the

value // x and store in AX

CMP AX, 0 // check whether the contents of AX=0

MOV DX, BX //move contents of BX into DX

SUB DX, AX //subtract the value of contents of //AX and place in DX

CMP DX, CX //compare contents of CX and DX

With more code here...Note it is difficult to understand and quite tedious

even for simple code

The C++ Programming LanguageThe C++ Programming Language

C++ is a higher-level language C++ is a higher-level language compared to assembly language.compared to assembly language.• Much more human-readableMuch more human-readable• Fewer lines of code for same taskFewer lines of code for same task

C is a lower-level language compared to C is a lower-level language compared to others (like C++ and Java which are others (like C++ and Java which are Object Oriented Programming Object Oriented Programming languages), C has no OO capabilities. languages), C has no OO capabilities. • Direct control over memory allocation and Direct control over memory allocation and

cleanup (as we will see)cleanup (as we will see)

Compiled vs. InterpretedCompiled vs. Interpreted For a program to run, the source code For a program to run, the source code

must be translated into the assembly must be translated into the assembly language of the machine the program will language of the machine the program will run on.run on.• Compiled language: the source code is Compiled language: the source code is

translated once and the executable form is translated once and the executable form is run. (C++ and Pascal)run. (C++ and Pascal)

• Interpreted language: an interpreter runs each Interpreted language: an interpreter runs each time the program is started, and it does the time the program is started, and it does the translation on-the-fly (Visual Basic, Perl, other translation on-the-fly (Visual Basic, Perl, other scripting languages and Java).scripting languages and Java).

• Java is compiled and interpreted requires a JVMJava is compiled and interpreted requires a JVM JVM: Java Virtual Machine JVM: Java Virtual Machine

Procedural vs. Object-OrientedProcedural vs. Object-Oriented Procedural ProgrammingProcedural Programming

• A program viewed as a series of instructions to A program viewed as a series of instructions to the computerthe computer

• Instructions are organized into functions and Instructions are organized into functions and libraries of functionslibraries of functions

Object-Oriented ProgrammingObject-Oriented Programming• A program viewed as a set of objects that A program viewed as a set of objects that

interact with each otherinteract with each other• An object encapsulates (hides and binds) An object encapsulates (hides and binds)

functions with the data that the object’s functions with the data that the object’s functions operate onfunctions operate on

Procedural vs. Object-OrientedProcedural vs. Object-Oriented

OOP good for complex systems – nice to OOP good for complex systems – nice to break down into small independent objectsbreak down into small independent objects

Procedural perhaps a bit more intuitive, Procedural perhaps a bit more intuitive, especially for beginners (where we will especially for beginners (where we will commence)commence)

C is a procedural language, no OO C is a procedural language, no OO capabilitiescapabilities

Java and C++ are Object-Oriented Java and C++ are Object-Oriented Languages, Java is pure Object Oriented Languages, Java is pure Object Oriented i.e. everything is an object in Java.i.e. everything is an object in Java.

Explanation of OOP and Explanation of OOP and Procedural ProgrammingProcedural Programming

Perhaps one of the best definitions of the Perhaps one of the best definitions of the difference between these two paradigms is difference between these two paradigms is as follows: as follows:

Consider a chair: a Consider a chair: a procedural procedural programmerprogrammer is interested in in the wood, is interested in in the wood, hammer, screws, screw driver etc i.e., hammer, screws, screw driver etc i.e., everything that went into making the everything that went into making the chair, however the chair, however the Object Oriented Object Oriented ProgrammerProgrammer would be interested only in would be interested only in the chair i.e. the finished articlethe chair i.e. the finished article

Procedural ProgrammingProcedural Programming Program is a set of Program is a set of sequentialsequential steps to be steps to be

executed by the computer, one after executed by the computer, one after another, this is the another, this is the Sequential ParadigmSequential Paradigm

However we do However we do NotNot necessarily run the necessarily run the same steps every time the program runs, same steps every time the program runs, can have can have selectionselection/decisions /decisions • May want to skip steps under certain May want to skip steps under certain

conditions (selection)conditions (selection)• May want to repeat steps under certain May want to repeat steps under certain

conditions (conditions (iterationiteration))• May need to save some information to use May need to save some information to use

later in the program (when computing a sum)later in the program (when computing a sum)

Programming ParadigmsProgramming Paradigms There are three essential programming There are three essential programming

paradigms (the word paradigm is from the Greek paradigms (the word paradigm is from the Greek word meaning example)word meaning example)

Sequential: Sequential: code is executed one after the after code is executed one after the after top-down:top-down:Sequential ParadigmSequential Paradigm

SelectionSelection/decisions. Achieved in C/C++ using /decisions. Achieved in C/C++ using the the if, if-elseif, if-else or or switch-caseswitch-case statements to be met statements to be met in later lectures.in later lectures.

IterationIteration:To be achieved in the C++/Java :To be achieved in the C++/Java languages using the languages using the for for looploop, while , while looploop oror thethe do- do-whilewhile loop, more in later lectures loop, more in later lectures

Elements of a ProgramElements of a Program Individual steps/commands to the computerIndividual steps/commands to the computer

• These are called Statements, a semicolon delimits a These are called Statements, a semicolon delimits a valid C++ statement.valid C++ statement.

Technique to organize code so it is easy to debug, fix, and Technique to organize code so it is easy to debug, fix, and maintain. maintain. Code and fixCode and fix is the most common way that one is the most common way that one programs, but perhaps the worst, SSADM is a better way. programs, but perhaps the worst, SSADM is a better way. SSADM: Structured, System Analysis and Design SSADM: Structured, System Analysis and Design Methodology Methodology • FunctionsFunctions

Way to save information that may change each time the Way to save information that may change each time the program runsprogram runs• Variables vary in a program Variables vary in a program

If we want to change what steps get executed: If we want to change what steps get executed: • Control flow – topic coming soonControl flow – topic coming soon

Code and FixCode and Fix

Write some codeWrite some code Fix problems just createdFix problems just created

• ProblemsProblems• Software complete after n fixesSoftware complete after n fixes• Subsequent fixes are very expensive (time and Subsequent fixes are very expensive (time and

resources)resources)• Previous fixes fail to workPrevious fixes fail to work• Poor fit to users’ needs (reflects programmers Poor fit to users’ needs (reflects programmers

view rather that that of the clients)view rather that that of the clients)

Design

InstallationOperation and Maintenance

Analysis and Specification

Implementation

Testing

Developing software: The traditional approach

The Waterfall ModelThe Waterfall Model Criticisms Criticisms

• Requirements must be fixed before system is designedRequirements must be fixed before system is designed• Design and code produce inconsistencies that are Design and code produce inconsistencies that are

difficult to fixdifficult to fix• Problems are not discovered until the Testing stageProblems are not discovered until the Testing stage• System performance can not be tested until near System performance can not be tested until near

completioncompletion• System underperformance is difficult to fix at this stageSystem underperformance is difficult to fix at this stage

Problems Problems • Ageing techniqueAgeing technique• Less effective for new software paradigms of OOD (UML)Less effective for new software paradigms of OOD (UML)• Costs can spiral out of controlCosts can spiral out of control• Projects can and usually do overrun (inefficient)Projects can and usually do overrun (inefficient)

InitialPlanning

FinalProduct

Analysis

Testing and Quality

Assurance

ReviewingPrototypes

BuildingPrototypes

Developing software: the modern approach (RAD)

FunctionsFunctions

Already have seen the main() Already have seen the main() functionfunction

Functions are used to group Functions are used to group individual statements that together individual statements that together accomplish a single larger taskaccomplish a single larger task

E.g., the main() function contains E.g., the main() function contains many statements that together many statements that together accomplish the task of printing a accomplish the task of printing a message to the screen or filemessage to the screen or file

Simple ExampleSimple Example

#include <iostream>#include <iostream>using namespace std;using namespace std;void printHello() {cout<< “Hello\n”};void printHello() {cout<< “Hello\n”};void printBye() {cout<<“Bye\n”};void printBye() {cout<<“Bye\n”};int main()int main(){{

printHello(); // this is a call to the printHello(); // this is a call to the // function printHello() // function printHello()

printBye(); // this is a call to the printBye(); // this is a call to the // function prinBye// function prinBye

return 0;return 0;}}See program fuctions1.cppSee program fuctions1.cppSee program fuctions1b.cpp (//does not compile) See program fuctions1b.cpp (//does not compile)

as //there are no function prototypesas //there are no function prototypes

Function ElementsFunction Elements Return-typeReturn-type

• Specifies what kind of information the function will returnSpecifies what kind of information the function will return• voidvoid means nothing is returned (called a procedure in other means nothing is returned (called a procedure in other

languages)languages) NameName

• Must be unique within the programMust be unique within the program• It is used to call (invoke) the function – i.e., to cause the function It is used to call (invoke) the function – i.e., to cause the function

statements to be executedstatements to be executed ArgumentsArguments

• Optional information that is used by the functionOptional information that is used by the function BodyBody

• The actual statements within the function groupsThe actual statements within the function groups

VariablesVariables

Used to store information within the Used to store information within the programprogram

Values can change as the program Values can change as the program runs (i.e., are variable)runs (i.e., are variable)• Obtained through calculationsObtained through calculations• From inputFrom input• From function resultsFrom function results

Simple ExamplesSimple Examples

#include <iostream>#include <iostream>using namespace std;using namespace std;int main()int main(){{

int x = 5;//obsolete here as not usedint x = 5;//obsolete here as not usedchar letter = ‘g’;char letter = ‘g’;cout <<“Please enter a character”;cout <<“Please enter a character”;cin >> letter; cin >> letter; cout << “the character input was “ << letter << endl;cout << “the character input was “ << letter << endl;

return 0;return 0;}}//see letter.cpp//see letter.cpp

Variable ElementsVariable Elements TypeType

• Indicates what kind of information can be Indicates what kind of information can be stored in the variablestored in the variable

NameName• Must be unique within a given functionMust be unique within a given function

Except for special Except for special global variablesglobal variables, which must , which must have unique names within the program. Global have unique names within the program. Global variables are not considered good programming variables are not considered good programming practice. Why? practice. Why?

• Used to refer to a variable throughout the Used to refer to a variable throughout the functionfunction

ValueValue• Can be set in many different waysCan be set in many different ways

Declarations vs. DefinitionsDeclarations vs. Definitions

Both functions and variables MUST be Both functions and variables MUST be declared before they can be useddeclared before they can be used

Declaration includes just:Declaration includes just: TypeType NameName Arguments (for functions)Arguments (for functions)

Definition can come later!Definition can come later!• For variables: value can be assigned later (as For variables: value can be assigned later (as

long as it is before its first use or garbage will long as it is before its first use or garbage will be used)be used)

• For functions: body of function can be added For functions: body of function can be added laterlater

Complex ExampleComplex Example See the functions1.cpp, function2.cpp and See the functions1.cpp, function2.cpp and

function3.cpp example codefunction3.cpp example code Variable declaration:Variable declaration:

• int x; char input[1000];int x; char input[1000]; Function declaration (prototype):Function declaration (prototype):

• void printHello();void printHello(); Function definitionFunction definition

• void printHello() void printHello() {{

cout << “Hello”<< endl;cout << “Hello”<< endl;}}

Important RulesImportant Rules

All variables and functions must be All variables and functions must be declared in the function/file where declared in the function/file where they are going to be used BEFORE they are going to be used BEFORE they are used.they are used.

All variables must be initialized to All variables must be initialized to some starting value before being some starting value before being used in calculations or being printed used in calculations or being printed out, otherwise we get rubbishout, otherwise we get rubbish

StatementsStatements

A statement is a single line of codeA statement is a single line of code Can be:Can be:

• Variable or function declarationsVariable or function declarations• Arithmetic operations Arithmetic operations

x = 5+3;x = 5+3;

• Function callsFunction calls Calcsum(x,y);Calcsum(x,y);

• Control flow commandsControl flow commands• More to be seen…More to be seen…

TypesTypes

““Type” in C++ refers to the kind of Type” in C++ refers to the kind of data or informationdata or information

Functions have return typesFunctions have return types Arguments to functions each have Arguments to functions each have

their own typetheir own type Variables have typesVariables have types

Why Type?Why Type? Why do we have to specify types of Why do we have to specify types of

variables, functions, arguments?variables, functions, arguments? Has to do with computer memoryHas to do with computer memory Different kinds of data require different Different kinds of data require different

amounts of memory to storeamounts of memory to store• A single character can have only one of 128 A single character can have only one of 128

values (a-z,A-Z,0-9,punctuation, some others)values (a-z,A-Z,0-9,punctuation, some others)• An integer in mathematics can have an infinite An integer in mathematics can have an infinite

number of values, limited to ~65,000 values on number of values, limited to ~65,000 values on a computera computer

• Therefore, more memory needed to store an Therefore, more memory needed to store an integer than a characterinteger than a character

Computer MemoryComputer Memory

Memory in computers made up of Memory in computers made up of transistorstransistors

Transistor: just a switch that can be either Transistor: just a switch that can be either on or offon or off

““on” state corresponds to the value 1, on” state corresponds to the value 1, “off” state corresponds to the value 0“off” state corresponds to the value 0

Everything in memory has to be made up Everything in memory has to be made up of 0s and 1s – i.e., has to be stored as a of 0s and 1s – i.e., has to be stored as a number in base 2 (binary)number in base 2 (binary)

Important to understand different basesImportant to understand different bases

Numeric TypesNumeric Types

16 bits = 2 bytes can have any value from 16 bits = 2 bytes can have any value from 0000 0000 0000 0000–1111 1111 1111 1111 0000 0000 0000 0000–1111 1111 1111 1111 or 0 – 65,535. (Shortcut: 65,535 = 2or 0 – 65,535. (Shortcut: 65,535 = 21616-1)-1)• Was used for a long time for integer valuesWas used for a long time for integer values• If used to store negative integers, could only store If used to store negative integers, could only store

up to +/- 32,768 (approx)up to +/- 32,768 (approx) 32-bit integers now more common32-bit integers now more common

• Ever heard of 32-bit operating system? Means that Ever heard of 32-bit operating system? Means that main data types used are 32-bitmain data types used are 32-bit

Amount of memory given to each type Amount of memory given to each type dependent on the machine and operating dependent on the machine and operating systemsystem

Next TimeNext Time

More on typesMore on types OperatorsOperators

• Arithmetic: + - * /Arithmetic: + - * /• Assignment: =Assignment: =• Increment/Decrement: ++ --Increment/Decrement: ++ --

Expressions/StatementsExpressions/Statements• DeclarationsDeclarations• AssignmentsAssignments• Other one-line operationsOther one-line operations

More program examplesMore program examples

Casting Casting int i = 16;int i = 16; double d;double d; d = i; // will give, d = 16.0d = i; // will give, d = 16.0 d = 10.3;d = 10.3; i = d; // will give i = 10i = d; // will give i = 10 cout << 2 * 3.4 + 7 / 2; // 6.8 + 3 = 9.8 cout << 2 * 3.4 + 7 / 2; // 6.8 + 3 = 9.8

(a //double), note 7/2 is evaluated as an (a //double), note 7/2 is evaluated as an integer integer

//ignoring the remainder. //ignoring the remainder. //see casting.cpp//see casting.cpp

Conditional StatementsConditional Statements

Conditions take the form:Conditions take the form: if (condition)if (condition) {statements executed if the {statements executed if the

condition is true }condition is true } elseelse {statements executed if the {statements executed if the

condition is false }condition is false }

Conditions Conditions Execution resumes here with the “if Execution resumes here with the “if

statement” having been executed. statement” having been executed. Note that the first line does not end with a Note that the first line does not end with a

semicolon. semicolon. The curly brackets are necessary only if The curly brackets are necessary only if

there are several statements. there are several statements. If you are only executing one statement as If you are only executing one statement as

a result of the condition, you can place it a result of the condition, you can place it on the same line or the next. on the same line or the next.

For example:For example:

Conditions Conditions

See tennis.cppSee tennis.cpp

Relational operators.Relational operators.

Relational operators allow you to compare Relational operators allow you to compare two or more items of data in an two or more items of data in an expression.expression.

= = is equal to (comparison operator)= = is equal to (comparison operator) != is not equal to!= is not equal to > is greater than> is greater than < is less than< is less than >= is greater than or equal to>= is greater than or equal to <= is less than or equal to<= is less than or equal to

Relations Relations

The mathematical operators < and > The mathematical operators < and > can be used with strings to can be used with strings to determine alphabetical order. determine alphabetical order.

For example:For example: ("abc" < "def")("abc" < "def") this is also true this is also true ("d">"b")("d">"b")

RelationsRelations When dealing with non-alphanumeric characters When dealing with non-alphanumeric characters

(i.e. numbers and letters), you need to know (i.e. numbers and letters), you need to know which character set, or code page, you are using which character set, or code page, you are using before you can determine the alphabetical order before you can determine the alphabetical order of a set of strings. of a set of strings.

The most common code page is the The most common code page is the ASCIIASCII (American Standard Code for Information (American Standard Code for Information Exchange). The EBDIC (Extended Binary Decimal Exchange). The EBDIC (Extended Binary Decimal Interchange Code) is used in large IBM Interchange Code) is used in large IBM mainframes. mainframes.

The first 33 characters of the ASCII character set The first 33 characters of the ASCII character set are non-printable control codes (CTRL, carriage are non-printable control codes (CTRL, carriage return etc).return etc).

Common pitfall with Boolean Common pitfall with Boolean expressions.expressions.

It is easy to write:It is easy to write: if (x or y > 0) if (x or y > 0) rather thanrather than if (x > 0 or y > 0) // using Borlandif (x > 0 or y > 0) // using Borland

//C++ //C++ if ((x>0)||(y>0))if ((x>0)||(y>0))

Explanation Explanation

which are both correct code but which are both correct code but logically different. logically different.

The first expression literally means The first expression literally means "if x is true or y is greater than zero", "if x is true or y is greater than zero", and x is always true for non-zero and x is always true for non-zero values of x.values of x.

Lazy evaluation.Lazy evaluation.

C++ compilers implement so-called lazy C++ compilers implement so-called lazy evaluation, in which Boolean expressions evaluation, in which Boolean expressions are evaluated only until their result is are evaluated only until their result is clear. clear.

For example, false For example, false and and anything is always anything is always false, true false, true or or anything is always true. anything is always true.

This is a useful technique when you want This is a useful technique when you want to avoid making calculations that might to avoid making calculations that might cause a crash. For example:cause a crash. For example:

Lazy evaluationLazy evaluation

if (second > 0 && first/second > 1.2) if (second > 0 && first/second > 1.2) // eliminate the possibility of // eliminate the possibility of dividing by //zerodividing by //zero

{...{... }}

Lazy evaluation Lazy evaluation

In this case if second is indeed zero, In this case if second is indeed zero, then the potentially fatal calculation then the potentially fatal calculation of first /second is never executed.of first /second is never executed.

Boolean variables. Boolean variables.

Some conditions are used several times in Some conditions are used several times in the course of a calculation, for example, the course of a calculation, for example, whether an individual is entitled to a whether an individual is entitled to a discount. discount.

Rather than re-evaluating the condition Rather than re-evaluating the condition you can store it in the form of a Boolean you can store it in the form of a Boolean variable. Hence:variable. Hence:

bool half_price = day = = "Monday" !! bool half_price = day = = "Monday" !! age < 15 !! row >= "w";age < 15 !! row >= "w";

Conditional operator, ? (the Conditional operator, ? (the operator is the ?)operator is the ?)

It is possible to abbreviate some It is possible to abbreviate some condition statements using the ? condition statements using the ? operator as follows:operator as follows:

conditional_expression ? conditional_expression ? expression_1 : expression_2expression_1 : expression_2

Conditional operatorConditional operator

in which, if conditional_expression is in which, if conditional_expression is true, expression_1 is performed, true, expression_1 is performed, otherwise expression_2 is carried otherwise expression_2 is carried out. out.

Note that the expressions must be of Note that the expressions must be of the same type. the same type.

You can use the conditional operator You can use the conditional operator in a straightforward assignment, or in a straightforward assignment, or within a more complex statement:within a more complex statement:

Conditional operator Conditional operator

max = x > y ? x : y; max = x > y ? x : y; //Assigns to max the larger of x and y//Assigns to max the larger of x and y cout << (s.length() < t.length() ? s : cout << (s.length() < t.length() ? s :

t); // prints the shorter of s and tt); // prints the shorter of s and t

The switch statement. (case The switch statement. (case statement of Pascal)statement of Pascal)

This switch statement allows you to This switch statement allows you to control the flow of your program by control the flow of your program by specifying a number of different specifying a number of different cases or conditions, rather than cases or conditions, rather than simply true or false. simply true or false.

See switch1.cppSee switch1.cpp

Switch Switch The switch keyword works by entering program flow at the The switch keyword works by entering program flow at the

statement whose case matches the expression. All subsequent statement whose case matches the expression. All subsequent statements are executed as well, so that if expression were 3 in statements are executed as well, so that if expression were 3 in this example, the output would be 363invalid value. This has been this example, the output would be 363invalid value. This has been obtained by entering the code at the line obtained by entering the code at the line

case 3: cout << x * 3; // then multiplying 12 (i.e. x) by 3 giving case 3: cout << x * 3; // then multiplying 12 (i.e. x) by 3 giving the 36, the 36,

then proceeding to the line then proceeding to the line case 4: cout << x / 4; // then dividing 12 by 4 giving the 3, case 4: cout << x / 4; // then dividing 12 by 4 giving the 3, then proceeding to the final line and outputting the string Invalid then proceeding to the final line and outputting the string Invalid

OutputOutput You can avoid this state of affairs by placing a You can avoid this state of affairs by placing a breakbreak keyword at keyword at

the end of each case statement, to go to the statement after the the end of each case statement, to go to the statement after the curly brackets. switch statements are of limited use: expression curly brackets. switch statements are of limited use: expression must always evaluate to a literal and you can have only one value must always evaluate to a literal and you can have only one value per case. per case.

Recommended