lecture 4: computer languages. a tutorial introduction to c++ cos120 software development using c++...

94
Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

Upload: imogene-pearson

Post on 29-Dec-2015

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

Lecture 4: Computer Languages.A Tutorial Introduction to C++

COS120 Software Development Using C++ AUBG, COS dept

Page 2: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

2

Lecture Contents:

Programming languages (Reminder, may skip); Processing HLL program (Reminder, may skip);

– (Editing, Compiling, Linking, Loading, Running) The C++ Programming Language

– A tutorial introduction.

Page 3: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

3

Programming Languages

Machine Language– “Native tongue” of the computer– Binary 0s and 1s that specify what to do

• 0010 0000 0000 0100• 1000 0000 0000 0101• 0011 0000 0000 0110

High - Level Languages– Resemble human language (C++, C, Pascal)

• cost = price + tax;

Page 4: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

4

Processing a High-Level Language Program

Set of programs used to develop software encapsulated within a software package, IDE

Text editor Compiler Linker Loader Examples: MS Visual Studio, Code::Blocks, g++.

Page 5: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

5

Processing a Program Editor used to enter the source program

– Output saved as a source file (prog.c or prog.cpp) Compiler translates the source program

– Displays syntax errors (not descriptive)– Generates an object program (prog.obj)

Linker combines object file with other object files– Generates an executable program (prog.exe)

Loader loads executable program into RAM Program execution starts Program execution terminates

Page 6: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

6

Process Cycle

Page 7: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

7

Tutorial Introduction to C++

Logical Structure of a program – C++ program consists of – functions and– global variables.

Functions are separate program units and contain statements that specify computing operations to be done.

Variables store values used during computation. Variables are named by the developer. Functions are named by the developer except one that is

always present and named main().

Page 8: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

8

Tutorial Introduction to C++

Program as Top-Down hierarchy of syntax categories:– Program // Program has function(s)– Function(s) // Function has statement(s)– Statement(s) // Statement has expression(s)– Expression(s)// Expression has operator(s) and operand(s)– Operator(s)– Operand(s) – Data

Page 9: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

9

Tutorial Introduction to C++

Program as Bottom-Up hierarchy of syntax categories:– Program– Function(s) // Function(s) are part of a program– Statement(s) // Statement(s) are part of a function – Expression(s)// Expression(s) are part of a statement – Operator(s) // Operator(s) are part of an expression– Operand(s) // Operand(s) are part of an expression– Data

Page 10: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

10

Typical structure of an elementary program

<preprocessor directives>

void main()

{

<definition/declaration statements>

<executable statements>

}

Open next slide to look at the “Hello, World!” program

Page 11: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

11

The “Hello, World!” program

C++ notation

#include <iostream>

using namespace std;

void main( )

{

cout << “\nHello, World!”;

}

Page 12: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

12

Tutorial Introduction to C++

Names – strings of characters of any length

– case sensitive

– key words are reserved Names, also called identifiers:

– reserved words (if, else, for, while, …)

– standard identifiers (cin, cout, …)

– user defined identifiers (Price, Pom12a, FileSize, Counter, Ion12bcd, …)

Page 13: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

13

Tutorial Introduction to C++

Data – classification by category:

– Literal Values

– Named Constants

– Variables

Page 14: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

14

Tutorial Introduction to C++

Data – classification by type:

– Boolean (keyword bool)– Character (keyword char)– Integer (keywords int, unsigned, short, long)– Real (keywords float, double, long double)

Page 15: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

15

Tutorial Introduction to C++

Operators: Survey on arithmetic, relational, logical and assignment operators.– Arithmetic * / %

– + -

– Relational < <= > >=

– Equality == !=

– Logical AND (conjunction) &&

– Logical OR (disjunction) ||

– Assignment =

Page 16: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

16

Tutorial Introduction to C++

Expressions - are composed of operands and operators;

1 + 2

A – 3 * 5.6

A = B + C

A = B = 1 + 2

A = (B = C / (D*E)) + F;

Attention: expression terminated by ; is a statement

Attention: A program is a sequence of statements

Page 17: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

17

Tutorial Introduction to C++

