50
C++ C++

01 c++ Intro.ppt

Embed Size (px)

Citation preview

Page 1: 01 c++ Intro.ppt

C++C++

Page 2: 01 c++ Intro.ppt

The Task of ProgrammingThe Task of Programming

► ProgrammingProgramming a computer involves writing a computer involves writing instructions that enable a computer to carry instructions that enable a computer to carry out a single task or a group of tasksout a single task or a group of tasks

► A computer A computer programming languageprogramming language requires requires learning both vocabulary and syntaxlearning both vocabulary and syntax

► Programmers use many different Programmers use many different programming languages, including BASIC, programming languages, including BASIC, Pascal, COBOL, RPG, and Pascal, COBOL, RPG, and C++C++

► The rules of any language make up its The rules of any language make up its syntaxsyntax► Machine languageMachine language is the language that is the language that

computers can understand; it consists of 1s computers can understand; it consists of 1s and 0sand 0s

1

Page 3: 01 c++ Intro.ppt

The Task of ProgrammingThe Task of Programming

►A translator (called either a compiler or A translator (called either a compiler or an interpreter) checks your program an interpreter) checks your program for syntax errorsfor syntax errors

►A A logical errorlogical error occurs when you use a occurs when you use a statement that, although syntactically statement that, although syntactically correct, doesn’t do what you intendedcorrect, doesn’t do what you intended

► You You runrun a program by issuing a a program by issuing a command to execute the program command to execute the program statementsstatements

► You You testtest a program by using sample a program by using sample data to determine whether the data to determine whether the program results are correctprogram results are correct

1

Page 4: 01 c++ Intro.ppt

Programming UniversalsProgramming Universals

► All programming languages provide methods All programming languages provide methods for directing for directing outputoutput to a desired object, such to a desired object, such as a monitor screen, printer or fileas a monitor screen, printer or file

► Similarly, all programming languages provide Similarly, all programming languages provide methods for sendingmethods for sending input input into the computer into the computer program so that it can be manipulatedprogram so that it can be manipulated

► In addition, all programming languages In addition, all programming languages provide for naming locations in computer provide for naming locations in computer memory memory

► These locations commonly are called These locations commonly are called variables variables (or (or attributesattributes))

1

Page 5: 01 c++ Intro.ppt

Programming UniversalsProgramming Universals

► Ideally, variables have meaningful names, Ideally, variables have meaningful names, although no programming language although no programming language actually requires that they meet this actually requires that they meet this standardstandard

►A variable may have only one value at a A variable may have only one value at a time, but it is the ability of memory time, but it is the ability of memory variables to variables to changechange in value that makes in value that makes computers and programming worthwhilecomputers and programming worthwhile

► In many computer programming In many computer programming languages, including C++, variables must languages, including C++, variables must be explicitly be explicitly declareddeclared, or given a data , or given a data type as well as a name, before they can type as well as a name, before they can be usedbe used

1

Page 6: 01 c++ Intro.ppt

Programming UniversalsProgramming Universals

► The The typetype determines what kind of values determines what kind of values may be stored in a variablemay be stored in a variable

►Most computer languages allow at least Most computer languages allow at least two types: one for numbers and one for two types: one for numbers and one for characterscharacters

►Numeric variablesNumeric variables hold values like 13 or -6 hold values like 13 or -6► Character variablesCharacter variables hold values like ‘A’ or hold values like ‘A’ or

‘&’‘&’►Many languages include even more Many languages include even more

specialized types, such as specialized types, such as integerinteger (for (for storing whole numbers) or storing whole numbers) or floating pointfloating point (for storing numbers with decimal places)(for storing numbers with decimal places)

1

Page 7: 01 c++ Intro.ppt

Procedural ProgrammingProcedural Programming

► Procedural programsProcedural programs consist of a series of consist of a series of steps or procedures that take place one after steps or procedures that take place one after the otherthe other

► The programmer determines the exact The programmer determines the exact conditions under which a procedure takes conditions under which a procedure takes place, how often it takes place, and when the place, how often it takes place, and when the program stopsprogram stops

► Programmers write procedural programs in Programmers write procedural programs in many programming languages, such as COBOL, many programming languages, such as COBOL, BASIC, FORTRAN, and RPGBASIC, FORTRAN, and RPG

