chapter 8

45
Chapter 8 Chapter 8 Introduction to Introduction to High-Level Language High-Level Language Programming Programming

Upload: vanna

Post on 06-Jan-2016

25 views

Category:

Documents


1 download

DESCRIPTION

Chapter 8. Introduction to High-Level Language Programming. Objectives. In this chapter, you will learn about Where do we stand? High-level languages Introduction to C++ Virtual data storage Statement types Putting the pieces together. Objectives Postponed (Covered in CS23021). - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 8

Chapter 8Chapter 8

Introduction to High-Level Introduction to High-Level Language ProgrammingLanguage Programming

Page 2: Chapter 8

ObjectivesObjectivesIn this chapter, you will learn aboutIn this chapter, you will learn about

Where do we stand?Where do we stand?

High-level languagesHigh-level languages

Introduction to C++Introduction to C++

Virtual data storageVirtual data storage

Statement typesStatement types

Putting the pieces togetherPutting the pieces together

Page 3: Chapter 8

Objectives PostponedObjectives Postponed(Covered in CS23021) (Covered in CS23021)

FunctionsFunctions

Managing complexityManaging complexity

Object-oriented programmingObject-oriented programming

Graphical programmingGraphical programming

The big picture: Software engineeringThe big picture: Software engineering

Page 4: Chapter 8

Where Do We Stand?Where Do We Stand? Early days of computingEarly days of computing

Programmers used assembly languageProgrammers used assembly language

• Programs written by technically oriented peoplePrograms written by technically oriented people

Assembler programs Assembler programs

• Were machine specific Were machine specific

• Required programmers take a microscopic view of a taskRequired programmers take a microscopic view of a task

Later decadesLater decades

Programmers demanded a more comfortable programming Programmers demanded a more comfortable programming environmentenvironment

• Programs could be written by “nontechie” peoplePrograms could be written by “nontechie” people

• Programs could be portable rather than machine specificPrograms could be portable rather than machine specific

• Programmers could avoid data storage and movement issuesProgrammers could avoid data storage and movement issues

Page 5: Chapter 8

High-level LanguagesHigh-level Languages

High-level programming languagesHigh-level programming languages Called third-generation languagesCalled third-generation languages

• Machine language was “first generation”Machine language was “first generation”• Assembly language was “second generation”Assembly language was “second generation”

Overcame deficiencies of assembly languageOvercame deficiencies of assembly language

Programmer didn’t need to manage details of Programmer didn’t need to manage details of data storage or movementdata storage or movement

Page 6: Chapter 8

High-level Languages High-level Languages (continued)(continued)

Expectations of a high-level language Expectations of a high-level language program (continued)program (continued)

Programmer can take a macroscopic view of Programmer can take a macroscopic view of tasks; “primitive operations” can be largertasks; “primitive operations” can be larger

Program will be portableProgram will be portable

Code will be closer to standard English and Code will be closer to standard English and use standard mathematical notationuse standard mathematical notation

Page 7: Chapter 8

Figure 8.1Figure 8.1

Transitions of a High-level Language ProgramTransitions of a High-level Language Program

Page 8: Chapter 8

Introduction to C++Introduction to C++ Some components of program on next slideSome components of program on next slide

CommentsComments• Anything following “//” on a line is a commentAnything following “//” on a line is a comment• Give information to human readers of codeGive information to human readers of code

The “include” directiveThe “include” directive• The linker includes object code from a libraryThe linker includes object code from a library• C++ does not provide input or output of data (I/O)C++ does not provide input or output of data (I/O)

The “using” directiveThe “using” directive• Tells compiler to look in a namespace for Tells compiler to look in a namespace for

definitions not mentioned in the programdefinitions not mentioned in the program• Used here for I/O commands “cin” & “cout” Used here for I/O commands “cin” & “cout”

Main program code in brackets after “main”Main program code in brackets after “main”

Page 9: Chapter 8

A Simple C++ ProgramA Simple C++ Program

Figure 8.2Figure 8.2

