Top Banner
© 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2
39

© 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

Dec 15, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Problem Solving Using C++

Structured Programming 256

Chapter 2

Page 2: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

C++ and Other Computer Languages

• C++ has many similarities to other computer languages– Very similar to Java and Smalltalk

• Shares many concepts with– Visual Basic, Delphi

• Inherits many characteristics from– Pascal, PL/1, C, Algol, Fortran, Cobol

Page 3: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Variables

• Used to store data during program execution– Results of calculations– Temporary values– Control information

• Can hold many different types of data– Numbers, characters, strings of characters and

objects ( collections of data and programs )

Page 4: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

What is a program variable?

• A named location to store data– a container for data

• It can hold only one type of data– for example only integers, only floating point

(real) numbers, or only characters

Page 5: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Post Office Metaphor

• Post Offices contain a section of PO boxes– Boxes are like memory. Available to store all

kinds of information. Boxes are allocated, assigned a name (number).

• Computer memory– Can store any type of data (numbers, strings

etc.)– Available for allocation and assignment

Page 6: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Creating variables• All program variables must be declared before using them

• A variable declaration associates a name with a storage location in memory and specifies the type of data it will store:

Type Variable_1, Variable_2, …;

• For example, to create three integer variables to store the number of baskets, number of eggs per basket, and total number of eggs:

int numberOfBaskets, eggsPerBasket, totalEggs;

Page 7: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Variables

• Variables store data in a program• Variables must be declared (or defined) before

they are used– Variable declarations

• Variable type• Variable name (identifier)

– Example• int nPosition, nHeight, nWidth;• char cAnswer;

Page 8: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Variable Names

• Naming rules– Identifiers must start with a letter, may contain

letters or numbers or _– There is essentially no limit to the length of an

identifier

• Variable name should match its use– Use dName rather than a– Use nHeight rather than x

Page 9: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Variable Types

• Primitive types– Basic building blocks of the C++ language. Match

intrinsic hardware capabilities.

• Class types– Contain:

• One or more primitive types• Plus associated C++ statements to manage the

primitive types• Possibly even other class types

Page 10: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Primitive Types

short integer 1 byte

int integer 2 bytes

unsigned integer 4 bytes

long integer 8 bytes

float real 4 bytes

double real 8 bytes

char character 2 bytes

bool logical 1 bit/1 byte

Use the sizeof() operator for a particular system

Page 11: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Primitive Data Types

Type Name Kind of Value Memory Used Size Range

short integer 1 byte -128 to 127

int integer 2 bytes -32768 to 32767

unsigned Integer 2 bytes 0 to 65,535

long integer 4 bytes -2,147,483,648 to 2,147,483,647

float floating point 4 bytes +/- 3.4028… x 10+38 to+/- 1.4023… x 0-45

double floating point 8 bytes +/- 1.767… x 10+308 to+/- 4.940… x 0-324

char single character 2 bytes all ASCII characters

bool true or false 1 bit not applicable

Page 12: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Primitive Types

• Integer– Signed whole numbers only (no decimal)

• Real (Scientific Notation)– Signed numbers with two portions

• An exponent• A mantissa with a fixed precision

• Char– ASCII character

Page 13: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Integer vs Real Numbers

• Why two different systems?– Clearly the range of integers fit into the range of real

numbers

• Integers are computationally very efficient– If you can use integers, do so your program will run

much faster

• Integers are precise– By their nature, real numbers often have very small

errors that creep into their representation. Integers do not have this issue.

Page 14: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Variable names: Identifiers

Rules- these must be obeyed

• all C++ identifiers must follow the same rules

• must not start with a digit

• must contain only numbers, letters, underscore (_) and $ (but avoid using $, it is reserved for special purposes)

• names are case-sensitive (ThisName and thisName are two different variable names)

Good Programming Practice - these should be obeyed

• always use meaningful names from the problem domain (for example, eggsPerBasket instead of n, which is meaningless, or count, which is not meaningful enough)

• start variable names with lower case

• capitalize interior words (use eggsPerBasket instead of eggsperbasket)

• avoid using $ since it is reserved for special purposes

Page 15: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Two main kinds of types in C++

primitive data types• the simplest types

• cannot decompose into other types

• values only, no methods

• Examples:int - integerdouble - floating point (real)char - character

class types• more complex

• composed of other types (primitive or class types)

• both data and methods

Page 16: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Syntax Templates

• Efficient method to communicate the grammar of a computer language– Similar to a sentence diagram– Indicates the required and optional portions of a

statement.

Page 17: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Assignment Statements

• Syntax template

Variable = Expression ;

• Operation– The expression on the right hand side is

evaluated and assigned to the memory location named by the variable on the left hand side.

Page 18: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Expressions

• Simple expression– Variable

• Arithmetic expressions– Binary operators (require two values)

• + - * / %

– Unary operators (only one value needed)• + - ++ --

Page 19: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Expression Examplesint nPosition, nHeight, nWidth;nPosition = 0;nHeight = 5;nWidth = nHeight;

nHeight = nHeight * 2;nPosition = nHeight + nWidth * 3 + 5;

float nXPos, nYPos;nXPos = 2.3;nYPos = nXPos / 0.3 ;

