bellevue university cis 205: introduction to programming using c++ lecture 3: primitive data types

29
Bellevue Bellevue University University CIS 205: CIS 205: Introduction to Introduction to Programming Using C++ Programming Using C++ Lecture 3: Primitive Data Lecture 3: Primitive Data Types Types

Post on 19-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Bellevue UniversityBellevue University

CIS 205: CIS 205: Introduction to Introduction to Programming Using C++Programming Using C++

Lecture 3: Primitive Data TypesLecture 3: Primitive Data Types

Page 2: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Today We Are Going To:Today We Are Going To:

• Introduce the concept of program Introduce the concept of program requirementsrequirements• Develop a strategy for tackling programsDevelop a strategy for tackling programs• Describe identifiers and their useDescribe identifiers and their use• Describe the primitive data types used Describe the primitive data types used

by C++ and their operationsby C++ and their operations• Use assignment statementsUse assignment statements

Page 3: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

TopicTopic

Tackling a Programming Problem:Tackling a Programming Problem:Project 2.1Project 2.1

Page 4: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Step 1: Specify RequirementsStep 1: Specify Requirements

• Usually what is presented to a Usually what is presented to a programmer is a task to be done:programmer is a task to be done:Write a program to convert an input Write a program to convert an input Fahrenheit temperature to Celsius.Fahrenheit temperature to Celsius.

• Begin by making sure you understand Begin by making sure you understand the requirementsthe requirements• Then go on to break requirements into Then go on to break requirements into

simpler piecessimpler pieces

Page 5: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Step 2: AnalyzeStep 2: Analyze

• Next step is to determine what the user Next step is to determine what the user of the program is going to seeof the program is going to see• identify input quantitiesidentify input quantities• identify output quantitiesidentify output quantities

• For temperature conversion:For temperature conversion:• input is an integer number (Fahrenheit)input is an integer number (Fahrenheit)• output is an integer number (Celsius)output is an integer number (Celsius)

Page 6: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

IdentifiersIdentifiers

• Names for entities used in calculationNames for entities used in calculation• Rules:Rules:• begin with letter (upper or lower case), or begin with letter (upper or lower case), or

an underscore (_)an underscore (_)• composed of these characters and digitscomposed of these characters and digits• can be of any lengthcan be of any length• cannot be a reserved wordcannot be a reserved word• case sensitive: case sensitive: AreaArea is different from is different from areaarea

Page 7: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Identifiers (cont.)Identifiers (cont.)

• Important, but not rules:Important, but not rules:• obey naming conventionsobey naming conventions• make names descriptivemake names descriptive

• In this case let us choose:In this case let us choose:• fahrenheitfahrenheit: for the input temp: for the input temp• celsiuscelsius: for the output temp: for the output temp

Page 8: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Integer Data TypesInteger Data Types

• Integers of different sizes allow Integers of different sizes allow programmers to use storage smartlyprogrammers to use storage smartly• signed (first bit indicates + or -)signed (first bit indicates + or -)• unsigned (range from 0 to maximum)unsigned (range from 0 to maximum)

• short: 16 bits (-32768 to 32767)short: 16 bits (-32768 to 32767)• int: 32 bits (-2147483648 to 2147483647)int: 32 bits (-2147483648 to 2147483647)• long: 64 bits (way bigger)long: 64 bits (way bigger)

Page 9: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Other Data TypesOther Data Types

• float: 32 bits (6 or 7 significant digits)float: 32 bits (6 or 7 significant digits)• double: 64 bits (14 or 15 significant digits)double: 64 bits (14 or 15 significant digits)

• char: 2 bytes, or 16 bitschar: 2 bytes, or 16 bits

• boolean: true or false (two values)boolean: true or false (two values)

Page 10: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Step 2: Analyze (Complete)Step 2: Analyze (Complete)

• Combine knowledge of identifiers and Combine knowledge of identifiers and data types to declare quantitiesdata types to declare quantities• For now still just planning this outFor now still just planning this out

• For temperature conversion:For temperature conversion:• int fahrenheit;int fahrenheit;• int celsius;int celsius;

Page 11: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Step 3: DesignStep 3: Design

• Describe the calculation in detailDescribe the calculation in detail• Prompt the user for inputPrompt the user for input• Read input number: fahrenheit tempRead input number: fahrenheit temp• Convert to celsius by:Convert to celsius by:

• subtracting 32subtracting 32• multiplying by 5/9multiplying by 5/9

• Display the resultDisplay the result

Page 12: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Step 4: (Begin) ImplementingStep 4: (Begin) Implementing

• Now transfer your thoughts into the fileNow transfer your thoughts into the file• Create the projectCreate the project• Create program structureCreate program structure• Declare variablesDeclare variables• Write COMMENTS that describe designWrite COMMENTS that describe design

Page 13: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Variable DeclarationsVariable Declarations

• First step is to declare the variables that First step is to declare the variables that have been identified thus farhave been identified thus far• (Note that you must expect to have to (Note that you must expect to have to

add to that list later.)add to that list later.)• Identify other quantities that can be Identify other quantities that can be

declared as declared as constantsconstants• In this case the conversion factors would In this case the conversion factors would

make good constantsmake good constants

Page 14: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

LiteralsLiterals

• Literal: way to represent a data value Literal: way to represent a data value explicitlyexplicitly

• boolean: true or falseboolean: true or false• integers: enter number of appropriate size; integers: enter number of appropriate size;

use l or L to specify long valuesuse l or L to specify long values• char: enclose in single quotes char: enclose in single quotes →→ 'A' 'A'• string (not a primitive type) double quotes string (not a primitive type) double quotes

→→ “The quick brown fox . . .” “The quick brown fox . . .”

Page 15: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Literals (cont.)Literals (cont.)