Page 10: Chapter 8

Figure 8.3Figure 8.3

The Overall Form of a Typical C++ ProgramThe Overall Form of a Typical C++ Program

Page 11: Chapter 8

Data TypesData Types Identifiers: Names in a programming Identifiers: Names in a programming

languagelanguage Any combination of letters, digits, and underscore Any combination of letters, digits, and underscore

symbol that does not start with a digit.symbol that does not start with a digit. Should select names suggestive of meaningShould select names suggestive of meaning

Keywords: Have special meanings in C++Keywords: Have special meanings in C++ Also called reserved words.Also called reserved words. Can not be used as an identifierCan not be used as an identifier

C++ is a case-sensitive, free-format languageC++ is a case-sensitive, free-format language

Data items can be constants or variablesData items can be constants or variables

Page 12: Chapter 8

Data Types (continued)Data Types (continued)

A declaration of a data item tellsA declaration of a data item tells

Whether the item is a constant or a variableWhether the item is a constant or a variable

The identifier used to name the itemThe identifier used to name the item

The data type of the itemThe data type of the item

Page 13: Chapter 8

Figure 8.5Figure 8.5

Some of the C++ Standard Data TypesSome of the C++ Standard Data Types

Page 14: Chapter 8

Data Types (continued)Data Types (continued) An arrayAn array

Groups together a collection of memory Groups together a collection of memory locations, all storing data of the same typelocations, all storing data of the same type

ExampleExampleInt Hits[12]Int Hits[12]

Figure 8.6Figure 8.6

A 12-Element Array HitsA 12-Element Array Hits

Page 15: Chapter 8

Statement TypesStatement Types

Input/output statementsInput/output statements

Input statementInput statement

• Collects a specific value from the user for a Collects a specific value from the user for a variable within the programvariable within the program

Output statementOutput statement

• Writes a message or the value of a program Writes a message or the value of a program variable to the user’s screen or to a filevariable to the user’s screen or to a file

Page 16: Chapter 8

Statement Types (continued)Statement Types (continued)

Assignment statementAssignment statement

Assigns a value to a program variableAssigns a value to a program variable

Control statementControl statement

Directs the flow of control Directs the flow of control

• Can cause it to deviate from usual sequential flowCan cause it to deviate from usual sequential flow

Page 17: Chapter 8

Input/Output StatementsInput/Output Statements

ExampleExample PseudocodePseudocode

Get value for Radius (interactively from keyboard)Get value for Radius (interactively from keyboard) C++C++

cin >> Radius;cin >> Radius;

cin: Input streamcin: Input stream Code for extraction operator (>>) and the Code for extraction operator (>>) and the

definition of the cin stream come from the definition of the cin stream come from the iostream library and std namespaceiostream library and std namespace

Page 18: Chapter 8

Input/Output Statements Input/Output Statements (continued)(continued)

ExampleExample Pseudocode Pseudocode

Print the value of Circumference (on screen)Print the value of Circumference (on screen) C++ C++

cout << Circumference;cout << Circumference;

cout: Output streamcout: Output stream Code for the insertion operator (<<) and the Code for the insertion operator (<<) and the

definition of the cout stream come from the definition of the cout stream come from the iostream library and std namespaceiostream library and std namespace

Page 19: Chapter 8

Input/Output (cont.)Input/Output (cont.) Consider real numbers such as 84.8232Consider real numbers such as 84.8232

The fixed format output of this number would be The fixed format output of this number would be 84.823284.8232

In scientific notation, this output would beIn scientific notation, this output would be8.48232e+0018.48232e+001

The computer is free to choose the output style.The computer is free to choose the output style. To specify fixed format output, include the following To specify fixed format output, include the following

formatting statement in the programformatting statement in the programcout.setf(ios::fixed);cout.setf(ios::fixed);

To require the output be in scientific notation, useTo require the output be in scientific notation, usecout.setf(ios::scientific);cout.setf(ios::scientific);

To require two decimal places, useTo require two decimal places, usecout.precision(2)cout.precision(2)