► You can also write procedural programs in C++ You can also write procedural programs in C++

1

Page 8: 01 c++ Intro.ppt

A A main( )main( ) Function in C++ Function in C++

► C++ programs consist of modules called C++ programs consist of modules called functionsfunctions

► Every statement within every C++ Every statement within every C++ program is contained in a functionprogram is contained in a function

► Every function consists of two parts:Every function consists of two parts: A A function headerfunction header is the initial line of code in a is the initial line of code in a

C++ which always has three parts:C++ which always has three parts:► Return type of the functionReturn type of the function► Name of the functionName of the function► Types and names of any variables enclosed in Types and names of any variables enclosed in

parentheses, and which the function receivesparentheses, and which the function receives A A function bodyfunction body

1

Page 9: 01 c++ Intro.ppt

Creating a Creating a main( )main( ) Function Function

►A C++ program may contain many A C++ program may contain many functions, but every C++ program functions, but every C++ program contains at least one function, and that contains at least one function, and that function is called function is called main( )main( )

► If the main function does not pass values If the main function does not pass values to other programs or receives values from to other programs or receives values from outside the program, then main( ) receives outside the program, then main( ) receives and returns a void typeand returns a void type

► The body of every function in a C++ The body of every function in a C++ program is contained in curly braces, also program is contained in curly braces, also known as curly bracketsknown as curly brackets

1

Page 10: 01 c++ Intro.ppt

Creating a Creating a main( )main( ) Function Function

► Every complete C++ statement ends with a Every complete C++ statement ends with a semicolonsemicolon

► Often several statements must be grouped Often several statements must be grouped together, as when several statements must together, as when several statements must occur in a loopoccur in a loop

► In such a case, the statements have their own In such a case, the statements have their own set of opening and closing braces within the set of opening and closing braces within the main braces, forming a main braces, forming a blockblock

1

Page 11: 01 c++ Intro.ppt

Working with VariablesWorking with Variables

► In C++, you must name and give a type In C++, you must name and give a type to variables (sometimes called to variables (sometimes called identifiersidentifiers) before you can use them) before you can use them

► Names of C++ variables can include Names of C++ variables can include letters, numbers, and underscores, but letters, numbers, and underscores, but must begin with a letter or underscoremust begin with a letter or underscore

► No spaces or other special characters are No spaces or other special characters are allowed within a C++ variable nameallowed within a C++ variable name

► Every programming language contains a Every programming language contains a few vocabulary words, or few vocabulary words, or keywordskeywords, that , that you need in order to use the languageyou need in order to use the language

1

Page 12: 01 c++ Intro.ppt

Common C++ KeywordsCommon C++ Keywords

Page 13: 01 c++ Intro.ppt

Working with VariablesWorking with Variables

► A C++ keyword cannot be used as a variable A C++ keyword cannot be used as a variable namename

► Each named variable must have a type Each named variable must have a type ► C++ supports three simple types:C++ supports three simple types:

IntegerInteger — Floating point— Floating point — Character— Character

► An An integerinteger is a whole number, either positive is a whole number, either positive or negativeor negative

► An integer value may be stored in an An integer value may be stored in an integer integer variablevariable declared with the keyword declared with the keyword intint

► You can also declare an integer variable You can also declare an integer variable using short int and long intusing short int and long int

1

Page 14: 01 c++ Intro.ppt

Working with VariablesWorking with Variables

► RealReal or or floating-point numbersfloating-point numbers are numbers are numbers that include decimal positions, such as 98.6, that include decimal positions, such as 98.6, 1000.00002, and -3.851000.00002, and -3.85

► They may be stored in variables with type They may be stored in variables with type float, doublefloat, double, and , and long doublelong double

► Characters may be stored in variables Characters may be stored in variables declared with the keyword declared with the keyword charchar

► A A charactercharacter may hold any single symbol in the may hold any single symbol in the ASCII character setASCII character set

► Often it contains a letter of the alphabet, but Often it contains a letter of the alphabet, but it could include a space, digit, punctuation it could include a space, digit, punctuation mark, arithmetic symbol, or other special mark, arithmetic symbol, or other special symbolsymbol

1

Page 15: 01 c++ Intro.ppt

Working with VariablesWorking with Variables