• special characters (in chars and strings):special characters (in chars and strings):• quotes: must “escape” compiler’s quotes: must “escape” compiler’s

interpretation in order to display an actual interpretation in order to display an actual quote characterquote character• other special characters include tabs, other special characters include tabs,

linefeeds, and backslasheslinefeeds, and backslashes• backslash (\) is the escape character:backslash (\) is the escape character: →→ \” will display an actual double-quote\” will display an actual double-quote

Page 16: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Literals (cont.)Literals (cont.)

• floating point types:floating point types:• decimal notation: 1.45decimal notation: 1.45• exponential notation: 1.3E-5exponential notation: 1.3E-5• to specify float append f or F: 126fto specify float append f or F: 126f• to specify double append d or D: 126dto specify double append d or D: 126d

Page 17: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Variable InitializationVariable Initialization

• In most cases need to give a variable an In most cases need to give a variable an initial value in addition to declaring itinitial value in addition to declaring it• This is critical for constantsThis is critical for constants• In our case do not need to initialize the In our case do not need to initialize the

variables variables fahrenheitfahrenheit and and celsiuscelsius, but we , but we will have to initialize our constantswill have to initialize our constantsconst double FACTOR = 1.8;const double FACTOR = 1.8;const double OFFSET = 32.0;const double OFFSET = 32.0;

Page 18: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Step 4: (Cont.) ImplementingStep 4: (Cont.) Implementing

• Have specified quantitiesHave specified quantities• At this point it is probably easiest to At this point it is probably easiest to

specify the program outputspecify the program output• Now go back to your comments and Now go back to your comments and

write code which will execute the actions write code which will execute the actions you describeyou describe

Page 19: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

OperatorsOperators

• An operator is a symbol or sequence of An operator is a symbol or sequence of symbols that causes an action to happensymbols that causes an action to happen• Expression: an action containing a Expression: an action containing a

sequence of operators and variablessequence of operators and variables

Page 20: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Numerical/Mathematical Numerical/Mathematical OperatorsOperators

• Ordinary mathematics:Ordinary mathematics:• multiplication: *multiplication: *• division: /division: /• addition: +addition: +• subtraction: -subtraction: -• unary negation: -unary negation: -• remainder (integers): %remainder (integers): %

Page 21: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Numerical/Mathematical Numerical/Mathematical Operators (cont.)Operators (cont.)

• Increment/Decrement:Increment/Decrement:var++; // increment by one AFTER usevar++; // increment by one AFTER use++var; // increment by one BEFORE use++var; // increment by one BEFORE usevar--; // decrement by one AFTER usevar--; // decrement by one AFTER use--var; // decrement by one BEFORE use--var; // decrement by one BEFORE use

Page 22: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Numerical/Mathematical Numerical/Mathematical Operators (cont.)Operators (cont.)

• Assignment shortcuts:Assignment shortcuts:+= adds expression on right to the one on += adds expression on right to the one on

the left, assigns result to name on leftthe left, assigns result to name on left-= subtracts right from left, assigns result -= subtracts right from left, assigns result

to variable on leftto variable on left*= multiplies right and left, assigns result *= multiplies right and left, assigns result

to variable on leftto variable on left/= divides left by right, assigns result to /= divides left by right, assigns result to

variable on leftvariable on left

Page 23: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Boolean/Logical OperatorsBoolean/Logical Operators

• Testing for true and false:Testing for true and false:• and: &&and: &&• or: ||or: ||• exclusive or: ^exclusive or: ^• logical negation: !logical negation: !• comparisons: <, >, <=, >=, ==, !=comparisons: <, >, <=, >=, ==, !=

Page 24: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Other OperatorsOther Operators

• String concatenation: +String concatenation: +• Class-member access: .Class-member access: .• Precedence: ( )Precedence: ( )

Page 25: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Operator Precedence and Operator Precedence and Evalutation OrderEvalutation Order

• Rules are too much to review here; look Rules are too much to review here; look for them in your bookfor them in your book• Pay attention to them; they will be the Pay attention to them; they will be the

source of many difficult bugssource of many difficult bugs• Remember that you can control order Remember that you can control order

with the “precedence operator”: ( )with the “precedence operator”: ( )

Page 26: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Step 4: (Finish) ImplementingStep 4: (Finish) Implementing

• Complete the implementation by coding Complete the implementation by coding the actionsthe actions• Note that in this case we can combine Note that in this case we can combine

them onto one linethem onto one linecelsius = (fahrenheit – OFFSET)/FACTOR;celsius = (fahrenheit – OFFSET)/FACTOR;

Page 27: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Step 5a: CompileStep 5a: Compile

• The first step in validating your code is The first step in validating your code is the compilation stepthe compilation step• Run the compilationRun the compilation• Interpret error messagesInterpret error messages• Fix problems, starting at TOP and Fix problems, starting at TOP and

recompiling frequentlyrecompiling frequently• (Remember, one mistake may cause (Remember, one mistake may cause

several errors)several errors)

Page 28: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Step 5b: TestStep 5b: Test

• Compilation is crucial, but you must also Compilation is crucial, but you must also check for other kinds of errorscheck for other kinds of errors• Doing so requires that you run your Doing so requires that you run your

program several times to prove that you program several times to prove that you get the right answerget the right answer• 3232°°F is 0F is 0°°CC• 212212°°F is 100F is 100°°CC• 8686°°F is 30F is 30°°CC

Page 29: Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types

Step 5b: Test (cont.)Step 5b: Test (cont.)

• Can see that there is something going Can see that there is something going wrong with our program – can you guess wrong with our program – can you guess what it is?what it is?• Have a round-off problemHave a round-off problem• For now we can solve that problem by For now we can solve that problem by

adding 0.5 to the result of our calculationadding 0.5 to the result of our calculation