Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topics this week Computer Programming Computer Programming Programming Life-Cycle Phases Programming Life-Cycle Phases Creating an Algorithm Creating an.

Similar presentations


Presentation on theme: "Topics this week Computer Programming Computer Programming Programming Life-Cycle Phases Programming Life-Cycle Phases Creating an Algorithm Creating an."— Presentation transcript:

1 Topics this week Computer Programming Computer Programming Programming Life-Cycle Phases Programming Life-Cycle Phases Creating an Algorithm Creating an Algorithm Machine Language vs. High Level Languages Machine Language vs. High Level Languages Compilation and Execution Processes Compilation and Execution Processes Problem-Solving Techniques Problem-Solving Techniques

2 What is Computer Programming? It is the process of planning and implementing a sequence of steps (called instructions) for a computer to follow in order to solve a problem. It is the process of planning and implementing a sequence of steps (called instructions) for a computer to follow in order to solve a problem. STEP 1 STEP 2 STEP 3...

3 99.99% of Programs Getting some information into the program Getting some information into the program Doing something with the information Doing something with the information Displaying results Displaying results Nearly all of programs you write will involve:

4 Previously we spoke about: Programming Life Cycle 1 Problem-Solving Phase Analysis and Specification Analysis and Specification General Solution (Algorithm) General Solution (Algorithm) Test/Verify (Desk check) Test/Verify (Desk check) 2 Implementation Phase Concrete Solution (Program) Concrete Solution (Program) Test/Verify Test/Verify 3 Maintenance Phase Use Use Maintain (update, maintain) Maintain (update, maintain)

5 A Tempting Shortcut? GOAL THINKING Problem solving CODE Implementation REVISE DEBUG TEST CODE Shortcut? No thinking

6 Problem-Solving Phase ANALYZE the problem and SPECIFY what the solution must do. ANALYZE the problem and SPECIFY what the solution must do. Develop and write down on a piece of paper GENERAL SOLUTION (ALGORITHM) to solve the problem Develop and write down on a piece of paper GENERAL SOLUTION (ALGORITHM) to solve the problem VERIFY that your solution really solves the problem. VERIFY that your solution really solves the problem. How will you know whether your solution is correct? How will you know whether your solution is correct?

7 Example A programmer needs an algorithm to determine an employee’s weekly wages. First think: How would the calculations be done by hand? How would the calculations be done by hand? Is there anything that is fixed or constant? Is there anything that is fixed or constant? Is there anything that changes/varies every time I do the sum? Is there anything that changes/varies every time I do the sum?

8 Analysis: One Employee’s Wages Assumptions/Known: 40 hours is a normal week Normal Hourly Rate of pay £4.00/hour Overtime rate of pay £6.00/hour Variables/Things that change Actual hours worked in one week:

9 If HoursWorked are more than 40.0 then wages = (40.0 * NormalRate) + (HoursWorked - 40.0) * OvertimeRate otherwise, wages = HoursWorked * NormalRate wages = HoursWorked * NormalRate Processes/Algorithm: Calculate Weekly Wages

10 Desk Check Calculations (use for testing algorithm) Use 2 examples of 30 hours and 50 hours Why? Case 1: 30 hours worked 30 x £ 4.00 = £120.00 ___________ £ 120.00 Case 2: 50 hours worked 40 x £ 4.00 = £160.00 10 x £6.00 = £60.00 ___________ £ 220.00 What are the employee’s wages in each case?

11 IPO Chart Inputs-Process-Outputs Inputs Information the computer needs Processes Things computer needs to do with Inputs Outputs Results computer must display NormalHours HoursWorked NormalRate OvertimeRate If HoursWorked are more than 40.0 then wages = (40.0 * NormalRate) + (HoursWorked - 40.0) * OvertimeRate otherwise, wages = HoursWorked * NormalRate Wages

12 General Algorithm to Determine an Employee’s Weekly Wages 1. Initialise employee’s NormalRate and OvertimeRate. 2. Get the HoursWorked this week from user 3. Calculate the wages 4. Display the answer It is written in English! We call this pseudocode:

13 Implementation We cannot simply write this pseudocode algorithm as a program. We cannot simply write this pseudocode algorithm as a program. It is merely a program DESIGN It is merely a program DESIGN YOU have to convert the DESIGN to your chosen programming language (ours at present is C++) YOU have to convert the DESIGN to your chosen programming language (ours at present is C++) A good design is one that can be easily converted into code not just C++. A good design is one that can be easily converted into code not just C++. A poor design is difficult to convert A poor design is difficult to convert A design should be “language” independent A 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

14 So what is a Programming Language? It is a language with strict grammatical rules, symbols, and special words used to construct a computer program. It is a language with strict grammatical rules, symbols, and special words used to construct a computer program. Syntax = grammarSyntax = grammar Semantics = meaningSemantics = meaning

15 Why a programming language? What is wrong with English? Computers do not understand English! Computers do not understand English! English is a natural language and requires each of us to understand meaning by context. English is a natural language and requires each of us to understand meaning by context. For Example For Example Lung Cancer in Women explodesLung Cancer in Women explodes Red Tape Holds Up New BridgesRed Tape Holds Up New Bridges Hospitals are sued by 7 Foot DoctorsHospitals are sued by 7 Foot Doctors Star's Broken Leg Hits Box OfficeStar's Broken Leg Hits Box Office Villagers Grill Gas MenVillagers Grill Gas Men

16 Computers are really stupid! Computers do not understand anything! Computers do not understand anything! well not quite they understand what a 1 and a 0 is.well not quite they understand what a 1 and a 0 is. Computers follow instructions Computers follow instructions Instructions have to be written in 1s and 0sInstructions have to be written in 1s and 0s Such instructions are called machine code.Such instructions are called machine code. We do not write in machine codeWe do not write in machine code

17 Machine language  Machine languages 11000000 000000000001 000000000010 11000000 000000000001 000000000010 Add contents of memory location 1 to contents of memory location 2  Not easy to write programs in! Assembly  ADD 12  Needs an assembler to translate to machine language (an assembler is software that converts the program into machine code) Opcode

18 Levels of Programming 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, Basic, Visual Basic, Prolog, C, C++ and JavaCOBOL, Pascal, FORTRAN, Logo, Basic, Visual Basic, Prolog, C, C++ and Java

19 High level languages Deliberately terse (concise). Deliberately terse (concise). Must be unambiguous. Must be unambiguous. Must be flexible enough to easily implement algorithms. Must be flexible enough to easily implement algorithms. Fairly portable Fairly portable

20 Creating machine (executable) code from C++ source code : Compilation and linking source code compiler object code linked to libraries.exe file

21 Implementation Phase: Test TESTING your program means running (executing) your program on the computer, to see if it produces correct results. (Verification) TESTING your program means running (executing) your program on the computer, to see if it produces correct results. (Verification) if it does not, then you must find out what is wrong with your program or algorithm and fix it--this is called debugging. if it does not, then you must find out what is wrong with your program or algorithm and fix it--this is called debugging. Compilers do not fix logic errors. Compilers do not fix logic errors.

