Revision c++

Embed Size (px)

Citation preview

  • 8/6/2019 Revision c++

    1/50

    Prepared By:Chandni Agarwal

    Revision C++

  • 8/6/2019 Revision c++

    2/50

    Th e Ta sk of Progr amm ing

    y Programming a computer involves writing instructionsthat enable a computer to carry out a single task or agroup of tasks

    y

    A computer programming language requires learningboth vocabulary and syntaxy Programmers use many different programming

    languages, including BASIC, Pascal, COBOL, RPG, andC++

    y The rules of any language make up its syntaxy Machine language is the language that computers can

    understand; it consists of 1s and 0s

    1

  • 8/6/2019 Revision c++

    3/50

    Th e Ta sk of Progr amm ing y A translator (called either a compiler or an

    interpreter) checks your program for syntaxerrors

    y A logical error occurs when you use a statementthat, although syntactically correct, doesnt dowhat you intended

    y You run a program by issuing a command toexecute the program statements

    y

    You test a program by using sample data todetermine whether the program results arecorrect

    1

  • 8/6/2019 Revision c++

    4/50

    Progr amm ing Univers al sy All programming languages provide methods for

    directing output to a desired object, such as a monitorscreen, printer or file

    y Similarly, all programming languages provide methodsfor sending input into the computer program so that itcan be manipulated

    y In addition, all programming languages provide fornaming locations in computer memory

    y

    These locations commonly are called variables (orattributes )

    1

  • 8/6/2019 Revision c++

    5/50

    Progr amm ing Univers al sy Ideally, variables have meaningful names,

    although no programming language actuallyrequires that they meet this standard

    y A variable may have only one value at a time, butit is the ability of memory variables to change invalue that makes computers and programmingworthwhile

    y In many computer programming languages,

    including C++, variables must be explicitlydeclared , or given a data type as well as a name,before they can be used

    1

  • 8/6/2019 Revision c++

    6/50

    Progr amm ing Univers al sy The type determines what kind of values may be

    stored in a variabley Most computer languages allow at least two

    types: one for numbers and one for charactersy Numeric variables hold values like 13 or -6y Character variables hold values like A or &y Many languages include even more specialized

    types, such as integer (for storing wholenumbers) or floating point (for storing numberswith decimal places)

    1

  • 8/6/2019 Revision c++

    7/50

    Procedur al Progr amm ing y Procedural programs consist of a series of steps or

    procedures that take place one after the othery The programmer determines the exact conditions under

    which a procedure takes place, how often it takes place,and when the program stops

    y Programmers write procedural programs in manyprogramming languages, such as COBOL, BASIC,FORTRAN, and RPG

    y You can also write procedural programs in C++

    1

  • 8/6/2019 Revision c++

    8/50

    A main( ) Function in C++

    y C++ programs consist of modules called functionsy Every statement within every C++ program is contained

    in a functiony Every function consists of two parts:

    y A function header is the initial line of code in a C++ whichalways has three parts:

    y Return type of the functiony Name of the functiony Types and names of any variables enclosed in parentheses, and which

    the function receivesy A function body

    1

  • 8/6/2019 Revision c++

    9/50

    Cre a ting a main( ) Functiony A C++ program may contain many functions,

    but every C++ program contains at least onefunction, and that function is called main( )

    y If the main function does not pass values toother programs or receives values from outsidethe program, then main( ) receives and returns avoid type

    y The body of every function in a C++ program iscontained in curly braces, also known as curlybrackets

    1

  • 8/6/2019 Revision c++

    10/50

    Cre a ting a main( ) Function

    y Every complete C++ statement ends with a semicolony Often several statements must be grouped together, as when

    several statements must occur in a loopy

    In such a case, the statements have their own set of openingand closing braces within the main braces, forming a block

    1

  • 8/6/2019 Revision c++

    11/50

    W orking wit h Va riabl es

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

    y Names of C++ variables can include letters, numbers,

    and underscores, but must begin with a letter orunderscore

    y No spaces or other special characters are allowed withina C++ variable name

    y Every programming language contains a few vocabularywords, or keywords , that you need in order to use thelanguage

    1

  • 8/6/2019 Revision c++

    12/50

    Comm on C++ Keywords

  • 8/6/2019 Revision c++

    13/50

    W orking wit h Va riabl es

    y A C++ keyword cannot be used as a variable namey Each named variable must have a typey C++ supports three simple types:

    y Integer Floating point Charactery An integer is a whole number, either positive or negativey An integer value may be stored in an integer variable

    declared with the keyword inty

    You can also declare an integer variable using short intand long int

    1

  • 8/6/2019 Revision c++

    14/50

    W orking wit h Va riabl es

    y Real or floating-point numbers are numbers thatinclude decimal positions, such as 98.6, 1000.00002, and -3.85

    y They may be stored in variables with type float, double ,and long double

    y Characters may be stored in variables declared with thekeyword char

    y A character may hold any single symbol in the ASCII

    character sety Often it contains a letter of the alphabet, but it couldinclude a space, digit, punctuation mark, arithmeticsymbol, or other special symbol

    1

  • 8/6/2019 Revision c++

    15/50

    W orking wit h Va riabl es

    y In C++, a character value is always expressed in singlequotes, such as A or &

    y To declare a variable, you list its type and its namey

    In addition, a variable declaration is a C++ statement, so itmust end with a semicolon

    y If you write a function that contains variables of diversetypes, each variable must be declared in a statement of itsown

    y If you want to declare two or more variables of the sametype, you may declare them in the same statement

  • 8/6/2019 Revision c++

    16/50

    W orking wit h Va riabl esy Explicitly stating the value of a variable is called

    assignment , and is achieved with the assignmentoperator =

    y The variable finalScore is declared and assigned a value

    at the same timey Assigning a value to a variable upon creation is often

    referred to as initializing the variable

    1

  • 8/6/2019 Revision c++

    17/50

    Th e const Qu al ifiery A variable that does not change in a program

    should not be declared as a variable

    y Instead, it should be a constant

    y The statement const double MINIMUM_WAGE =5.75; declares a constant named MINIMUM_WAGEthat can be used like a variable, but cannot bechanged during a program

    1

  • 8/6/2019 Revision c++

    18/50

    Cre a ting Co mm ents

    y Comments are statements that do not affect thecompiling or running of a program

    y Comments are simply explanatory remarks that theprogrammer includes in a program to clarify what istaking place

    y These remarks are useful to later program users becausethey might help explain the intent of a particular

    statement or the purpose of the entire programy C++ supports both line comments and block comments

    1

  • 8/6/2019 Revision c++

    19/50

  • 8/6/2019 Revision c++

    20/50

    Using Li b ra ries a ndPreprocessor Directives

    y H eader files are files that contain predefined values androutines, such as sqrt( )

    y Their filenames usually end in .hy In order for your C++ program to use these predefined

    routines, you must include a preprocessor directive , astatement that tells the compiler what to do beforecompiling the program

    y In C++, all preprocessor directives begin with a pound

    sign (#), which is also called an octothorpy The #include preprocessor directive tells the compilerto include a file as part of the finished product

    1

  • 8/6/2019 Revision c++

    21/50

    C++ Bin a ry Arithm etic Oper a tors

    y Often after data values are input, you perform calculationswith them

    y C++ provides five simple arithmetic operators for creatingarithmetic expressions:

    y addition (+) subtraction (-)y multiplication (*) division (/)y modulus (%)

    y Each of these arithmetic operators is a binary operator;

    each takes two operands, one on each side of the operator,as in 12 + 9 or 16.2*1.5y The results of an arithmetic operation can be stored in

    memory

    2

  • 8/6/2019 Revision c++

    22/50

    C++ Bin a ry Arithm etic Oper a tors

    2

  • 8/6/2019 Revision c++

    23/50

    C++ Bin a ry Arithm etic Oper a torsy In Figure 2-2, each operation is assigned to a resultvariable of the correct type

    y The expression a + b has an integer result becauseboth a and b are integers, not because their sum is storedin the intResult variable

    y If the program contained the statementdo ubleResult = a+b; the expression a+b wouldstill have an integer value, but the value would be cast ,or transformed, into a double when the sum is assignedto do ubleResult

    2

  • 8/6/2019 Revision c++

    24/50

    C++ Bin a ry Arithm etic Oper a torsy The automatic cast that occurs when you assign a value of

    one type to another is called an implicit casty The modulus operator (%), which gives the remainder of

    integer division, can be used only with integersy When more than one arithmetic operator is included in an

    expression, then multiplication, division, and modulusoperations always occur before addition or subtraction

    y Multiplication, division, and modulus are said to havehigher precedence

    2

  • 8/6/2019 Revision c++

    25/50

    S h ortcut Arithm etic Oper a torsy C++ employs several shortcut operatorsy When you add two variable values and store the result in

    a third variable, the expression takes the form r esult=fi r stValue + sec o n d Value

    y When you use an expression like this, bothfi r stValue and sec o n d Value retain their originalvalues; only the result is altered

    y

    When you want to increase a value, the expression takesthe form fi r stValue = fi r stValue +sec o n d Value

    2

  • 8/6/2019 Revision c++

    26/50

    S hortcut

    Arit

    hmetic Oper

    ators

    y C++ provides the -= operator for subtracting one valuefrom another, the *= operator for multiplying one valueby another, and the /= operator for dividing one value

    by anothery As with the += operator, you must not insert a space

    within the subtraction, multiplication, or divisionshortcut operators

    y The options shown in Figure 2-4 means replace thecurrent value of count with the value that is 1 more thancount, or simply increment count

    2

  • 8/6/2019 Revision c++

    27/50

    S hortcut

    Arit

    hmetic Oper

    ators

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

    2

  • 8/6/2019 Revision c++

    28/50

    S h ortcut Arithm etic Oper a torsy The prefix and postfix increment and decrement

    operators are examples of unary operatorsy Unary operators are those that require only one

    operand, such as num in the expression ++numy When an expression includes a prefix operator, the

    mathematical operation takes place before theexpression is evaluated

    y When an expression includes a postfix operator, themathematical operation takes place after the expressionis evaluated

    2

  • 8/6/2019 Revision c++

    29/50

    S h ortcut Arithm etic Oper a torsy The difference between the results produced by the

    prefix and postfix operators can be subtle, but theoutcome of a program can vary greatly depending

    on which increment operator you use in anexpression

    2

  • 8/6/2019 Revision c++

    30/50

    E val u a ting Boo le a n Ex pressionsy A boolean expression is one that evaluates as true orfalse

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

    statement code 2 has the value 1

    2

  • 8/6/2019 Revision c++

    31/50

    E val u a ting Boo le a n Ex pressionsy The unary operator ! Means not, and essentially reverses the

    true/false value of an expression

    2

  • 8/6/2019 Revision c++

    32/50

    S e lectiony Computer programs seem smart because of their

    ability to use selections or make decisionsy C++ lets you perform selections in a number of

    ways:y The if statementy The switch statementy The if operatory Logical AND and Logical OR

    2

  • 8/6/2019 Revision c++

    33/50

    S om e S am p le S e lectionS ta te m ents wit h in a C++ Progr am

    2

  • 8/6/2019 Revision c++

    34/50

    Th e if S ta te m ent

    y If the execution of more than one statement depends on the selection, thenthe statements must be blocked with curly braces as shown in the codesegment in Figure 2-8

    2

  • 8/6/2019 Revision c++

    35/50

    Th e if S ta te m ent

    2

  • 8/6/2019 Revision c++

    36/50

    M u ltip le Ex ecut abl e S ta te m entin a n if-e lse

    2

  • 8/6/2019 Revision c++

    37/50

    Th e if S ta te m ent

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

    2

  • 8/6/2019 Revision c++

    38/50

    Th e switc h S ta te m enty When you want to create different outcomes depending on

    specific values of a variable, you can use a series of ifs shown inthe program statement in Figure 2-14

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

    y The switch can contain any number of cases in any order

    2

  • 8/6/2019 Revision c++

    39/50

    Th e if Oper a tory Another alternative to the if statement involves the if

    operator (also called the conditional operator ), which isrepresented by a question mark (?)

    y E.g.y

    cout

  • 8/6/2019 Revision c++

    40/50

    Logic al AN D a nd Logic al OR

    y In some programming situations, two or moreconditions must be true to initiate an action

    y Figure 2-16 works correctly using a nested if that is,one if statement within another if statement

    y If numVisits is not greater than 5, the statement isfinishedthe second comparison does not even takeplace

    y Alternatively, a logical AND (&&) can be used, as shownin Figure 2-17

    2

  • 8/6/2019 Revision c++

    41/50

    Logic al AN D a nd Logic al OR

    2

  • 8/6/2019 Revision c++

    42/50

    Logic al AN D a nd Logic al ORy A logical AND is a compound boolean expression in which two

    conditions must be true for the entire expression to evaluate astrue

    y Table 2-3 shows how an expression using && is evaluatedy An entire expression is true only when the expression on each

    side of the && is true

    2

  • 8/6/2019 Revision c++

    43/50

    Using t h e Logic al ORy In certain programming situations, only one of two

    alternatives must be true for some action to take placey A logical OR (||) could also be usedy A logical OR is a compound boolean expression in

    which either of two conditions must be true for theentire expression to evaluate as true

    y Table 2-4 shows how C++ evaluates any expressionthat uses the || operator

    2

  • 8/6/2019 Revision c++

    44/50

    Using t h e Logic al OR

    2

  • 8/6/2019 Revision c++

    45/50

  • 8/6/2019 Revision c++

    46/50

    A Typic al Run of t h eDecisions.cpp Progr am

    2

  • 8/6/2019 Revision c++

    47/50

    Th e w h ile Loop

    y Loops provide a mechanism with which to performstatements repeatedly and, just as important, to stop thatperformance when warrantedw hile (boolean expression)

    statement;y In C++, the while statement can be used to loopy The variable count, shown in the program in Figure 2-21, is

    often called a loop-control variable , because it is the valueof count that controls whether the loop body continues toexecute

    2

  • 8/6/2019 Revision c++

    48/50

    Th e w h ile Loop

    2

  • 8/6/2019 Revision c++

    49/50

    Th e w h ile Loop

    2

  • 8/6/2019 Revision c++

    50/50

    Th e for S ta te m ent

    y The for statement represents an alternative to the while statementy It is most often used in a definite loop , or a loop that must execute a

    definite number of timesy It takes the form:

    for ( initialize; evaluate; alter)statement ;

    2