You are on page 1of 50

Revision C++

Prepared By: Chandni Agarwal

1 The Task of Programming


y Programming a computer involves writing instructions

y y

y y

that enable a computer to carry out a single task or a group of tasks A computer programming language requires learning both vocabulary and syntax Programmers use many different programming languages, including BASIC, Pascal, COBOL, RPG, and C++ The rules of any language make up its syntax Machine language is the language that computers can understand; it consists of 1s and 0s

1 The Task of Programming


y A translator (called either a compiler or an

interpreter) checks your program for syntax errors y A logical error occurs when you use a statement that, although syntactically correct, doesnt do what you intended y You run a program by issuing a command to execute the program statements y You test a program by using sample data to determine whether the program results are correct

1 Programming Universals
y All programming languages provide methods for

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


y Similarly, all programming languages provide methods

for sending input into the computer program so that it can be manipulated y In addition, all programming languages provide for naming locations in computer memory y These locations commonly are called variables (or attributes)

1 Programming Universals
y Ideally, variables have meaningful names,

although no programming language actually requires that they meet this standard y A variable may have only one value at a time, but it is the ability of memory variables to change in value that makes computers and programming worthwhile y In many computer programming languages, including C++, variables must be explicitly declared, or given a data type as well as a name, before they can be used

1 Programming Universals
y The type determines what kind of values may be

stored in a variable y Most computer languages allow at least two types: one for numbers and one for characters y Numeric variables hold values like 13 or -6 y Character variables hold values like A or & y Many languages include even more specialized types, such as integer (for storing whole numbers) or floating point (for storing numbers with decimal places)

1 Procedural Programming
y Procedural programs consist of a series of steps or

procedures that take place one after the other


y 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 many

programming languages, such as COBOL, BASIC, FORTRAN, and RPG


y You can also write procedural programs in C++

1 A main( ) Function in C++


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

in a function y Every function consists of two parts:


y A function header is the initial line of code in a C++ which

always has three parts:


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

the function receives


y A function body

1 Creating a main( ) Function


y A C++ program may contain many functions,

but every C++ program contains at least one function, and that function is called main( )
y If the main function does not pass values to

other programs or receives values from outside the program, then main( ) receives and returns a void type
y The body of every function in a C++ program is

contained in curly braces, also known as curly brackets

1 Creating a main( ) Function

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

several statements must occur in a loop y In such a case, the statements have their own set of opening and closing braces within the main braces, forming a block

1 Working with Variables


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 or underscore


y No spaces or other special characters are allowed within

a C++ variable name


y Every programming language contains a few vocabulary

words, or keywords, that you need in order to use the language

Common C++ Keywords

1 Working with Variables


y A C++ keyword cannot be used as a variable name y Each named variable must have a type y C++ supports three simple types: y Integer Floating point
Character

y An integer is a whole number, either positive or negative y An integer value may be stored in an integer variable

declared with the keyword int y You can also declare an integer variable using short int and long int

1 Working with Variables


y Real or floating-point numbers are numbers that

y y y y

include decimal positions, such as 98.6, 1000.00002, and 3.85 They may be stored in variables with type float, double, and long double Characters may be stored in variables declared with the keyword char A character may hold any single symbol in the ASCII character set Often it contains a letter of the alphabet, but it could include a space, digit, punctuation mark, arithmetic symbol, or other special symbol

Working with Variables


y In C++, a character value is always expressed in single y y y

quotes, such as A or & To declare a variable, you list its type and its name In addition, a variable declaration is a C++ statement, so it must end with a semicolon If you write a function that contains variables of diverse types, each variable must be declared in a statement of its own If you want to declare two or more variables of the same type, you may declare them in the same statement

1 Working with Variables


y Explicitly stating the value of a variable is called

assignment, and is achieved with the assignment operator = y The variable finalScore is declared and assigned a value at the same time y Assigning a value to a variable upon creation is often referred to as initializing the variable

1 The const Qualifier


y 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_WAGE that can be used like a variable, but cannot be changed during a program

1 Creating Comments
y Comments are statements that do not affect the

compiling or running of a program


y Comments are simply explanatory remarks that the

programmer includes in a program to clarify what is taking place


y These remarks are useful to later program users because

they might help explain the intent of a particular statement or the purpose of the entire program
y C++ supports both line comments and block comments