Page 20: Chapter 8

Output using literal stringsOutput using literal strings Suppose we want to output message before the Suppose we want to output message before the

value, such asvalue, such asThe circumference that corresponds to thisThe circumference that corresponds to this

radius is 84.8234radius is 84.8234

This could be accomplished usingThis could be accomplished usingcout << “The concumference that corresponds “cout << “The concumference that corresponds “

<< “to this radius is “ << Circumference<< “to this radius is “ << Circumference

Many other output features are availableMany other output features are available Some additional information is given in textbookSome additional information is given in textbook We won’t cover the output options in detail here.We won’t cover the output options in detail here.

Page 21: Chapter 8

The Assignment StatementThe Assignment Statement

General formGeneral form PseudocodePseudocode

Set the value of “variable” to “arithmetic Set the value of “variable” to “arithmetic expression”expression”

C++ assignment statement evaluationC++ assignment statement evaluationvariable = expression;variable = expression;

1.1. Expression on the right is evaluatedExpression on the right is evaluated2.2. The result is written into the memory location The result is written into the memory location

specified on the leftspecified on the left Example: Consider assemby code forExample: Consider assemby code for

A= B + C - 3;A= B + C - 3;

Page 22: Chapter 8

Assignment Statements (cont.)Assignment Statements (cont.) The C++ symbols for four basic operationsThe C++ symbols for four basic operations

+ Addition+ Addition- Subtraction- Subtraction* Multiplication* Multiplication/ Division/ Division

Example: The product of A & B is A*B.Example: The product of A & B is A*B. Data Type Considerations:Data Type Considerations:

If A and B are integers, then A/B is the integer If A and B are integers, then A/B is the integer obtained by truncation: 7/2 is 3obtained by truncation: 7/2 is 3

If either A or B is a real number then A/B is a real If either A or B is a real number then A/B is a real number: 7/2 is 3.5number: 7/2 is 3.5

Other data-type considerations are covered in Other data-type considerations are covered in textbook, and will be used, as needed.textbook, and will be used, as needed.

Page 23: Chapter 8

Control StatementsControl Statements

Types of control mechanismsTypes of control mechanisms SequentialSequential

• Instructions are executed in orderInstructions are executed in order

ConditionalConditional

• Choice of which instructions to execute next Choice of which instructions to execute next depends on some conditiondepends on some condition

LoopingLooping

• Group of instructions may be executed many Group of instructions may be executed many timestimes

Page 24: Chapter 8

Control Statements (continued)Control Statements (continued)

Sequential is the default mode of executionSequential is the default mode of execution

Conditional flow of controlConditional flow of control

Evaluation of a Boolean condition (also called Evaluation of a Boolean condition (also called a Boolean expression)a Boolean expression)

Which programming statement to execute Which programming statement to execute next is based on the value of the Boolean next is based on the value of the Boolean condition (true or false)condition (true or false)

Page 25: Chapter 8

Control Statements (continued)Control Statements (continued)

Conditional flow of control (continued)Conditional flow of control (continued) if-else statementif-else statement

if (Boolean condition)if (Boolean condition)

S1;S1;

elseelse

S2;S2; if variation of the if-else statementif variation of the if-else statement

if (Boolean condition)if (Boolean condition)

S1;S1;

Page 26: Chapter 8

Figure 8.10Figure 8.10

Conditional Flow of Conditional Flow of Control (flowchart)Control (flowchart)

(If-Else)(If-Else)

Page 27: Chapter 8

Figure 8.11Figure 8.11

If-Else with Empty ElseIf-Else with Empty Else

Page 28: Chapter 8

Control Statements (continued)Control Statements (continued)

Looping (iteration)Looping (iteration)

The loop body may be executed repeatedly The loop body may be executed repeatedly based on the value of the Boolean conditionbased on the value of the Boolean condition

while statementwhile statement

while (Boolean condition)while (Boolean condition)

S1;S1;

Page 29: Chapter 8

Figure 8.12Figure 8.12