Executable statements: assignment

<var> = <expression>;

x = 5;

How to read? “x becomes 5” or

“x gets 5” or

“x takes the value of 5” but never

x equals 5 (NO!)

Page 18: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

18

Tutorial Introduction to C++

Executable statements: selection/decision

if ( <expression>) <statement>

if ( <expression>) <statement1> else <statement2>

switch statement

Page 19: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

19

Tutorial Introduction to C++

Example: fragment of linear equation solutionif ( <expression>) <statement>

if ( b != 0 ) x = -c/b;

if ( b != 0 ){ x = -c/b; cout << “\n Solution is =“ << x;

}

Page 20: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

20

Tutorial Introduction to C++

Example: fragment of triangle area problemif ( <expression>) <statement1> else <statement2>

if ( a+b>c && b+c>a && a+c>b) { p = (a+b+c)/2; s = sqrt( p*(p-a)*(p-b)*(p-c) ); cout << “\n Area is = “ << s;

} else cout << “\nYou entered invalid data“;

Page 21: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

21

Tutorial Introduction to C++

Example: Fragment of menu choice program switch statement

int choice; cin >> choice;switch (choice){ case 1: Rectangle(); break; case 2: Square(); break; case 3: Triangle(); break; case 4: Circle(); break; default: cout << “\n Invalid input”;};

Page 22: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

22

Tutorial Introduction to C++

Executable statements: iteration/repetition

– for (<exp1>;<exp2>;<exp3>) <stmt>

– while ( <exp> ) <stmt>

– do <stmt> while( <exp> );

Page 23: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

23

Tutorial Introduction to C++

Example: sum of first five integers s=1+2+3+4+5– for (<exp1>;<exp2>;<exp3>) <stmt>

int I, s=0; for ( I=1; I<=5; I++ ) {

s = s + I;// display intermediate resultscout << ‘\n’ << s;

} // display final result cout << “\n\n\nFinal sum is = ” << s;

Page 24: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

24

Tutorial Introduction to C++ Example: sum of first five integers s=1+2+3+4+5 while ( <exp> ) <stmt>