22 Maintenance Phase USE and MODIFY the program to meet changing requirements or correct errors that show up when using it USE and MODIFY the program to meet changing requirements or correct errors that show up when using it maintenance begins when your program is put into use and accounts for the majority of effort on most programs maintenance begins when your program is put into use and accounts for the majority of effort on most programs You will not be concerned very much with this phase while you learn. You will not be concerned very much with this phase while you learn. But when you are in industry this is a massive part of your job! But when you are in industry this is a massive part of your job!

23 The Basic Control Structures in programming a sequence is a series of statements that execute one after another a sequence is a series of statements that execute one after another selection (branch) is used to execute different statements depending on certain conditions (Boolean conditions) selection (branch) is used to execute different statements depending on certain conditions (Boolean conditions) Iteration (repetition) is used to repeat statements while certain conditions are met. Often requires the use of loops. Iteration (repetition) is used to repeat statements while certain conditions are met. Often requires the use of loops.

24 Organising Structures (functions in C++) Stepwise refinement Stepwise refinement Breaking big problems into smaller bitsBreaking big problems into smaller bits “Natural” problem solving strategy “Natural” problem solving strategy Most common approach in programming Most common approach in programming Different people can work on different “bits” Different people can work on different “bits” Nearly all high level languages support this Nearly all high level languages support this

25 Stepwise refinement the breaking down of problems into a series of single-function tasks and single-function subtasks. the breaking down of problems into a series of single-function tasks and single-function subtasks. We previously discussed functions. We previously discussed functions.

26 SEQUENCES 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!

27 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

28 LOOP (repetition) Statement1 Condition... False True WHILE Condition DO Statement1 So Statement1 is executed as long as the condition is true.

29 Loop (repetition) Example 1.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

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

31 Subprogram 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

32 Use 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

33 #include 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 number cin >> 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 number cin >> n; } // 3) end loop return 0; } double CalculateResult(double number) { // subprogram/function definition float result; if (number > 0) result = number * 10.0; else result = number * -10.0; return result; }//see calculate1.cpp

34 Problem Solving Techniques OVERCOME MENTAL BLOCK -- by rewriting the problem in your own words OVERCOME MENTAL BLOCK -- by rewriting the problem in your own words DRAW A FIGURE/DIAGRAM DRAW A FIGURE/DIAGRAM ASK QUESTIONS – ASK QUESTIONS – What is the data, What sort of data is it? What would be good identifiers (names) for the data.What is the data, What sort of data is it? What would be good identifiers (names) for the data. How much data is there, where does it come from? Is it given? Do you get it from the user? Do you calculate it? Do you get it from a file?How much data is there, where does it come from? Is it given? Do you get it from the user? Do you calculate it? Do you get it from a file? Can you identify what is input and what is to be output?Can you identify what is input and what is to be output? What are the processes?What are the processes? Do you need to repeat steps Do 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 conditions What are the conditions

35 Problem Solving Techniques LOOK FOR FAMILIAR THINGS -- certain situations arise again and again. E.g. creating tables, adding up lists of numbers, reading from files. LOOK FOR FAMILIAR THINGS -- certain situations arise again and again. E.g. creating tables, adding up lists of numbers, reading from files. Do you know any equations? Do you know any equations? Find the area of a room, find the stopping distance of a car.Find the area of a room, find the stopping distance of a car. SOLVE BY ANALOGY -- it may give you a place to start. In a broader sense than looking for familiar things. SOLVE BY ANALOGY -- it may give you a place to start. In a broader sense than looking for familiar things. E.g. Finding the student with the highest and lowest score is analogous to finding the highest and lowest temperature.E.g. Finding the student with the highest and lowest score is analogous to finding the highest and lowest temperature.

36 Problem Solving USE MEANS-ENDS ANALYSIS USE MEANS-ENDS ANALYSIS Where you often know start conditions and know what the end goal is.Where you often know start conditions and know what the end goal is. Identify intermediate goals then think how you get from the start to any intermediary goalsIdentify intermediate goals then think how you get from the start to any intermediary goals E.g. How do you find your way to the canteen/bar from here?E.g. How do you find your way to the canteen/bar from here? Setup intermediary goals: get to reception, past bookshop, security and lifts then canteen. Setup intermediary goals: get to reception, past bookshop, security and lifts then canteen. Get to stairs, get to reception, go down the stairs Get to stairs, get to reception, go down the stairs

37 More Problem Solving Techniques Stepwise refinement -- break up large problems into manageable units. Stepwise refinement -- break up large problems into manageable units. SIMPLIFY SIMPLIFY Can you solve a simpler but related problem?Can you solve a simpler but related problem? E.g. Bobs DIY:- Do not attempt to solve the general problem but solve the simpler casesE.g. Bobs DIY:- Do not attempt to solve the general problem but solve the simpler cases BUILDING-BLOCK APPPROACH -- can you solve small pieces of the problem? And then join them up BUILDING-BLOCK APPPROACH -- can you solve small pieces of the problem? And then join them up E.g. a large application like a word processor has many functions. (Text manipulation, Tables, drawing)E.g. a large application like a word processor has many functions. (Text manipulation, Tables, drawing) Do not try to solve all at once.Do not try to solve all at once.

38 Result of Problem solving 1. One or more pages of rough work that sketches your ideas of problem requirements, of user inputs, of outputs, of constants, of conditions for repetition and selection, of assumptions. 2. A formal written design that includes: 1.inputs, Processes, Outputs, assumptions. Create an IPO chart 2.Write steps to process input unambiguously using a semi formal notation (PDL, Flowchart or structure diagram?) Can you translate each step of the plan into C++ easily? 3.Verification/testing procedures documented (A test table).

39 What we are aiming for is a Structured Systematic Approach to Programming Advantages: Not one giant step, but breaks in to smaller and smaller chunks. Not one giant step, but breaks in to smaller and smaller chunks. Programmer concentrates on details Programmer concentrates on details Easy to do in teams Easy to do in teams Easy to keep track of development Easy to keep track of development Creates more reliable and robust programs. Creates more reliable and robust programs. These terms are a bit ambiguous, different programmers give different definitions hereThese terms are a bit ambiguous, different programmers give different definitions here Makes more possible reuse and extensibility. Makes more possible reuse and extensibility.

40 Structured Programming Errors isolated Errors isolated Design written in code Design written in code Improves reliability Improves reliability Minimizes risk of Failure Minimizes risk of Failure Faster development Faster development Full documentation Full documentation MaintainabilityMaintainability

41  So find a solution, write it down in English.  Write it down more formally in Pseudo- code (PDL), or as a structure diagram or a flow chart.  Start your programming environment and convert your pseudo-code to C++  Tell the computer to convert the C++ to machine language (compile)  Tell the computer to load the machine language into memory and execute (Run). Summary

42 Note Learning C++ syntax by heart is useless! Learning C++ syntax by heart is useless! Experience is essential Experience is essential You will need to build up a virtual scrapbook of techniques to be successfu l You will need to build up a virtual scrapbook of techniques to be successfu l

43 “Get some information in, Do something with it, Display the result.”

44 “Get some information in, Do something with it, Display the result.”

45 Topics Structure of a simple C++ Program Structure of a simple C++ Program TYPES of information TYPES of information Simple and ComplexSimple and Complex Variables, Constants and Literals Variables, Constants and Literals Identifiers: to Name memory Identifiers: to Name memory Declarations Declarations Getting information into your program Getting information into your program Operator basics Operator basics