While LoopWhile Loop

Page 30: Chapter 8

Putting the Pieces TogetherPutting the Pieces Together

At this point, we canAt this point, we can Perform input and outputPerform input and output

Assign values to variablesAssign values to variables

Direct the flow of control using conditional Direct the flow of control using conditional statements or loopingstatements or looping

For a complete program, we need toFor a complete program, we need to Assemble the statements in the correct orderAssemble the statements in the correct order

Fill in the missing piecesFill in the missing pieces

Page 31: Chapter 8

Meeting ExpectationsMeeting Expectations

C++ meets the four expectations for a high-C++ meets the four expectations for a high-level programming languagelevel programming language

ExpectationsExpectations

A programmer need not manage the details of A programmer need not manage the details of the movement of data items within memory, the movement of data items within memory, nor pay any attention to where they are storednor pay any attention to where they are stored

Page 32: Chapter 8

Meeting ExpectationsMeeting Expectations

Expectations (continued)Expectations (continued)

Programmer can take a macroscopic view of Programmer can take a macroscopic view of tasks, thinking at a higher level of problem tasks, thinking at a higher level of problem solvingsolving

Programs written in high-level languages will Programs written in high-level languages will be portable rather than machine-specificbe portable rather than machine-specific

Programming statements in a high-level Programming statements in a high-level language language

• Will be closer to standard EnglishWill be closer to standard English

• Will use standard mathematical notationWill use standard mathematical notation

Page 33: Chapter 8

Pseudocode Language Instructions Pseudocode Language Instructions in C++in C++

(Sections 8.1 – 8.6)(Sections 8.1 – 8.6)

Recall pseudocode language instructionsRecall pseudocode language instructions (pg 58)(pg 58) Computation:Computation:

Set value of “variable” to “arithemetic expression” Set value of “variable” to “arithemetic expression” Input/Output:Input/Output:

Get a value for “variable”Get a value for “variable” Print the value for “variable”Print the value for “variable” Print the message “message”Print the message “message”

Conditional:Conditional: If “a boolean expression” is true thenIf “a boolean expression” is true then

First set of algorithmic operationsFirst set of algorithmic operations

ElseElse Second set of algorithmic operationsSecond set of algorithmic operations

Page 34: Chapter 8

Pseudocode Language InstructionsPseudocode Language Instructions (cont.)(cont.)

Iteration (looping):Iteration (looping): While (a boolean condition is true) doWhile (a boolean condition is true) do

operationoperation

operationoperation

..........

operationoperation

End of LoopEnd of Loop

Page 35: Chapter 8

Computation: Expressions in C++Computation: Expressions in C++

OperatorOperator PrecedencePrecedence AssociativityAssociativity

( )( ) 11 nana

+, - , ++, -- , ! ( unary )+, - , ++, -- , ! ( unary ) 22 L->R (+a, -a, ++a, --a, !a)L->R (+a, -a, ++a, --a, !a)R->L (a++, a--)R->L (a++, a--)

*, /, %*, /, % 33 L->RL->R

+, -+, - 44 L->RL->R

<, >, <=, >=<, >, <=, >= 55 L->RL->R

==, !===, != 66 L->RL->R

&&&& 77 L->RL->R

|||| 88 L->RL->R

== 99 R->LR->L

An expression in C++ is a sequence of operators and operands which adhere to the C++ syntax rules. The operators are grouped according to an order of precedence, and associativity

Page 36: Chapter 8

Computation: Expressions in C++Computation: Expressions in C++

Example 1: a = b + c * d;Example 1: a = b + c * d;

Example 2: a = b + c * d – e;Example 2: a = b + c * d – e;

Example 3: a = (b + c) * (d-e);Example 3: a = (b + c) * (d-e);

Example 4: a = b / c;Example 4: a = b / c;

Example 5: a = b % c;Example 5: a = b % c;

Example 6: a = b = c – d;Example 6: a = b = c – d;

Other: +=, -=, *= , /=, %= ???Other: +=, -=, *= , /=, %= ???