int I = 1, s; s=0; while ( I<=5 ) {s = s + I;

// display intermediate results cout << ‘\n’ << s; I = I + 1; }

// display final result cout << “\n\n\nFinal sum is = ” << s;

Page 25: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

25

Tutorial Introduction to C++

Example: sum of first five integers s=1+2+3+4+5 do <stmt> while( <exp> );

int I = 1; int s = 0; do { s = s + I;

// display intermediate results cout << ‘\n’ << s; I = I + 1;

} while (I<5); // display final result cout << “\n\n\nFinal sum is = ” << s;

Page 26: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

26

Tutorial Introduction to C++

Elementary standard input/output: I/O - C notation based on library functionsgetchar(), putchar() - Read/Write a charactergets(), puts() - Read/Write a string of charsscanf(), printf() - formatted Read/Write

I/O - C++ notation based on OO streamscin - standard input stream cout - standard output stream

Page 27: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

27

The “Hello, World!” program

C notation

#include <stdio.h>

void main( )

{

printf(“\nHello, World!”);

}

Page 28: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

28

The “Hello, World!” program

C++ notation

#include <iostream>

using namespace std;

void main( )

{

cout << “\nHello, World!”;

}

Page 29: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

29

The “Hello, World!” program

#include <iostream>In C++, a stream is a sequence of characters associated with

an input device, or an output device, or a disk file.Class iostream defines object cin as the stream

associated with input device (keyboard).Class iostream defines object cout as the stream

associated with output device (screen).Class iostream also defines:

– input operator >> (extract from input stream);– output operator << (insert to output stream).

Page 30: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

30

The “Hello, World!” program

Concrete form: using namespace std;

Abstract form: using namespace <region>;

This line indicates that the program uses objects defined in the namespace specified by <region> in general (std for concrete).

This line should always follow the #include-s.

Page 31: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

31

Before lecture end

Lecture:A Tutorial Introduction to C++

More to read:Friedman/Koffman, Chapter 02

Or Coming approx. 60 slides

Page 32: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 2: Overview of C++

Problem Solving,

Abstraction, and Design using C++ 5e

by Frank L. Friedman and Elliot B. Koffman

Page 33: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

33Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

C++ Background

• Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s

• Based on C

• Supports object-oriented programming

• 1998 Standard

Page 34: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

34Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

2.1 C++ Language Elements

• Comments

• Compiler directives

• Function main

• Declaration statements

• Executable statements

Page 35: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

35Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Comments

• // symbols indicate a line comment - apply to just the rest of the line

• Block comments start with /* and end with */ - apply to as many lines as you like

• Used to describe the code in English or provide non-code information

• E.g. to include the name of the program or the author’s name

Page 36: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

36Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 2.1 Converting miles to kilometers

Page 37: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

37Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

#include <filename>

• Compiler directive

• Includes previously written code from a library into your program

• E.g.

#include <iostream>

has operators for performing input and output within the program

• Libraries allow for code reuse

Page 38: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

38Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

using namespace std;

• Indicates to compiler that this program uses objects defined by a standard namespace called std.

• Ends with a semicolon

• Follows #include directives in the code

• Must appear in all programs

Page 39: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

39Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Function main

int main ( )

{

// function body

}

Page 40: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

40Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Function main

• Exactly one main function per program

• A function is a collection of related statements that perform a specific operation

• int indicates the return type of the function

• ( ) indicates no special information passed to the function by the operating system

Page 41: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

41Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Types of Statements

• Declaration statements - describe the data the function needs:

const float KM_PER_MILE = 1.609;

float miles,

kms;

• Executable statements - specify the actions the program will take:

cout << “Enter the distance in miles: “;

cin >> miles;

Page 42: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

42Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

2.2 Reserved Words (Keywords)

• Have special meaning in C++

• Cannot be used for other purposes

Page 43: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

43Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 2.1 Reserved words in Listing 2.1

Page 44: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

44Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Identifiers

• Names for data and objects to be manipulated by the program

• Must begin with a letter or underscore (not recommended)

• Consist only of letters, digits, and underscores

• Cannot be reserved word

• Upper and lower case significant

Page 45: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

45Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Identifiers

Identifier Usecin C++ name for standard input stream

cout C++ name for standard output stream

km Data element for storing distance in kms

KM_PER_MILE Conversion constant

miles Data element for storing distance in miles

std C++ name for the standard namespace

Page 46: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

46Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

2.3 Data Types

• Defines a set of values and operations that can be performed on those values

• integers– positive and negative whole numbers,

e.g. 5, -52, 343222– short, int, long– represented internally in binary– predefined constants INT_MIN and INT_MAX

Page 47: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

47Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Data Types (con’t)

• Floating point (real)– number has two parts, integral and fractional– e.g. 2.5, 3.66666666, -.000034, 5.0– float, double, long double– stored internally in binary as mantissa and

exponent– 10.0 and 10 are stored differently in memory

Page 48: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

48Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Data Types (con’t)

• Boolean– named for George Boole– represent conditional values– values: true and false

Page 49: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

49Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Data Types (con’t)

• Characters– represent individual character values

E.g. ’A’ ’a’ ’2’ ’*’ ’”’ ’ ’– stored in 1 byte of memory– special characters: escape sequences

E.g. ’\n’ ’\b’ ’\r’ ’\t’ ‘\’’

Page 50: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

50Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

string Class

• Strings not built-in, but come from library

• Classes extend C++

• string literal enclosed in double quotes

E.g.: “Enter speed: “ “ABC” “B” “true”

“1234”

• #include <string>– for using string identifiers, but not needed for

literals

Page 51: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

51Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Variable Declarations

• Set aside memory with a specific name for the data and define its values and operations

• The value can change during execution

• type identifier-list;

• E.g.: float x, y;

int me, you;

float week = 40.0;

string flower = “rose”;

Page 52: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

52Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Constant Declarations

• Memory cells whose values cannot change once set

• const type constant-identifier = value;

• E.g.:

const float KM_PER_MILE = 1.609;

• Often identified by using all upper case name

Page 53: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

53Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 2.2 Printing a welcoming message

Page 54: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

54Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

2.4 Executable Statements

• Assignment statements

• Input statements

• Program output

• The return statement

Page 55: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

55Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 2.2 Memory (a) before and (b) after execution of a program

Page 56: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

56Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Assignment Statements

• variable = expression;

• E.g.:

kms = KM_PER_MILE * miles;

Page 57: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

57Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Input Statements

• Obtain data for program to use - different each time program executes

• Standard stream library iostream

• cin - name of stream associated with standard input device (keyboard by default)

• Extraction operator (>>)

• E.g.:cin >> miles;

cin >> age >> firstInitial;

Page 58: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

58Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

In Listing 2.2:

cin >> letter1 >> letter2 >> lastname;

has the effect:

Page 59: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

59Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 2.6 Effect of cin >> letter1 >> letter2 >> lastname;

Page 60: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

60Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Program Output

• Used to display results of program

• Also standard stream library iostream

• cout - name of stream associated with standard output device (monitor by default)

• Insertion operator (<<) for each element

cout << data-element;

Page 61: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

61Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Program Output

• cout statement can be broken across lines

• Strings cannot be broken across lines

• Prompt messages used to inform program user to enter data

• Screen cursor is a moving marker indicating the position of where the next character will be displayed

• endl (or ‘\n’) causes a new line in output

Page 62: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

62Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Output Example

cout << “The distance in kilometers is “

<< kms << endl;

If variable kms has value 16.09, the output is:

The distance in kilometers is 16.09

Page 63: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

63Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The return Statement

• Last line of main function is typically

return 0;

• This transfers control from the program to the operating system, indicating that no error has occurred

Page 64: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

64Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 2.3 General Form of a C++ Program

Page 65: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

65Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Program Style

• Use of spacing– one statement per line– blanks after comma, around operators– in between some lines of code for readability

• Use of comments– header section– document algorithm steps– describe difficult code

Page 66: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

66Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Program Style

• Naming conventions for identifiers– Variables in all lower case, with initial capital

letter for additional words. No underscore.– Constants in all upper case, with underscores

between words.

Page 67: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

67Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

2.6 Arithmetic Expressions

• int data type

+ - * / %

• Integer division examples - result is integer15 / 3 = 5

15 / 2 = 7

0 / 15 = 0

15 / 0 undefined

Page 68: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

68Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Modulus for Integers

• Used only with integers

• Yields remainder - the result is integer

• Examples:7 % 2 = 1

299 % 100 = 99

49 % 5 = 4

15 % 0 undefined

15 % -7 system dependent

Page 69: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

69Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Mixed-type Expressions

• E.g.: 4.6 / 2 evaluates to 2.3

• Rule: when an integer and a floating point operand are combined by an operator, the integer gets converted to the floating point type

• Caveat: this rule is dependent on operator precedence rules

Page 70: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

70Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Mixed-type Assignments

• If the variable on left side of assignment is of different type than the type of the evaluated expression on the right side of =, the result of the expression must be converted to the appropriate type

Page 71: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

71Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Mixed-type Assignment Examples

float a, b, x;

int m, n;

a=10; // result is 10.0 stored in a

b = 3.5;

m=5;

n = 10;

x = m / n; // result is 0 assigned to x

m = b * 3; // result is 10 assigned to m

Page 72: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

72Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Order of Operator Precedence

( ) nested expressions evaluated

inside outunary +, -*, /, %binary +, -

Highest

Lowest

Associativity

Warning: watch out for the types of operands and the type of the result from evaluating each operand!

Page 73: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

73Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 2.10 Evaluation forz - (a +b / 2) + w * -y

Page 74: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

74Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 2.11 Evaluation tree form = x + k / 2;

Page 75: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

75Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Mathematical Formulas in C++

Page 76: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

76Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Case Study: Coin Collection

• Problem statementSaving nickels and pennies and want to exchange

these coins at the bank so need to know the value of coins in dollars and cents.

• Analysis– Need to count of nickels and pennies separately– Determine total value in cents– Use integer division by 100 to calculate dollars– Use modulus (%) to get remaining cents

Page 77: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

77Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Case Study: Data Requirements

• Problem input– string name– integer nickels– integer pennies

• Problem output– integer dollars– integer change

• Additional program variables– integer totalCents

Page 78: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

78Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Case Study: Formulas

• One dollar equals 100 pennies

• One nickel equals 5 pennies

Page 79: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

79Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Case Study: Design - Algorithm

1. Read in your niece’s first name

2. Read in the count of nickels and pennies

3. Compute the total value in cents

4. Find the value in dollars and loose change.

5. Display the value in dollars and loose change.

Page 80: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

80Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Case Study: Design - Algorithm

1. Read in your niece’s first name

2. Read in the count of nickels and pennies

3. Compute the total value in cents

3.1 totalCents is 5 times nickels plus pennies

4. Find the value in dollars and loose change.

4.1 dollars is integer quotient of totalCents and 100

4.2 change is integer remainer of totalCents and 100

5. Display the value in dollars and loose change.

Page 81: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

81Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Case Study: Implementation

• / used to implement step 4.1

• % used to implement step 4.2

• Verify that correct data types are used

• Verify mixed-type operations and promotions

Page 82: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

82Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Case Study: Testing

• Test results using various input combinations

• Verify results by hand or with calculator

Page 83: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

83Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 2.4 Value of a coin collection

// File: coins.cpp

// Determines the value of a coin collection

#include <iostream>

#include <string>

using namespace std;

int main()

{

string name; // input: niece’s first name

int pennies; // input: count of pennies

int nickels; // input: count of nickels

int dollars; // output: value of coins in dollars

int change; // output: value of coins in cents

int totalCents; // total cents represented

Page 84: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

84Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

// Read in your niece’s first name.

cout << "Enter your first name: ";

cin >> name;

// Read in the count of nickels and pennies.

cout << "Enter the number of nickels: ";

cin >> nickels;

cout << "Enter the number of pennies: ";

cin >> pennies;

Listing 2.4 Value of a coin collection (continued)

Page 85: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

85Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

// Compute the total value in cents.

totalCents = 5 * nickels + pennies;

// Find the value in dollars and change.

dollars = totalCents / 100; // integer division

change = totalCents % 100;

// Display the value in dollars and change.

cout << "Good work " << name << '!' << endl;

cout << "Your collection is worth "

<< dollars << " dollars and "

<< change << " cents." << endl;

return 0;

}

Listing 2.4 Value of a coin collection (continued)

Page 86: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

86Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

coins.cpp Sample Execution

Enter your first name: Sally

Enter the number of nickels: 30

Enter the number of pennies: 77

Good work Sally!

Your collection is worth 2 dollars and 27 cents.

Page 87: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

87Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

2.7 Interactive Mode, Batch Mode, and Data Files

• Interactive mode - input from user via keyboard

• Batch mode - input via a file, no user interaction

• Input/output redirection can be used for batch mode

Page 88: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

88Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Input Redirection• Requires a file already containing all input

data before the program is executed• At the time the program is executed, the

input file is specified• E.g. in UNIX

metric < mydata• Executes the program metric using the file

mydata for input• Echo printing often used with batch input

Page 89: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

89Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Output Redirection• Sends ALL output to a file instead of to the

display monitor• Not typically used with interactive input mode,

since even prompt messages will be sent to the output file

• E.g. in UNIX (not typical)

metric > myoutput• Both input AND output redirection

metric < mydata > myoutput

Page 90: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

90Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

2.8 Common Programming Errors

• Syntax– a grammatical error in the formation of a

program statement– detected by the compiler– prevents translation of source code into object

code, so no execution possible– messages are compiler dependent, so you must

learn how your compiler identifiers errors

Page 91: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

91Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Common Programming Errors

• Run-time errors– detected and displayed during execution of a

program– usually fatal - halts execution of code

Page 92: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

92Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Common Programming Errors

• Undetected errors– program runs to completion, but results are

incorrect– often the result of input of the wrong type being

entered

Page 93: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

93Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Common Programming Errors

• Logic errors– caused by a faulty algorithm– often difficult to locate– can result in either a run-time or undetected

error– system cannot identify - up to programmer to

locate– vital to verify program output to ensure correct

results

Page 94: Lecture 4: Computer Languages. A Tutorial Introduction to C++ COS120 Software Development Using C++ AUBG, COS dept

94

Thank You

For

Your Attention!