1 Creating Comments
y A line comment begins with two slashes (//) and continues

to the end of the line on which it is placed y A block comment begins with a single slash and an asterisk (/*) and ends with an asterisk and a slash (*/); it might be contained on a single line or continued across many lines

1 Using Libraries and


Preprocessor Directives
y Header files are files that contain predefined values and y y

y y

routines, such as sqrt( ) Their filenames usually end in .h In order for your C++ program to use these predefined routines, you must include a preprocessor directive, a statement that tells the compiler what to do before compiling the program In C++, all preprocessor directives begin with a pound sign (#), which is also called an octothorp The #include preprocessor directive tells the compiler to include a file as part of the finished product

2 C++ Binary Arithmetic Operators


y Often after data values are input, you perform calculations

with them y C++ provides five simple arithmetic operators for creating arithmetic expressions:
y addition (+) y multiplication (*) y modulus (%)

subtraction (-) division (/)

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.5 y The results of an arithmetic operation can be stored in memory

2 C++ Binary Arithmetic Operators

2 C++ Binary Arithmetic Operatorsto a result y In Figure 2-2, each operation is assigned
variable of the correct type
y The expression a + b has an integer result because

both a and b are integers, not because their sum is stored in the intResult variable
y If the program contained the statement

doubleResult = a+b; the expression a+b would still have an integer value, but the value would be cast, or transformed, into a double when the sum is assigned to doubleResult

2 C++ Binary Arithmetic Operators


y The automatic cast that occurs when you assign a value of

one type to another is called an implicit cast y The modulus operator (%), which gives the remainder of integer division, can be used only with integers y When more than one arithmetic operator is included in an expression, then multiplication, division, and modulus operations always occur before addition or subtraction y Multiplication, division, and modulus are said to have higher precedence

2 Shortcut Arithmetic Operators


y C++ employs several shortcut operators y When you add two variable values and store the result in

a third variable, the expression takes the form result= firstValue + secondValue
y When you use an expression like this, both

firstValue and secondValue retain their original values; only the result is altered
y When you want to increase a value, the expression takes

the form firstValue = firstValue + secondValue

2 Shortcut Arithmetic Operators


y C++ provides the -= operator for subtracting one value

from another, the *= operator for multiplying one value by another, and the /= operator for dividing one value by another
y As with the += operator, you must not insert a space

within the subtraction, multiplication, or division shortcut operators


y The options shown in Figure 2-4 means replace the

current value of count with the value that is 1 more than count, or simply increment count

2 Shortcut Arithmetic Operators


y As you might expect, you can use two minus signs (--)

before or after a variable to decrement it

2 Shortcut Arithmetic Operators


y The prefix and postfix increment and decrement

operators are examples of unary operators


y Unary operators are those that require only one

operand, such as num in the expression ++num


y When an expression includes a prefix operator, the

mathematical operation takes place before the expression is evaluated


y When an expression includes a postfix operator, the

mathematical operation takes place after the expression is evaluated

2 Shortcut Arithmetic Operators


y The difference between the results produced by the

prefix and postfix operators can be subtle, but the outcome of a program can vary greatly depending on which increment operator you use in an expression

2
y A boolean expression is one that evaluates as true or y y y y y y

Evaluating Boolean Expressions

false All false relational expressions are evaluated as 0 Thus, an expression such as 2>9 has the value 0 You can prove that 2>9 is evaluated as 0 by entering the statement code <<(2>9); into a C++ program A 0 appears on output All true relational expressions are evaluated as 1 Thus, the expression 9>2 has the value 1

2 Evaluating Boolean Expressions


y The unary operator ! Means not, and essentially reverses the

true/false value of an expression

2 Selection
y Computer programs seem smart because of their

ability to use selections or make decisions


y C++ lets you perform selections in a number of

ways:
y The if statement y The switch statement y The if operator y Logical AND and Logical OR

2 Some Sample Selection Statements within a C++ Program

2 The if Statement

y If the execution of more than one statement depends on the selection, then

the statements must be blocked with curly braces as shown in the code segment in Figure 2-8

2 The if Statement

2 Multiple Executable Statement in an if-else

2 The if Statement
y Any C++ expression can be evaluated as part of an if

statement

2 The switch Statement


y When you want to create different outcomes depending on

specific values of a variable, you can use a series of ifs shown in the 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 The if Operator
y Another alternative to the if statement involves the if

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

y E.g. y cout<<(driveAge<26)?The driver is under 26:The driver is

at least 26;

y The if operator provides a concise way to express two

alternatives

y The conditional operator is an example of a ternary operator,

one that takes three operands instead of just one or two

2 Logical AND and Logical OR


y In some programming situations, two or more

conditions must be true to initiate an action


y Figure 2-16 works correctly using a nested ifthat is,

one if statement within another if statement


y If numVisits is not greater than 5, the statement is

finishedthe second comparison does not even take place


y Alternatively, a logical AND (&&) can be used, as shown

in Figure 2-17

2 Logical AND and Logical OR

2 Logical AND and Logical OR


y A logical AND is a compound boolean expression in which two

conditions must be true for the entire expression to evaluate as true y Table 2-3 shows how an expression using && is evaluated y An entire expression is true only when the expression on each side of the && is true

2 Using the Logical OR


y In certain programming situations, only one of two

alternatives must be true for some action to take place y A logical OR (||) could also be used y A logical OR is a compound boolean expression in which either of two conditions must be true for the entire expression to evaluate as true y Table 2-4 shows how C++ evaluates any expression that uses the || operator

2 Using the Logical OR

2 Using the Logical OR

y When either expression1 or expression2 is true (or both are

true), the entire expression is true y On pages 53 and 54 of the textbook, perform the steps so you can write a program that makes several decisions

2 A Typical Run of the Decisions.cpp Program

2 The while Loop


y Loops provide a mechanism with which to perform

statements repeatedly and, just as important, to stop that performance when warranted
while (boolean expression) statement;

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

often called a loop-control variable, because it is the value of count that controls whether the loop body continues to execute

2 The while Loop

2 The while Loop

2 The for Statement


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

definite number of times y It takes the form:


for (initialize; evaluate; alter) statement;

You might also like