46 Shortest C++ Program. A Skeleton program int main ( ) { return 0; } //already run and discussed type of returned value name of function

47 What happens? The operating system (Windows ) The operating system (Windows ) “Loads” the program “Loads” the program Think of it as WINDOWS calling the “main” function. Think of it as WINDOWS calling the “main” function. Instructions “in main” are carried out one at a time. Instructions “in main” are carried out one at a time. Notice the “int” in front of “main” this line is like a contract to the operating system Notice the “int” in front of “main” this line is like a contract to the operating system “I will send you a piece of information in the form of an integer.”“I will send you a piece of information in the form of an integer.” Hence the NEED for a return instruction. return 0 sends a zero to windows XPHence the NEED for a return instruction. return 0 sends a zero to windows XP

48 Discussion of structure Your program must have a function called “main” Your program must have a function called “main” Note that Main, MAIN, mAiN will cause an error Note that Main, MAIN, mAiN will cause an error The round brackets ‘(‘ and ‘)’after main tells the computer that main is a function rather than a variable The round brackets ‘(‘ and ‘)’after main tells the computer that main is a function rather than a variable The curly brackets (parentheses) ‘{‘ and ‘}’ mark the beginning and end of instructions that form the body of main. The curly brackets (parentheses) ‘{‘ and ‘}’ mark the beginning and end of instructions that form the body of main. i.e. They are blocksi.e. They are blocks The semi-colon ‘;’ after return 0 is an instruction terminator or separator. The semi-colon ‘;’ after return 0 is an instruction terminator or separator.

49 #include using namespace std; int main ( ) { cout << “Hello World” << endl; return 0; } //already run The “Hello World” Program uses complex information i.e. the display (cout) needs more effort Instructions to tell computer that I want to use standard complex OBJECTS for input and output

50 Discussion of Hello World Program There are now two instructions in main There are now two instructions in main we added a display information instruction using a complex OBJECT coutwe added a display information instruction using a complex OBJECT cout cout represents the display screen. That is why it is complex. It hides all the complicated business of displaying things from you. All you need to know is how to send information to cout.cout represents the display screen. That is why it is complex. It hides all the complicated business of displaying things from you. All you need to know is how to send information to cout. cout receives information using the “<<“ send to operator.cout receives information using the “<<“ send to operator. So we literally send the string “Hello World” to the display!So we literally send the string “Hello World” to the display! endl is also sent to the display, this is interpreted by cout as a new-line command.endl is also sent to the display, this is interpreted by cout as a new-line command.

51 Discussion 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 greatly from machine to machine. Sending information to screens varies greatly from machine to machine. So cout became “standard”. So cout became “standard”. Customised cout’s were created for all the major types of computer in the world. Customised cout’s were created for all the major types of computer in the world. So that you can write one piece of code that should compile on all the main types of computer in the world. So that you can write one piece of code that should compile on all the main types of computer in the world.

52 Discussion of Hello World Because cout is NOT “BUILT IN” we need to tell the computer that we want to make use of the “standard” facilities for input and output Because cout is NOT “BUILT IN” we need to tell the computer that we want to make use of the “standard” facilities for input and output HENCE the lines HENCE the lines #include #include 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

53 Some Definitions Statements Statements A statement is what programmers often call an instruction.A statement is what programmers often call an 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 blocks blocks Any section of code which is surrounded by curly brackets is a block { }Any section of code which is surrounded by curly brackets is a block { }

54 Example A Block of 4 statements { cout <<"A fraction: "<<5.0/8.0 <<endl; cout <<"Big # : "<< 7000.0*7000.0<<endl; cout <<8 + 5 <<" is the sum of 8 & 5\n"; cout << “Hello world”; } Block denoted by Curly braces