► In C++, a character value is always expressed In C++, a character value is always expressed in single quotes, such as ‘A’ or ‘&’in single quotes, such as ‘A’ or ‘&’

► To declare a variable, you list its type and its To declare a variable, you list its type and its namename

► In addition, a variable declaration is a C++ In addition, a variable declaration is a C++ statement, so it must end with a semicolonstatement, so it must end with a semicolon

► If you write a function that contains variables If you write a function that contains variables of diverse types, each variable must be of diverse types, each variable must be declared in a statement of its owndeclared in a statement of its own

► If you want to declare two or more variables of If you want to declare two or more variables of the same type, you may declare them in the the same type, you may declare them in the same statementsame statement

Page 16: 01 c++ Intro.ppt

Working with VariablesWorking with Variables

► Explicitly stating the value of a variable is Explicitly stating the value of a variable is called called assignmentassignment, and is achieved with the , and is achieved with the assignment operator =assignment operator =

► The variable finalScore is declared and The variable finalScore is declared and assigned a value at the same timeassigned a value at the same time

► Assigning a value to a variable upon creation Assigning a value to a variable upon creation is often referred to as is often referred to as initializinginitializing the variable the variable

1

Page 17: 01 c++ Intro.ppt

The const QualifierThe const Qualifier

► A variable that does not change in a A variable that does not change in a program should not be declared as a program should not be declared as a variablevariable

► Instead, it should be a constantInstead, it should be a constant

► The statement const double The statement const double MINIMUM_WAGE = 5.75; declares a MINIMUM_WAGE = 5.75; declares a constant named MINIMUM_WAGE that can constant named MINIMUM_WAGE that can be used like a variable, but cannot be be used like a variable, but cannot be changed during a programchanged during a program

1

Page 18: 01 c++ Intro.ppt

Creating CommentsCreating Comments

► CommentsComments are statements that do not affect are statements that do not affect the compiling or running of a programthe compiling or running of a program

► Comments are simply explanatory remarks Comments are simply explanatory remarks that the programmer includes in a program that the programmer includes in a program to clarify what is taking placeto clarify what is taking place

► These remarks are useful to later program These remarks are useful to later program users because they might help explain the users because they might help explain the intent of a particular statement or the intent of a particular statement or the purpose of the entire programpurpose of the entire program

► C++ supports both line comments and block C++ supports both line comments and block commentscomments

1

Page 19: 01 c++ Intro.ppt

Creating CommentsCreating Comments