Assume b = 5, c = 3, d = 4, e = 2

Page 37: Chapter 8

Computation (cont.)Computation (cont.)

Consider equation: axConsider equation: ax22 + bx + c = 0 + bx + c = 0 The roots are x = ( –b The roots are x = ( –b sqrt(b sqrt(b22 – 4 – 4ac) ) / 2aac) ) / 2a Using a high level language we could write:Using a high level language we could write:

discrim = b*b – 4*a*c;discrim = b*b – 4*a*c;

root1 = (-b + sqrt(discrim)) / (2*a);root1 = (-b + sqrt(discrim)) / (2*a);

root2 = (-b – sqrt(discrim)) / (2*a);root2 = (-b – sqrt(discrim)) / (2*a);

This closely resembles the way we look at the problemThis closely resembles the way we look at the problemmathematicallymathematically

Page 38: Chapter 8

/*/*circle03.cppcircle03.cpp Gets the radius of a circle, calculatesGets the radius of a circle, calculates

it’s circumference and prints out the resultit’s circumference and prints out the result*/*/

#include <iostream>#include <iostream>using std::cin;using std::cin;using std::cout;using std::cout;

int main() {int main() { const double PI = 3.14159;const double PI = 3.14159; double radius = 0.0, circumference = 0.0;double radius = 0.0, circumference = 0.0;

cout << "Please enter the radius " << '\n';cout << "Please enter the radius " << '\n'; cin >> radius;cin >> radius; circumference = 2 * PI * radius;circumference = 2 * PI * radius;

cout << “The circumference is: “ ;cout << “The circumference is: “ ; cout << circumference << “.\n”;cout << circumference << “.\n”;

return 0;return 0;}}

i/o example #3

cout – prompt user for data

<< (insertion operator)

cin – store data in a variable

>> (extraction operator)

cout – output data entered

Input and Output in C++

Page 39: Chapter 8

Conditional Statements in C++Conditional Statements in C++

Conditional flow of control (continued)Conditional flow of control (continued) if-else statementif-else statement

if (Boolean condition)if (Boolean condition)

S1;S1;

elseelse

S2;S2; if variation of the if-else statementif variation of the if-else statement

if (Boolean condition)if (Boolean condition)

S1;S1;

Page 40: Chapter 8

Figure 8.12Figure 8.12

Conditional Flow of ControlConditional Flow of Control

(If-Else)(If-Else)

Page 41: Chapter 8

Figure 8.13Figure 8.13

If-Else with Empty ElseIf-Else with Empty Else

Page 42: Chapter 8

Iterative Statement in C++Iterative Statement in C++

Looping (iteration)Looping (iteration)

The loop body may be executed repeatedly The loop body may be executed repeatedly based on the value of the Boolean conditionbased on the value of the Boolean condition

while statementwhile statement

while (Boolean condition)while (Boolean condition)

S1;S1;

Page 43: Chapter 8

Figure 8.14Figure 8.14

While LoopWhile Loop

Page 44: Chapter 8

Interative Example in C++Interative Example in C++

Sum = 0; Sum = 0; //initialize Sum//initialize Sum

cout << “Please enter the numbers to add; “;cout << “Please enter the numbers to add; “;

cout << “terminate with a negative number.” << endl;cout << “terminate with a negative number.” << endl;

cin >> Number; cin >> Number; // this will get the first value// this will get the first value

while (Number >= 0)while (Number >= 0)

{ { Sum = Sum + Number;Sum = Sum + Number;

cin >> Number; }cin >> Number; }

cout << “The total is “ << Sum << endl;cout << “The total is “ << Sum << endl;

Page 45: Chapter 8

SummarySummary

In a high-level language, the programmer:In a high-level language, the programmer:

Need not manage storage Need not manage storage

Can think about the problem at a higher levelCan think about the problem at a higher level

Can use more powerful and more natural-Can use more powerful and more natural-language-like program instructionslanguage-like program instructions

Can write a much more portable programCan write a much more portable program