55 TYPES 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 double)To hold numbers with fractions (float and 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

56 Simple Information integer (whole numbers) integer (whole numbers) For counting thingsFor counting things To represent values which only have whole numbersTo represent values which only have whole numbers Pounds, Pence? Pounds, Pence? Grades, Scores (Chelsea 10 : United 0) Grades, Scores (Chelsea 10 : United 0) Categories Categories int

57 Simple Information Floating points numbers Floating points numbers For representing numbers that may contain fractionsFor representing numbers that may contain fractions Averages, measurements.Averages, measurements. pi, e, phipi, e, phi floatdouble

58 Simple information Single characters Single characters Can represents your initials Can represents your initials Can represent single key responses to questions Can represent single key responses to questions ‘y’ for yes and ‘n’ for no‘y’ for yes and ‘n’ for no Not much else Not much else

59 What about Strings In some languages this is a simple piece of information In some languages this is a simple piece of information In C++ it is not. A string is complex in that it is made up of lots of chars. In C++ it is not. A string is complex in that it is made up of lots of chars. In C++ we use the “standard” string facilities In C++ we use the “standard” string facilities #include string

60 Recap! Your programs will initially entail Your programs will initially entail Getting information into the computerGetting information into the computer This information will either be whole numbers, floating point numbers, single characters or strings. This information will either be whole numbers, floating point numbers, single characters or strings. More complex information we will cover at a later date. More complex information we will cover at a later date. Doing something (operate on) with the information (int, float, double, char or string)Doing something (operate on) with the information (int, float, double, char or string) Displaying resultsDisplaying results

61 Constants, Variables and Literals Remember at school Area of a circle is πr 2 Circumference of a circle is 2πr π is a constant representing the number 3.1415925 ….. r is a variable representing the radius of a circle 2 literally represents itself, it is a literal Fundamental building blocks of programs

62 Key programming concept Programs use, variables, constants and literals to store information needed to solve problems Programs use, variables, constants and literals to store information needed to solve problems Remember the bank problem or Bobs DIY (looked at) we used variables to hold values for wall height and widths etc. Remember the bank problem or Bobs DIY (looked at) we used variables to hold values for wall height and widths etc.

63 Fundamental task is Getting information in to the computer Key ideas Key ideas We enter values of literals directly into code.We enter values of literals directly into code. We enter values of constants directly into codeWe enter values of constants directly into code We have a choice on how we enter values of variables.We have a choice on how we enter values of variables. We can enter values directly We 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.

64 Using literals char, string, integer, float and double values are referred to by value not by a name. char, string, integer, float and double values are referred to by value not by a name. We type these directly into code We type these directly into code #include using namespace std; int main() { cout <<“The sum of one plus three is “ << 1 + 3 << endl; return 0 } string literal 2 integer literals

65 Char literals #include using namespace std; int main() { cout <<“First letter of the alphabet is “ << ‘A’ << endl; return 0; } //see char1.cpp char literals in SINGLE QUOTES

66 floating point literals floating point number can contain fractions. floating point number can contain fractions. floating point literals are doubles floating point literals are doubles #include 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

67 Discussion You can enter information directly into code using literals You can enter information directly into code using literals This is obviously very limiting if a program wanted to reuse a value we need to keep typing in its value every time. This is obviously very limiting if a program wanted to reuse a value we need to keep typing in its value every time. Also if a program makes use of a value many times it is hard work to change all the CORRECT references in a long program, especially if the number, say 10 refers to a count in one part of the program and the number 10 means a grade in another. Also if a program makes use of a value many times it is hard work to change all the CORRECT references in a long program, especially if the number, say 10 refers to a count in one part of the program and the number 10 means a grade in another. How can we differentiate between them? How can we differentiate between them? It can also be very confusing for another person to understand what the numbers mean. It can also be very confusing for another person to understand what the numbers mean.

68 Solution Variables and Constants These are NAMED areas of memory. These are NAMED areas of memory. The programmer instructs the computer to reserve space for the kind of information he/she wants and at the same time tell the computer the name that will be used to refer to that bit of information. The programmer instructs the computer to reserve space for the kind of information he/she wants and at the same time tell the computer the name that will be used to refer to that bit of information. This kind of instruction is called a DECLARATION This kind of instruction is called a DECLARATION

69 DECLARATION We can declare We can declare integersintegers floating point numbers (doubles)floating point numbers (doubles) charschars stringsstrings

70 Constants and Variable Declarations When a variable is declared the computer marks the bit of memory reserved so that it allows its contents to change (vary) at any time. In particular at run time When a variable is declared the computer marks the bit of memory reserved so that it allows its contents to change (vary) at any time. In particular at run time When a constant is declared the computer effectively locks the memory reserved and prevents the contents being updated. When a constant is declared the computer effectively locks the memory reserved and prevents the contents being updated.

71 Creating Constants and Variables #include 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 memory space big enough to store our information. It also creates an identifier (a name) for us to refer to this memory space

72 Rules for Creating Constants const type identifier = value; choose one of int char float double string You create a name. It must obey the rules for identifiers (see rules in a minute) You provide the constant value e.g. for Pi value was 3.141592

73 Examples const int maxnumber = 10; const double Pi = 3.142; const char AGrade = ‘A’; const string MyName = “Vas”;

74 Rules for Creating Variables type identifier; or Type identifier = value; or type identifier, identifier, …;

75 Examples int 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;

76 Rules for Creating Identifiers An identifier must start with a letter or underscore, and be followed by zero or more letters An identifier must start with a letter or underscore, 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 VALID VALID age_of_dogtaxRateY2K PrintHeadingageOfHorse NOT VALID (Why?) NOT VALID (Why?) age# 2000TaxRate Age-Of-Cat Age of Cat Age of Cat

77 Meaningful Identifiers Age-Of-Cat Age of Cat ILLEGAL!! Use underscore to link words or run words together and capitalise the start of each word Age_Of_Cat AgeOfCat LEGAL!!

78 More About Identifiers C++ is case sensitive so C++ is case sensitive so NUMBER Number number are all legitimate but DIFFERENT identifiers 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?

79 Long Identifier Names Some C++ compilers recognize only the first 32 characters of an identifier as significant Some C++ compilers recognize only the first 32 characters of 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_Zoo age_Of_This_Old_Rhinoceros_At_My_Safar i Also it is very annoying to keep typing in! Also it is very annoying to keep typing in!

80 Meaningful Identifiers It is common sense to try to create identifiers that are: It is common sense to try to create identifiers that are: Meaningful:- they describe the information they refer to Meaningful:- they describe the information they refer to E.g. Height, Count, BloodPressure, CarSpeedE.g. Height, Count, BloodPressure, CarSpeed Terse:- They are only as long as necessary to convey meaning. Terse:- They are only as long as necessary to convey meaning.

81 Reserved Words Identifiers CANNOT be a reserved word.Identifiers CANNOT be a reserved word. Reserved words are built in words that have special meanings in the language.Reserved words are built in words that have special meanings in the language. They must be used only for their specified purpose. Using them for any other purpose will result in a error.They must be used only for their specified purpose. Using them for any other purpose will result in a error. e.g. doifswitch whileelsereturne.g. doifswitch whileelsereturn *

82 Reserved Words C++ is case sensitive. ALL reserved words are lower case C++ is case sensitive. ALL reserved words are lower case WHILE Whilewhile Are all different identifiers only the last is a reserved word

83 Operators All the data types we have seen (int, float, double, char and string) have a set of operators that can be applied to them All the data types we have seen (int, float, double, char and string) have a set of operators that can be applied to them E.g. Numerical data uses the familiar + - / for add subtract and divide. E.g. Numerical data uses the familiar + - / for add subtract and divide. The asterisk * is used for multiplication The asterisk * is used for multiplication These work in the usual manner These work in the usual manner

84 string operators arithmetic is not meaningful when applied to strings arithmetic is not meaningful when applied to strings You do not multiply first names! You do not multiply first names! strings operators do other things strings operators do other things E.g. The + operator applied to strings joins them (concatenates) together E.g. The + operator applied to strings joins them (concatenates) together We will see other operations we want to do with strings; like searching a string for a substring or comparing strings. We will see other operations we want to do with strings; like searching a string for a substring or comparing strings.

85 Expressions A VALID arrangement of variables, constants, literals and operators Expressions are evaluated and compute a VALUE of a given type E.g. Expression 9 + 4 computes to 13

86 A special OPERATOR The assignment operator = Causes much confusion! IT DOES NOT WORK LIKE EQUALS IN MATHS

87 variable = expression number = 4; result = 10 * number; 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

88 Using assignments to get information into the computer int myage; string myname; double mysalary; myage = 21; myname = “Vas”; mysalary = 1000.00;

89 Interactive input formally covered later using cin and cout using cin and cout using data files using data files

90 Programming in C++ Lecture 2b Types, Operators, Expressions

91 Overview Types Types Binary arithmeticBinary arithmetic Operators Operators Arithmetic, logical, assignmentArithmetic, logical, assignment Expressions/Statements Expressions/Statements DeclarationsDeclarations AssignmentsAssignments Other one-line operationsOther one-line operations More program examples More program examples

92 Types “Type” in C++ refers to the kind of data or information that is to be stored in the variable “Type” in C++ refers to the kind of data or information that is to be stored in the variable A variable is a quantity that can be changed during a program A variable is a quantity that can be changed during a program Functions have return types, i.e. can return expressions to the calling function Functions have return types, i.e. can return expressions to the calling function Arguments to functions each have their own type (these are passed to the function) Arguments to functions each have their own type (these are passed to the function) Variables have types Variables have types

93 Why Type? Why do we have to specify types of variables, functions, arguments? Why do we have to specify types of variables, functions, arguments? Has to do with computer memory Has to do with computer memory Different kinds of data require different amounts of memory to store Different kinds of data require different amounts of memory to store A single character can have only one of 128 values (a-z,A-Z,0-9,punctuation, some others)A single character can have only one of 128 values (a-z,A-Z,0-9,punctuation, some others) An integer (in the mathematical sense) can have an infinite number of values, on a computer however this is limited to ~65,000 values, depends on how many bits are usedAn integer (in the mathematical sense) can have an infinite number of values, on a computer however this is limited to ~65,000 values, depends on how many bits are used Therefore, more memory is needed to store an integer than a characterTherefore, more memory is needed to store an integer than a character

94 Computer Memory Memory in computers is made up of transistors Memory in computers is made up of transistors Transistor: just a switch that can be either on or off, easier to have just two electrical states rather that 10 (i.e. to represent 0- 9) Transistor: just a switch that can be either on or off, easier to have just two electrical states rather that 10 (i.e. to represent 0- 9) “on” state corresponds to the value 1, “off” state corresponds to the value 0 “on” state corresponds to the value 1, “off” state corresponds to the value 0 Everything in memory has to be made up of 0s and 1s – i.e., has to be stored as a number in base 2 (binary) Everything in memory has to be made up of 0s and 1s – i.e., has to be stored as a number in base 2 (binary) Important to understand different bases Important to understand different bases

95 Reminder:Converting Between Bases To convert numbers in some other base into base 10 (decimal) values: To convert numbers in some other base into base 10 (decimal) values: For each position, starting with position 0, the least significant digit (rightmost), take the digit in that position and multiply it by the base raised to the power of that position; add the values togetherFor each position, starting with position 0, the least significant digit (rightmost), take the digit in that position and multiply it by the base raised to the power of that position; add the values together 10 in base 2 = 1x2 1 + 0x2 0 = 2+0 = 210 in base 2 = 1x2 1 + 0x2 0 = 2+0 = 2 100101 in base 2 = 1x2 5 + 1x2 2 + 1x2 0 = 32 + 4 + 1 = 37100101 in base 2 = 1x2 5 + 1x2 2 + 1x2 0 = 32 + 4 + 1 = 37

96 Converting Between Bases Hexadecimal (base 16) uses the digits 0-9 + A-E (A=10, B=11,…E=15) and prefix 0x to differentiate from decimal //a zero 0 not an o Hexadecimal (base 16) uses the digits 0-9 + A-E (A=10, B=11,…E=15) and prefix 0x to differentiate from decimal //a zero 0 not an o To convert binary to hexadecimal, group binary digits in groups of 4, convert each group of 4 into decimal, and use the appropriate hex digit for that group of 4 To convert binary to hexadecimal, group binary digits in groups of 4, convert each group of 4 into decimal, and use the appropriate hex digit for that group of 4 100101 in base 2 = 0010 0101 first hex digit = 0010 or 2 second hex digit = 0101 or 5 0x25 = 2x16 1 + 5x16 0 = 32 + 5 = 37 100101 in base 2 = 0010 0101 first hex digit = 0010 or 2 second hex digit = 0101 or 5 0x25 = 2x16 1 + 5x16 0 = 32 + 5 = 37 See OctalandHex.cpp See OctalandHex.cpp

97 Converting Between Bases Octal (base 8) numbers prefixed with 0 (zero) Octal (base 8) numbers prefixed with 0 (zero) 052 in base 8 = 5x8 1 + 2x8 0 = 40+ 2 = 42 052 in base 8 = 5x8 1 + 2x8 0 = 40+ 2 = 42 Octal conversion to binary: same as hex, but group digits into groups of 3 Octal conversion to binary: same as hex, but group digits into groups of 3 100101 in base 2 = 100 101 first octal digit = 100 or 4 second octal digit = 101 or 5 045 = 4x8 1 + 5x8 0 = 32 + 5 = 37 100101 in base 2 = 100 101 first octal digit = 100 or 4 second octal digit = 101 or 5 045 = 4x8 1 + 5x8 0 = 32 + 5 = 37 See OctalandHex.cpp See OctalandHex.cpp

98 Common Bases Binary, octal (base 8), hexadecimal (base 16) all common bases in programming Binary, octal (base 8), hexadecimal (base 16) all common bases in programming Useful because powers of 2 and easy to convert between Useful because powers of 2 and easy to convert between Computer memory almost always in powers of 2 Computer memory almost always in powers of 2

99 Back to Types Types typically defined in pieces of memory that are powers of 2 Types typically defined in pieces of memory that are powers 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 nibble 8 bits = 1 byte, 4 bits is a nibble 1 byte can have any value between 0000 0000 and 1111 1111 – i.e., between 0 – 255.1 byte can have any value between 0000 0000 and 1111 1111 – i.e., between 0 – 255. 1111 1111 binary hex digit: 1111 = 8+4+2+1 = 15 = E 0xEE = 15x16 1 + 15x16 0 = 240 + 15 = 2551111 1111 binary hex digit: 1111 = 8+4+2+1 = 15 = E 0xEE = 15x16 1 + 15x16 0 = 240 + 15 = 255 More than number of values needed for characters – 1 byte typically used for character typeMore than number of values needed for characters – 1 byte typically used for character type

100 Numeric Types 16 bits = 2 bytes can have any value from 0000 0000 0000 0000– 1111 1111 1111 1111 or 0 – 65,535. (Shortcut: 65,535 = 2 16 -1) 16 bits = 2 bytes can have any value from 0000 0000 0000 0000– 1111 1111 1111 1111 or 0 – 65,535. (Shortcut: 65,535 = 2 16 -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 up to +/- 32,768 (approx) why?If used to store negative integers, could only store up to +/- 32,768 (approx) why? 32-bit integers now more common 32-bit integers now more common Ever heard of 32-bit operating system? Means that main data types used are 32-bitEver heard of 32-bit operating system? Means that main data types used are 32-bit Amount of memory given to each type dependent on the machine and operating system Amount of memory given to each type dependent on the machine and operating system

101 Type Sizes Many different types in C++ (more to come) Many different types in C++ (more to come) char: a single characterchar: a single character Often 1 byte, 128 values Often 1 byte, 128 values int: an integer valueint: an integer value Often 32 bits/4 bytes, 4 billion values Often 32 bits/4 bytes, 4 billion values float: a floating-point numberfloat: a floating-point number Often 4 bytes Often 4 bytes double: a double-precision floating-point numberdouble: a double-precision floating-point number Double the size of a float, often 64 bits or 8 bytes Double the size of a float, often 64 bits or 8 bytes

102 Operators Arithmetic: + - * / % -(unary e.g. - (x+y)) Arithmetic: + - * / % -(unary e.g. - (x+y)) Increment/decrement: ++ -- Increment/decrement: ++ -- Relational: > >= >= < <= Equality: == != Equality: == != Assignment: = += -= *= Assignment: = += -= *= Logical: || && Logical: || && Reference/Dereference: & * -- for later Reference/Dereference: & * -- for later

103 Expressions Built up out of constant values (e.g., 5 or 10.7), variables (x, y, etc) and operators Built up out of constant values (e.g., 5 or 10.7), variables (x, y, etc) and operators Number and type of variables has to match what the operator expects – like a function Number and type of variables has to match what the operator expects – like a function Some exceptions when working with numerical variables! Some exceptions when working with numerical variables!

104 Type conversions (coercion) Some types can automatically be converted to others Some types can automatically be converted to others int, float, double can often be treated the same for calculation purposes int, float, double can often be treated the same for calculation purposes int values will be converted up into floats for calculations.int values will be converted up into floats for calculations. But major differences between integer and floating-point arithmetic! But major differences between integer and 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

105 Expression Examples See/code examplesin.cpp See/code examplesin.cpp Many examples follow Many examples follow x, y, z are integer variables x, y, z are integer variables f and d are float variables f and d are float variables

106 Arithmetic y = 5;// y is now 5 x = y + 3; // x is now 8 f = 2 * 4; // f is now 8.0 g = f / 3.0; // g is now 2.6…67 y = x / 3; // y is now 2 z = x % 3; // z is now 2 See ExamplesinCpp.cpp

107 Increment/Decrement x = 5; f = 2.5; x++; // x is now 6 f--;// f is now 1.5 ++f;// f is now 2.5 --x;// x is now 5 y = ++x – 2; // x = 6, y = 2 g = f-- + 2; // f = 1.5, g = 4.5! //see ExamplesinCpp2.cpp

108 Relational x = 5; f = 6.0; y = (x > f); // y = 0 (false) g = (x <= f); // g = 1 (true) // usually used in conditionals if (x > f) { // do something } See conditional1.cpp

109 Relational conditions:Common errors if (x = 5); if ((x=5)&&(y=7)) if ((x>0)&&(x 0)&&(x<=)) Must use if (x==4) Or if (y!=10)

110 Equality & Assignment x = 5; // sets value of x to 5 if (x == 5) // returns true/false { x += 3; // x is now 8 if (x != 5) { cout << “x is not 5\n”; } x *= 2; // x is now 16 See conditional2.cpp

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

112 Programming in C++ Lecture 2c Elements of a Program

113 Overview of Lecture Overview of Computers & Programming Overview 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 programmingProcedural programming vs. Object-oriented programming Elements of a Program Elements of a Program StatementsStatements FunctionsFunctions VariablesVariables Types Types Computer memory & binary arithmeticComputer memory & binary arithmetic C++ typesC++ types

114 What Is A Computer? CPU/processor just does a few basic things: CPU/processor just does a few basic things: Arithmetic unit (adds, subtracts, multiplies, divides), sometimes called the ALU the Arithmetic and Logic UnitArithmetic unit (adds, subtracts, multiplies, divides), sometimes called the ALU the Arithmetic and Logic Unit Memory control (loads and stores integer and floating-point values from memory)Memory control (loads and stores integer and floating-point values from memory) Think of address and data buses etcThink of address and data buses etc Everything a computer does is accomplished with these simple operations Everything a computer does is accomplished with these simple operations

115 Assembly Language Computer processors each have their own built-in assembly language, this is code that the CPU understands Computer processors each have their own built-in assembly language, this is code that the CPU understands E.g., Intel CPUs have their own language that differs from the language of Motorola Power PC CPUsE.g., Intel CPUs have their own language that differs from the language of Motorola Power PC CPUs These have a limited range of commands, LOAD, ADD, SUB, MOV etc These have a limited range of commands, LOAD, ADD, SUB, MOV etc Each command typically does very little Each command typically does very little Arithmetic commands, load/store from memoryArithmetic commands, load/store from memory Code not totally unreadable, but close, fortunately we do not generally write in assembly language any more, but it is good to know about it. Code not totally unreadable, but close, fortunately we do not generally write in assembly language any more, but it is good to know about it.

116 C++ versus Assembly Here is some simple C++ code: Here is some simple C++ code: assume x, y and z have been defined assume x, y and z have been defined as integers || means the logical or operator || means the logical or operator x = y + 2; if ( (x > 0) || ( (y-x) 0) || ( (y-x) <= z) ) x = y + z; We will also see three similar lines of code in Intel x86 assembly language in a moment... We will also see three similar lines of code in Intel x86 assembly language in a moment...

117 Truth table for Logical or AB A || B FalseFalseFalse TrueFalseTrue FalseTrueTrue TrueTrueTrue

118 Truth table for Logical or continued The predicate A is: It is Tuesday The predicate B is: It is raining A || B FalseFalseFalse TrueFalseTrue FalseTrueTrue TrueTrueTrue

119 Truth table for And (&&) AB A && B FalseFalseFalse TrueFalseFalse FalseTrueFalse TrueTruetrue

120 MOV AX, y // put y into AX MOV BX, x // put x into BX MOV CX, z // put z into CX ADD 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

121 The C++ Programming Language C++ is a higher-level language compared to assembly language. C++ is a higher-level 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 others (like C++ and Java which are Object Oriented Programming languages), C has no OO capabilities. C is a lower-level language compared to others (like C++ and Java which are Object Oriented Programming languages), C has no OO capabilities. Direct control over memory allocation and cleanup (as we will see)Direct control over memory allocation and cleanup (as we will see)

122 Compiled vs. Interpreted For a program to run, the source code must be translated into the assembly language of the machine the program will run on. For a program to run, the source code must be translated into the assembly language of the machine the program will run on. Compiled language: the source code is translated once and the executable form is run. (C++ and Pascal)Compiled language: the source code is translated once and the executable form is run. (C++ and Pascal) Interpreted language: an interpreter runs each time the program is started, and it does the translation on-the-fly (Visual Basic, Perl, other scripting languages and Java).Interpreted language: an interpreter runs each time the program is started, and it does the translation on-the-fly (Visual Basic, Perl, other 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

123 Procedural vs. Object-Oriented Procedural Programming Procedural Programming A program viewed as a series of instructions to the computerA program viewed as a series of instructions to the computer Instructions are organized into functions and libraries of functionsInstructions are organized into functions and libraries of functions Object-Oriented Programming Object-Oriented Programming A program viewed as a set of objects that interact with each otherA program viewed as a set of objects that interact with each other An object encapsulates (hides and binds) functions with the data that the object’s functions operate onAn object encapsulates (hides and binds) functions with the data that the object’s functions operate on

124 Procedural vs. Object-Oriented OOP good for complex systems – nice to break down into small independent objects OOP good for complex systems – nice to break down into small independent objects Procedural perhaps a bit more intuitive, especially for beginners (where we will commence) Procedural perhaps a bit more intuitive, especially for beginners (where we will commence) C is a procedural language, no OO capabilities C is a procedural language, no OO capabilities Java and C++ are Object-Oriented Languages, Java is pure Object Oriented i.e. everything is an object in Java. Java and C++ are Object-Oriented Languages, Java is pure Object Oriented i.e. everything is an object in Java.

125 Explanation of OOP and Procedural Programming Perhaps one of the best definitions of the difference between these two paradigms is as follows: Perhaps one of the best definitions of the difference between these two paradigms is as follows: Consider a chair: a procedural programmer is interested in in the wood, hammer, screws, screw driver etc i.e., everything that went into making the chair, however the Object Oriented Programmer would be interested only in the chair i.e. the finished article Consider a chair: a procedural programmer is interested in in the wood, hammer, screws, screw driver etc i.e., everything that went into making the chair, however the Object Oriented Programmer would be interested only in the chair i.e. the finished article

126 Procedural Programming Program is a set of sequential steps to be executed by the computer, one after another, this is the Sequential Paradigm Program is a set of sequential steps to be executed by the computer, one after another, this is the Sequential Paradigm However we do Not necessarily run the same steps every time the program runs, can have selection/decisions However we do Not necessarily run the same steps every time the program runs, can have selection/decisions May want to skip steps under certain conditions (selection)May want to skip steps under certain conditions (selection) May want to repeat steps under certain conditions (iteration)May want to repeat steps under certain conditions (iteration) May need to save some information to use later in the program (when computing a sum)May need to save some information to use later in the program (when computing a sum)

127 Programming Paradigms There are three essential programming paradigms (the word paradigm is from the Greek word meaning example) There are three essential programming paradigms (the word paradigm is from the Greek word meaning example) Sequential: code is executed one after the after top-down:Sequential Paradigm Sequential: code is executed one after the after top-down:Sequential Paradigm Selection/decisions. Achieved in C/C++ using the if, if-else or switch-case statements to be met in later lectures. Selection/decisions. Achieved in C/C++ using the if, if-else or switch-case statements to be met in later lectures. Iteration:To be achieved in the C++/Java languages using the for loop, while loop or the do-while loop, more in later lectures Iteration:To be achieved in the C++/Java languages using the for loop, while loop or the do-while loop, more in later lectures

128 Elements of a Program Individual steps/commands to the computer Individual steps/commands to the computer These are called Statements, a semicolon delimits a valid C++ statement.These are called Statements, a semicolon delimits a valid C++ statement. Technique to organize code so it is easy to debug, fix, and maintain. Code and fix is the most common way that one programs, but perhaps the worst, SSADM is a better way. SSADM: Structured, System Analysis and Design Methodology Technique to organize code so it is easy to debug, fix, and maintain. Code and fix is the most common way that one programs, but perhaps the worst, SSADM is a better way. SSADM: Structured, System Analysis and Design Methodology FunctionsFunctions Way to save information that may change each time the program runs Way to save information that may change each time the program runs Variables vary in a programVariables 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

129 Code and Fix Write some code Write some code Fix problems just created Fix problems just created ProblemsProblems Software complete after n fixesSoftware complete after n fixes Subsequent fixes are very expensive (time and resources)Subsequent fixes are very expensive (time and resources) Previous fixes fail to workPrevious fixes fail to work Poor fit to users’ needs (reflects programmers view rather that that of the clients)Poor fit to users’ needs (reflects programmers view rather that that of the clients)

130 Design Installation Operation and Maintenance Analysis and Specification Implementation Testing Developing software: The traditional approach

131 The 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 difficult to fixDesign and code produce inconsistencies that are difficult 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 completionSystem performance can not be tested until near completion 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)

132 Initial Planning Final Product Analysis Testing and Quality Assurance Reviewing Prototypes Building Prototypes Developing software: the modern approach (RAD)

133 Functions Already have seen the main() function Already have seen the main() function Functions are used to group individual statements that together accomplish a single larger task Functions are used to group individual statements that together accomplish a single larger task E.g., the main() function contains many statements that together accomplish the task of printing a message to the screen or file E.g., the main() function contains many statements that together accomplish the task of printing a message to the screen or file

134 Simple Example #include #include using namespace std; void printHello() {cout<< “Hello\n”}; void printBye() {cout<<“Bye\n”}; int main() { printHello(); // this is a call to the // function printHello() printBye(); // this is a call to the // function prinBye // function prinBye return 0; } See program fuctions1.cpp See program fuctions1b.cpp (//does not compile) as //there are no function prototypes

135 Function Elements Return-type Return-type Specifies what kind of information the function will returnSpecifies what kind of information the function will return void means nothing is returned (called a procedure in other languages)void means nothing is returned (called a procedure in other languages) Name Name 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 statements to be executedIt is used to call (invoke) the function – i.e., to cause the function statements to be executed Arguments Arguments Optional information that is used by the functionOptional information that is used by the function Body Body The actual statements within the function groupsThe actual statements within the function groups

136 Variables Used to store information within the program Used to store information within the program Values can change as the program runs (i.e., are variable) Values can change as the program runs (i.e., are variable) Obtained through calculationsObtained through calculations From inputFrom input From function resultsFrom function results

137 Simple Examples #include #include using namespace std; int main() { int x = 5;//obsolete here as not used char letter = ‘g’; cout <<“Please enter a character”; cin >> letter; cout << “the character input was “ << letter << endl; return 0; } //see letter.cpp

138 Variable Elements Type Type Indicates what kind of information can be stored in the variableIndicates what kind of information can be stored in the variable Name Name Must be unique within a given functionMust be unique within a given function Except for special global variables, which must have unique names within the program. Global variables are not considered good programming practice. Why? Except for special global variables, which must have unique names within the program. Global variables are not considered good programming practice. Why? Used to refer to a variable throughout the functionUsed to refer to a variable throughout the function Value Value Can be set in many different waysCan be set in many different ways

139 Declarations vs. Definitions Both functions and variables MUST be declared before they can be used Both functions and variables MUST be declared before they can be used Declaration includes just: Declaration includes just: Type Type Name Name Arguments (for functions) Arguments (for functions) Definition can come later! Definition can come later! For variables: value can be assigned later (as long as it is before its first use or garbage will be used)For variables: value can be assigned later (as long as it is before its first use or garbage will be used) For functions: body of function can be added laterFor functions: body of function can be added later

140 Complex Example See the functions1.cpp, function2.cpp and function3.cpp example code See the functions1.cpp, function2.cpp and function3.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 definition Function definition void printHello() { cout << “Hello”<< endl; }void printHello() { cout << “Hello”<< endl; }

141 Important Rules All variables and functions must be declared in the function/file where they are going to be used BEFORE they are used. All variables and functions must be declared in the function/file where they are going to be used BEFORE they are used. All variables must be initialized to some starting value before being used in calculations or being printed out, otherwise we get rubbish All variables must be initialized to some starting value before being used in calculations or being printed out, otherwise we get rubbish

142 Statements A statement is a single line of code A statement is a single line of code Can be: Can be: Variable or function declarationsVariable or function declarations Arithmetic operationsArithmetic 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…

143 Types “Type” in C++ refers to the kind of data or information “Type” in C++ refers to the kind of data or information Functions have return types Functions have return types Arguments to functions each have their own type Arguments to functions each have their own type Variables have types Variables have types

144 Why Type? Why do we have to specify types of variables, functions, arguments? Why do we have to specify types of variables, functions, arguments? Has to do with computer memory Has to do with computer memory Different kinds of data require different amounts of memory to store Different kinds of data require different amounts of memory to store A single character can have only one of 128 values (a-z,A-Z,0-9,punctuation, some others)A single character can have only one of 128 values (a-z,A-Z,0-9,punctuation, some others) An integer in mathematics can have an infinite number of values, limited to ~65,000 values on a computerAn integer in mathematics can have an infinite number of values, limited to ~65,000 values on a computer Therefore, more memory needed to store an integer than a characterTherefore, more memory needed to store an integer than a character

145 Computer Memory Memory in computers made up of transistors Memory in computers made up of transistors Transistor: just a switch that can be either on or off Transistor: just a switch that can be either on or off “on” state corresponds to the value 1, “off” state corresponds to the value 0 “on” state corresponds to the value 1, “off” state corresponds to the value 0 Everything in memory has to be made up of 0s and 1s – i.e., has to be stored as a number in base 2 (binary) Everything in memory has to be made up of 0s and 1s – i.e., has to be stored as a number in base 2 (binary) Important to understand different bases Important to understand different bases

146 Numeric Types 16 bits = 2 bytes can have any value from 0000 0000 0000 0000–1111 1111 1111 1111 or 0 – 65,535. (Shortcut: 65,535 = 2 16 -1) 16 bits = 2 bytes can have any value from 0000 0000 0000 0000–1111 1111 1111 1111 or 0 – 65,535. (Shortcut: 65,535 = 2 16 -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 up to +/- 32,768 (approx)If used to store negative integers, could only store up to +/- 32,768 (approx) 32-bit integers now more common 32-bit integers now more common Ever heard of 32-bit operating system? Means that main data types used are 32-bitEver heard of 32-bit operating system? Means that main data types used are 32-bit Amount of memory given to each type dependent on the machine and operating system Amount of memory given to each type dependent on the machine and operating system

147 Next Time More on types More on types Operators Operators Arithmetic: + - * /Arithmetic: + - * / Assignment: =Assignment: = Increment/Decrement: ++ --Increment/Decrement: ++ -- Expressions/Statements Expressions/Statements DeclarationsDeclarations AssignmentsAssignments Other one-line operationsOther one-line operations More program examples More program examples

148 Casting int i = 16; int i = 16; double d; double d; d = i; // will give, d = 16.0 d = i; // will give, d = 16.0 d = 10.3; d = 10.3; i = d; // will give i = 10 i = d; // will give i = 10 cout << 2 * 3.4 + 7 / 2; // 6.8 + 3 = 9.8 (a //double), note 7/2 is evaluated as an integer cout << 2 * 3.4 + 7 / 2; // 6.8 + 3 = 9.8 (a //double), note 7/2 is evaluated as an integer //ignoring the remainder. //ignoring the remainder. //see casting.cpp //see casting.cpp

149 Conditional Statements Conditions take the form: Conditions take the form: if (condition) if (condition) {statements executed if the condition is true } {statements executed if the condition is true } else else {statements executed if the condition is false } {statements executed if the condition is false }

150 Conditions Execution resumes here with the “if statement” having been executed. Execution resumes here with the “if statement” having been executed. Note that the first line does not end with a semicolon. Note that the first line does not end with a semicolon. The curly brackets are necessary only if there are several statements. The curly brackets are necessary only if there are several statements. If you are only executing one statement as a result of the condition, you can place it on the same line or the next. If you are only executing one statement as a result of the condition, you can place it on the same line or the next. For example: For example:

151 Conditions See tennis.cpp See tennis.cpp

152 Relational operators. Relational operators allow you to compare two or more items of data in an expression. Relational operators allow you to compare two or more items of data in an 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

153 Relations The mathematical operators can be used with strings to determine alphabetical order. The mathematical operators can be used with strings to determine alphabetical order. For example: ("abc" < "def") ("abc" < "def") this is also true this is also true ("d">"b") ("d">"b")

154 Relations When dealing with non-alphanumeric characters (i.e. numbers and letters), you need to know which character set, or code page, you are using before you can determine the alphabetical order of a set of strings. When dealing with non-alphanumeric characters (i.e. numbers and letters), you need to know which character set, or code page, you are using before you can determine the alphabetical order of a set of strings. The most common code page is the ASCII (American Standard Code for Information Exchange). The EBDIC (Extended Binary Decimal Interchange Code) is used in large IBM mainframes. The most common code page is the ASCII (American Standard Code for Information Exchange). The EBDIC (Extended Binary Decimal Interchange Code) is used in large IBM mainframes. The first 33 characters of the ASCII character set are non-printable control codes (CTRL, carriage return etc). The first 33 characters of the ASCII character set are non-printable control codes (CTRL, carriage return etc).

155 Common pitfall with Boolean expressions. It is easy to write: if (x or y > 0) if (x or y > 0) rather than rather than if (x > 0 or y > 0) // using Borland if (x > 0 or y > 0) // using Borland //C++ //C++ if ((x>0)||(y>0)) if ((x>0)||(y>0))

156 Explanation which are both correct code but logically different. which are both correct code but logically different. The first expression literally means "if x is true or y is greater than zero", and x is always true for non- zero values of x. The first expression literally means "if x is true or y is greater than zero", and x is always true for non- zero values of x.

157 Lazy evaluation. C++ compilers implement so-called lazy evaluation, in which Boolean expressions are evaluated only until their result is clear. C++ compilers implement so-called lazy evaluation, in which Boolean expressions are evaluated only until their result is clear. For example, false and anything is always false, true or anything is always true. For example, false and anything is always false, true or anything is always true. This is a useful technique when you want to avoid making calculations that might cause a crash. For example: This is a useful technique when you want to avoid making calculations that might cause a crash. For example:

158 Lazy evaluation if (second > 0 && first/second > 1.2) // eliminate the possibility of dividing by //zero if (second > 0 && first/second > 1.2) // eliminate the possibility of dividing by //zero {... {... } }

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

160 Boolean variables. Some conditions are used several times in the course of a calculation, for example, whether an individual is entitled to a discount. Some conditions are used several times in the course of a calculation, for example, whether an individual is entitled to a discount. Rather than re-evaluating the condition you can store it in the form of a Boolean variable. Hence: Rather than re-evaluating the condition you can store it in the form of a Boolean variable. Hence: bool half_price = day = = "Monday" !! age = "w"; bool half_price = day = = "Monday" !! age = "w";

161 Conditional operator, ? (the operator is the ?) It is possible to abbreviate some condition statements using the ? operator as follows: It is possible to abbreviate some condition statements using the ? operator as follows: conditional_expression ? expression_1 : expression_2 conditional_expression ? expression_1 : expression_2

162 Conditional operator in which, if conditional_expression is true, expression_1 is performed, otherwise expression_2 is carried out. in which, if conditional_expression is true, expression_1 is performed, otherwise expression_2 is carried out. Note that the expressions must be of the same type. Note that the expressions must be of the same type. You can use the conditional operator in a straightforward assignment, or within a more complex statement: You can use the conditional operator in a straightforward assignment, or within a more complex statement:

163 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 : t); // prints the shorter of s and t cout << (s.length() < t.length() ? s : t); // prints the shorter of s and t

164 The switch statement. (case statement of Pascal) This switch statement allows you to control the flow of your program by specifying a number of different cases or conditions, rather than simply true or false. This switch statement allows you to control the flow of your program by specifying a number of different cases or conditions, rather than simply true or false. See switch1.cpp See switch1.cpp

165 Switch The switch keyword works by entering program flow at the statement whose case matches the expression. All subsequent statements are executed as well, so that if expression were 3 in this example, the output would be 363invalid value. This has been obtained by entering the code at the line The switch keyword works by entering program flow at the statement whose case matches the expression. All subsequent statements are executed as well, so that if expression were 3 in this example, the output would be 363invalid value. This has been obtained by entering the code at the line case 3: cout << x * 3; // then multiplying 12 (i.e. x) by 3 giving the 36, case 3: cout << x * 3; // then multiplying 12 (i.e. x) by 3 giving 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 Output then proceeding to the final line and outputting the string Invalid Output You can avoid this state of affairs by placing a break keyword at the end of each case statement, to go to the statement after the curly brackets. switch statements are of limited use: expression must always evaluate to a literal and you can have only one value per case. You can avoid this state of affairs by placing a break keyword at the end of each case statement, to go to the statement after the curly brackets. switch statements are of limited use: expression must always evaluate to a literal and you can have only one value per case.


Download ppt "Topics this week Computer Programming Computer Programming Programming Life-Cycle Phases Programming Life-Cycle Phases Creating an Algorithm Creating an."

Similar presentations


Ads by Google