► A A line commentline comment begins with two slashes (//) and begins with two slashes (//) and continues to the end of the line on which it is placedcontinues to the end of the line on which it is placed

► A A block commentblock comment begins with a single slash and an begins with a single slash and an asterisk (/*) and ends with an asterisk and a slash (*/); asterisk (/*) and ends with an asterisk and a slash (*/); it might be contained on a single line or continued it might be contained on a single line or continued across many linesacross many lines

1

Page 20: 01 c++ Intro.ppt

Using Libraries and Using Libraries and Preprocessor DirectivesPreprocessor Directives

► Header filesHeader files are files that contain predefined are files that contain predefined values and routines, such as sqrt( )values and routines, such as sqrt( )

► Their filenames usually end in .hTheir filenames usually end in .h► In order for your C++ program to use these In order for your C++ program to use these

predefined routines, you must include a predefined routines, you must include a preprocessor directivepreprocessor directive, a statement that tells , a statement that tells the compiler what to do before compiling the the compiler what to do before compiling the programprogram

► In C++, all preprocessor directives begin with In C++, all preprocessor directives begin with a pound sign (#), which is also called an a pound sign (#), which is also called an octothorpoctothorp

► The The #include#include preprocessor directive tells the preprocessor directive tells the compiler to include a file as part of the compiler to include a file as part of the finished productfinished product

1

Page 21: 01 c++ Intro.ppt

C++ Binary Arithmetic C++ Binary Arithmetic OperatorsOperators

► Often after data values are input, you perform Often after data values are input, you perform calculations with themcalculations with them

► C++ provides five simple arithmetic operators C++ provides five simple arithmetic operators for creating arithmetic expressions:for creating arithmetic expressions: addition (+)addition (+) – subtraction (-)– subtraction (-) multiplication (*)multiplication (*) – division (/)– division (/) modulus (%)modulus (%)

► Each of these arithmetic operators is a binary Each of these arithmetic operators is a binary operator; each takes two operands, one on each operator; each takes two operands, one on each side of the operator, as in 12 + 9 or 16.2*1.5side of the operator, as in 12 + 9 or 16.2*1.5

► The results of an arithmetic operation can be The results of an arithmetic operation can be stored in memorystored in memory

2

Page 22: 01 c++ Intro.ppt

C++ Binary Arithmetic C++ Binary Arithmetic OperatorsOperators

2

Page 23: 01 c++ Intro.ppt

C++ Binary Arithmetic C++ Binary Arithmetic OperatorsOperators

► In Figure 2-2, each operation is assigned to a In Figure 2-2, each operation is assigned to a result variable of the correct typeresult variable of the correct type

► The expression The expression a + ba + b has an integer result has an integer result because both a and b are integers, because both a and b are integers, notnot because their sum is stored in the because their sum is stored in the intResultintResult variablevariable

► If the program contained the statement If the program contained the statement doubleResult = a+b;doubleResult = a+b; the expression the expression a+ba+b would would still have an integer value, but the value still have an integer value, but the value would be would be castcast, or transformed, into a double , or transformed, into a double when the sum is assigned to when the sum is assigned to doubleResultdoubleResult

2

Page 24: 01 c++ Intro.ppt

C++ Binary Arithmetic C++ Binary Arithmetic OperatorsOperators

► The automatic cast that occurs when you The automatic cast that occurs when you assign a value of one type to another is called assign a value of one type to another is called an implicit castan implicit cast

► The modulus operator (%), which gives the The modulus operator (%), which gives the remainder of integer division, can be used remainder of integer division, can be used only with integersonly with integers

► When more than one arithmetic operator is When more than one arithmetic operator is included in an expression, then multiplication, included in an expression, then multiplication, division, and modulus operations always division, and modulus operations always occur before addition or subtractionoccur before addition or subtraction

► Multiplication, division, and modulus are said Multiplication, division, and modulus are said to have to have higher precedencehigher precedence

2

Page 25: 01 c++ Intro.ppt

Shortcut Arithmetic OperatorsShortcut Arithmetic Operators

► C++ employs several shortcut operatorsC++ employs several shortcut operators

► When you add two variable values and store When you add two variable values and store the result in a third variable, the expression the result in a third variable, the expression takes the form takes the form result= firstValue + result= firstValue + secondValuesecondValue

► When you use an expression like this, both When you use an expression like this, both firstValuefirstValue and and secondValuesecondValue retain their retain their original values; only the result is alteredoriginal values; only the result is altered

► When you want to increase a value, the When you want to increase a value, the expression takes the form expression takes the form firstValue = firstValue = firstValue + secondValuefirstValue + secondValue

2

Page 26: 01 c++ Intro.ppt

Shortcut Arithmetic OperatorsShortcut Arithmetic Operators

► C++ provides the -= operator for subtracting C++ provides the -= operator for subtracting one value from another, the *= operator for one value from another, the *= operator for multiplying one value by another, and the /= multiplying one value by another, and the /= operator for dividing one value by anotheroperator for dividing one value by another

► As with the += operator, you must not insert As with the += operator, you must not insert a space within the subtraction, a space within the subtraction, multiplication, or division shortcut operatorsmultiplication, or division shortcut operators

► The options shown in Figure 2-4 means The options shown in Figure 2-4 means replace the current value of count with the replace the current value of count with the value that is 1 more than count, or simplyvalue that is 1 more than count, or simply incrementincrement count count

2

Page 27: 01 c++ Intro.ppt

Shortcut Arithmetic OperatorsShortcut Arithmetic Operators

► As you might expect, you can use two As you might expect, you can use two minus signs (--) before or after a variable minus signs (--) before or after a variable to to decrementdecrement it it

2

Page 28: 01 c++ Intro.ppt

Shortcut Arithmetic OperatorsShortcut Arithmetic Operators

► The prefix and postfix increment and decrement The prefix and postfix increment and decrement operators are examples of unary operatorsoperators are examples of unary operators

► Unary operatorsUnary operators are those that require only one are those that require only one operand, such as num in the expression ++numoperand, such as num in the expression ++num

► When an expression includes a prefix operator, When an expression includes a prefix operator, the mathematical operation takes place before the mathematical operation takes place before the expression is evaluatedthe expression is evaluated

► When an expression includes a postfix When an expression includes a postfix operator, the mathematical operation takes operator, the mathematical operation takes place after the expression is evaluatedplace after the expression is evaluated

2

Page 29: 01 c++ Intro.ppt

Shortcut Arithmetic OperatorsShortcut Arithmetic Operators

►The difference between the The difference between the results produced by the prefix and results produced by the prefix and postfix operators can be subtle, postfix operators can be subtle, but the outcome of a program can but the outcome of a program can vary greatly depending on which vary greatly depending on which increment operator you use in an increment operator you use in an expressionexpression

2

Page 30: 01 c++ Intro.ppt

Evaluating Boolean ExpressionsEvaluating Boolean Expressions

► A A boolean expressionboolean expression is one that evaluates as true is one that evaluates as true or falseor false

► All false relational expressions are evaluated as 0All false relational expressions are evaluated as 0► Thus, an expression such as 2>9 has the value 0Thus, an expression such as 2>9 has the value 0► You can prove that 2>9 is evaluated as 0 by You can prove that 2>9 is evaluated as 0 by

entering the statement code <<(2>9); into a C++ entering the statement code <<(2>9); into a C++ programprogram

► A 0 appears on outputA 0 appears on output► All true relational expressions are evaluated as 1 All true relational expressions are evaluated as 1 ► Thus, the expression 9>2 has the value 1Thus, the expression 9>2 has the value 1

2

Page 31: 01 c++ Intro.ppt

Evaluating Boolean ExpressionsEvaluating Boolean Expressions

► The unary operator ! Means not, and essentially The unary operator ! Means not, and essentially reverses the true/false value of an expressionreverses the true/false value of an expression

2

Page 32: 01 c++ Intro.ppt

SelectionSelection

► Computer programs seem smart because Computer programs seem smart because of their ability to use selections or make of their ability to use selections or make decisions decisions

► C++ lets you perform selections in a C++ lets you perform selections in a number of ways:number of ways: The if statementThe if statement

The switch statementThe switch statement

The if operatorThe if operator

Logical AND and Logical ORLogical AND and Logical OR

2

Page 33: 01 c++ Intro.ppt

Some Sample Selection Some Sample Selection Statements within a C++ ProgramStatements within a C++ Program2

Page 34: 01 c++ Intro.ppt

The ifThe if StatementStatement

► If the execution of more than one statement depends on If the execution of more than one statement depends on the selection, then the statements must be blocked with the selection, then the statements must be blocked with curly braces as shown in the code segment in Figure 2-8curly braces as shown in the code segment in Figure 2-8

2

Page 35: 01 c++ Intro.ppt

The ifThe if StatementStatement2

Page 36: 01 c++ Intro.ppt

Multiple Executable Statement Multiple Executable Statement in an if-elsein an if-else

2

Page 37: 01 c++ Intro.ppt

The ifThe if StatementStatement

► Any C++ expression can be evaluated as Any C++ expression can be evaluated as part of an if statementpart of an if statement

2

Page 38: 01 c++ Intro.ppt

The switch StatementThe switch Statement

► When you want to create different outcomes depending When you want to create different outcomes depending on specific values of a variable, you can use a series of ifs on specific values of a variable, you can use a series of ifs shown in the program statement in Figure 2-14shown in the program statement in Figure 2-14

► As an alternative to the long string of ifs shown in Figure As an alternative to the long string of ifs shown in Figure 2-14, you can use the 2-14, you can use the switch statementswitch statement

► The switch can contain any number of cases in any orderThe switch can contain any number of cases in any order

2

Page 39: 01 c++ Intro.ppt

The if OperatorThe if Operator

► Another alternative to the if statement involves Another alternative to the if statement involves the the if operatorif operator (also called the (also called the conditional conditional operatoroperator), which is represented by a question ), which is represented by a question mark (?)mark (?)

► E.g. E.g.

► cout<<(driveAge<26)?”The driver is under cout<<(driveAge<26)?”The driver is under 26”:”The driver is at least 26”;26”:”The driver is at least 26”;

► The if operator provides a concise way to express The if operator provides a concise way to express two alternativestwo alternatives

► The conditional operator is an example of a The conditional operator is an example of a ternary operator, one that takes three operands ternary operator, one that takes three operands instead of just one or twoinstead of just one or two

2

Page 40: 01 c++ Intro.ppt

Logical AND and Logical ORLogical AND and Logical OR

► In some programming situations, two or more In some programming situations, two or more conditions must be true to initiate an actionconditions must be true to initiate an action

► Figure 2-16 works correctly using a Figure 2-16 works correctly using a nested ifnested if—that is, one if statement within another if —that is, one if statement within another if statementstatement

► If numVisits is not greater than 5, the If numVisits is not greater than 5, the statement is finished—the second comparison statement is finished—the second comparison does not even take placedoes not even take place

► Alternatively, a Alternatively, a logical AND (&&)logical AND (&&) can be used, can be used, as shown in Figure 2-17as shown in Figure 2-17

2

Page 41: 01 c++ Intro.ppt

Logical AND and Logical ORLogical AND and Logical OR2

Page 42: 01 c++ Intro.ppt

Logical AND and Logical ORLogical AND and Logical OR

► A logical AND is a compound boolean expression A logical AND is a compound boolean expression in which two conditions must be true for the in which two conditions must be true for the entire expression to evaluate as trueentire expression to evaluate as true

► Table 2-3 shows how an expression using && is Table 2-3 shows how an expression using && is evaluated evaluated

► An entire expression is true only when the An entire expression is true only when the expression on each side of the && is trueexpression on each side of the && is true

2

Page 43: 01 c++ Intro.ppt

Using the Logical ORUsing the Logical OR

► In certain programming situations, only one In certain programming situations, only one of two alternatives must be true for some of two alternatives must be true for some action to take placeaction to take place

► A logical OR (||) could also be usedA logical OR (||) could also be used► A logical OR is a compound boolean A logical OR is a compound boolean

expression in which either of two conditions expression in which either of two conditions must be true for the entire expression to must be true for the entire expression to evaluate as trueevaluate as true

► Table 2-4 shows how C++ evaluates any Table 2-4 shows how C++ evaluates any expression that uses the || operatorexpression that uses the || operator

2

Page 44: 01 c++ Intro.ppt

Using the Logical ORUsing the Logical OR2

Page 45: 01 c++ Intro.ppt

Using the Logical ORUsing the Logical OR

► When either expression1 or expression2 is true When either expression1 or expression2 is true (or both are true), the entire expression is true(or both are true), the entire expression is true

► On pages 53 and 54 of the textbook, perform On pages 53 and 54 of the textbook, perform the steps so you can write a program that the steps so you can write a program that makes several decisionsmakes several decisions

2

Page 46: 01 c++ Intro.ppt

A Typical Run of the A Typical Run of the Decisions.cpp ProgramDecisions.cpp Program

2

Page 47: 01 c++ Intro.ppt

The while LoopThe while Loop

► Loops provide a mechanism with which to Loops provide a mechanism with which to perform statements repeatedly and, just as perform statements repeatedly and, just as important, to stop that performance when important, to stop that performance when warrantedwarrantedwhile (boolean expression)while (boolean expression)

statement;statement;

► In C++, the while statement can be used to In C++, the while statement can be used to looploop

► The variable count, shown in the program in The variable count, shown in the program in Figure 2-21, is often called a Figure 2-21, is often called a loop-control loop-control variablevariable, because it is the value of count that , because it is the value of count that controls whether the loop body continues to controls whether the loop body continues to executeexecute

2

Page 48: 01 c++ Intro.ppt

The while LoopThe while Loop2

Page 49: 01 c++ Intro.ppt

The while LoopThe while Loop2

Page 50: 01 c++ Intro.ppt

The for StatementThe for Statement

► The The for statementfor statement represents an alternative to the represents an alternative to the while statementwhile statement

► It is most often used in a It is most often used in a definite loopdefinite loop, or a loop , or a loop that must execute a definite number of timesthat must execute a definite number of times

► It takes the form:It takes the form:for (for (initialize; evaluate; alter)initialize; evaluate; alter)

statementstatement;;

2