nHeight = -nWidth;nHeight = nWidth * -nPosition;

Page 20: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Additional Arithmetic Operators

• Increment and Decrement – ++ will increment a variable by 1– -- will decrement a variable by 1– A unary operator that can be prefix or postfix

• Modulus operator %– Integer division yields an integer result– % Returns the remainder of an integer division

Page 21: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Samples

int nSomeNumber, nQuotient, nRemainder;nSomeNumber = 17;nQuotient = nSomeNumber / 3;nRemainder = nSomeNumber % 3;float nAnswer;nAnswer = nSomeNumber / 3.0;nSomeNumber++;nQuotient = 7;nSomeNumber = nQuotient ++;nSomeNumber = ++nQuotient ;

Page 22: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Samplesvoid main() { cout<<"Hello World”<<endl; int nSomeNumber, nQuotient, nRemainder; nSomeNumber = 17; nQuotient = 7; nSomeNumber = nQuotient++; cout<<"nQuotient postfix is " << nQuotient<<endl; cout<<"nSomeNumber postfix is " << nSomeNumber<<endl; nSomeNumber = ++nQuotient ; cout<<"nQuotient prefix is " +<<nQuotient<<endl; cout<<"nSomeNumber prefix is " << nSomeNumber<<endl; }

Page 23: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Examples to runint nCount = 0;int nValue = 0;

nValue = nCount++;cout<<"NCount is"+nCount+"nValue is ”<< nValue<<endl;nValue = ++nCount;cout<<"NCount is "+nCount+" nValue is ”<< nValue<<endl;nCount++;++nCount;

nValue = nValue + 1;

nCount = nValue--;nCount = nValue - 1;

Page 24: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Prefix and Postfix

• A prefix ++ or -- is evaluated (executed) first and the new value is available in the current expression

• A postfix ++ or -- is evaluated (executed) after the expression has been evaluated therefore the new value IS NOT available in the current expression

Page 25: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Precedence Rules

• How is the following expression evaluated?– nPosition = nHeigth / nWidth + 5 * 3;

• Why?• Precedence rules (introduction)

– First unary operators + , -, ++, -- – Next binary operators *, /, %– Then binary operators +, -– Unless there are parenthesis ( )

Page 26: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Precedence Exercise

int nCount = 0;int nValue = 0;

nValue = 1 + 2 – 3 – 4;nValue = 16 * 4 / 2 * 3;nValue = 7 – 3 * 4 + 2;

nValue = 6 * -nCount + 5;

nValue = (6 * (-nCount)) + 5;

Page 27: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Conversion between types

• Implicit conversion– C++ will automatically convert some types. This

conversion is often call promotion since the conversion always moves to a more expansive type.

– shortintlongfloatdouble– Any type can be promoted to a type on its right

• byte can be promoted to long• float can not be promoted to short

Page 28: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Sample

int foo; double foobar;

foobar = 2.5; foo = foobar; cout<<"foobar is " << foobar;

Page 29: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Conversion between types

• Explicit conversion• C++ allows the programmer to explicitly

specify a conversion though a cast– This allows a conversion that would not be

done through promotion, but should be used with caution.

• Values are truncated (not rounded) without warning.• Special issues when casting characters to numbers

Page 30: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Key escape characters

• Double quote– \”

• Single quote– \’

• New line– \n

• Carriage return– \r

• Tab– \t

• Backslash– \\

Page 31: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Console I/O

• Input from the keyboard, output to a “console” window.– Not Windows programming per se– Rather a rudimentary input and output

mechanism useful for simple programs where we don’t want to spend a great deal of time on the user interface

• No mouse, graphics, multiple windows etc.

Page 32: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Output

• Cout<<– Outputs to the console window

• Use endl or \n for a new line

Page 33: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Input Methods

• Cin>>

Page 34: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

A Matter of Programming Style

• Using a good programming style is essential– Allows you to communicate your design to team– Makes your program more easy to modify later– Communicates a clean and professional message

• Most programming organizations have development standards– Variable names, class names, comments etc.

Page 35: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Style Pointers

• Use meaningful names for variables and all identifiers– I often use a prefix to the variable that

communicates its type. This is optional.

• Use comments to explain the program– Comments are ignored by the compiler, rather

they are used to communicate with other programmers (or yourself).

Page 36: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Comments

• Two types of comments– // -- everything after a // is ignored by the

compiler to the end of the line– /* -- everything after a /* is ignored by the

compiler until a */ is reached

Page 37: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Style Pointers

• Indenting– Indenting your source code makes it easier to see the

beginning and ending of blocks.

• Named constants– Rather than using values like 100 as a maximum

number, use a named constant of MAXNUMBER.

– Benefits – easier to understand, and most importantly, easier to modifier later.

Page 38: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Named Constants

• Named constants are of type– const

• Normally there names are all upper case

• Examples

const int MAXNUMBER = 100;

const float MINTEMP = -40.0;

Page 39: © 2000 Scott S Albert Problem Solving Using C++ Structured Programming 256 Chapter 2.

© 2000 Scott S Albert

Summary

• We are starting to see the major foundations of the C++ language– Basic types

• Conversion between types

– Assignment statements– Arithmetic expressions– Etc.