1
1
A
A Review
Review of Programming and C++
of Programming and C++
COSC1567
COSC1567
C++ Programming
C++ Programming
Lecture 1
2
2
The Task of Programming
The Task of Programming
• Programming a computer involves writing
instructions 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
3
3
The Task of Programming
The Task of Programming
• A translator (called either a compiler or an
interpreter) checks your program for syntax
errors
• A logical error occurs when you use a
statement that, although syntactically
correct, doesn’t do what you intended
• You run a program by issuing a command to
execute the program statements
• You test a program by using sample data to
determine whether the program results are
correct
4
4
Programming Universals
Programming Universals
• All programming languages provide methods for
directing output to a desired object, such as a
monitor screen, printer or file
• Similarly, all programming languages provide
methods for sending input into the computer
program so that it can be manipulated
• In addition, all programming languages provide for
naming locations in computer memory
• These locations commonly are called variables (or
attributes)
5
5
Programming Universals
Programming Universals
• Ideally, variables have meaningful names,
although no programming language actually
requires that they meet this standard
• 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
• 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
6
6
Programming Universals
Programming Universals
• The type determines what kind of values may
be stored in a variable
• Most computer languages allow at least two
types: one for numbers and one for
characters
• Numeric variables hold values like 13 or -6
• Character variables hold values like ‘A’ or ‘&’
• Many languages include even more
specialized types, such as integer (for
storing whole numbers) or floating point (for
storing numbers with decimal places)
7
7
Procedural Programming
Procedural Programming
• Procedural programs consist of a series of steps or
procedures that take place one after the other
• The programmer determines the exact conditions
under which a procedure takes place, how often it
takes place, and when the program stops
• Programmers write procedural programs in many
programming languages, such as COBOL, BASIC,
FORTRAN, and RPG
• You can also write procedural programs in C++
8
8
A
A main( )
main( ) Function in C++
Function in C++
• C++ programs consist of modules called
functions
• Every statement within every C++ program is
contained in a function
• Every function consists of two parts:
– A function header is the initial line of code in a C++
which always has three parts:
• Return type of the function
• Name of the function
• Types and names of any variables enclosed in
parentheses, and which the function receives
– A function body
9
9
Creating a
Creating a main( )
main( ) Function
Function
• A C++ program may contain many functions,
but every C++ program contains at least one
function, and that function is called main( )
• 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
• The body of every function in a C++ program
is contained in curly braces, also known as
curly brackets
10
10
Creating a
Creating a main( )
main( ) Function
Function
• Every complete C++ statement ends with a
semicolon
• Often several statements must be grouped together,
as when several statements must occur in a loop
• In such a case, the statements have their own set of
opening and closing braces within the main braces,
forming a block
11
11
Working with Variables
Working with Variables
• In C++, you must name and give a type to
variables (sometimes called identifiers) before
you can use them
• Names of C++ variables can include letters,
numbers, and underscores, but must begin with
a letter or underscore
• No spaces or other special characters are
allowed within a C++ variable name
• Every programming language contains a few
vocabulary words, or keywords, that you need
in order to use the language
12
12
Common C++ Keywords
Common C++ Keywords
13
13
Working with Variables
Working with Variables
• A C++ keyword cannot be used as a variable
name
• Each named variable must have a type
• C++ supports three simple types:
– Integer — Floating point — Character
• An integer is a whole number, either positive or
negative
• An integer value may be stored in an integer
variable declared with the keyword int
• You can also declare an integer variable using
short int and long int
14
14
Working with Variables
Working with Variables
• Real or floating-point numbers are numbers that
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
15
15
Working with Variables
Working with Variables
• In C++, a character value is always expressed in
single 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
16
16
Working with Variables
Working with Variables
• Explicitly stating the value of a variable is called
assignment, and is achieved with the assignment
operator =
• The variable finalScore is declared and assigned a
value at the same time
• Assigning a value to a variable upon creation is
often referred to as initializing the variable
17
17
The const Qualifier
The const Qualifier
• A variable that does not change in a program
should not be declared as a variable
• Instead, it should be a constant
• 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
18
18
Creating Comments
Creating Comments
• Comments are statements that do not affect the
compiling or running of a program
• Comments are simply explanatory remarks that
the programmer includes in a program to clarify
what is taking place
• 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
• C++ supports both line comments and block
comments
19
19
Creating Comments
Creating Comments
• A line comment begins with two slashes (//) and
continues to the end of the line on which it is placed
• 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
20
20
Using Libraries and
Using Libraries and
Preprocessor Directives
Preprocessor Directives
• Header files are files that contain predefined
values and 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
21
21
C++ Binary Arithmetic Operators
C++ Binary Arithmetic Operators
• Often after data values are input, you perform
calculations with them
• C++ provides five simple arithmetic operators for
creating arithmetic expressions:
– addition (+) – subtraction (-)
– multiplication (*) – division (/)
– modulus (%)
• 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
• The results of an arithmetic operation can be stored
in memory
2
22
22
C++ Binary Arithmetic Operators
C++ Binary Arithmetic Operators
23
23
C++ Binary Arithmetic Operators
C++ Binary Arithmetic Operators
• In Figure 2-2, each operation is assigned to a result
variable of the correct type
• 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
• 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
24
24
C++ Binary Arithmetic Operators
C++ Binary Arithmetic Operators
• The automatic cast that occurs when you assign a
value of one type to another is called an implicit
cast
• The modulus operator (%), which gives the
remainder of integer division, can be used only with
integers
• When more than one arithmetic operator is included
in an expression, then multiplication, division, and
modulus operations always occur before addition or
subtraction
• Multiplication, division, and modulus are said to
have higher precedence
25
25
Shortcut Arithmetic Operators
Shortcut Arithmetic Operators
• C++ employs several shortcut operators
• When you add two variable values and store the
result in a third variable, the expression takes the
form result= firstValue + secondValue
• When you use an expression like this, both
firstValue and secondValue retain their original
values; only the result is altered
• When you want to increase a value, the expression
takes the form firstValue = firstValue +
secondValue
26
26
Shortcut Arithmetic Operators
Shortcut Arithmetic Operators
• 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
• As with the += operator, you must not insert a
space within the subtraction, multiplication, or
division shortcut operators
• 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
27
27
Shortcut Arithmetic Operators
Shortcut Arithmetic Operators
• As you might expect, you can use two minus
signs (--) before or after a variable to decrement it
28
28
Shortcut Arithmetic Operators
Shortcut Arithmetic Operators
• The prefix and postfix increment and decrement
operators are examples of unary operators
• Unary operators are those that require only one
operand, such as num in the expression ++num
• When an expression includes a prefix operator, the
mathematical operation takes place before the
expression is evaluated
• When an expression includes a postfix operator, the
mathematical operation takes place after the
expression is evaluated
29
29
Shortcut Arithmetic Operators
Shortcut Arithmetic Operators
• 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
30
30
Evaluating Boolean Expressions
Evaluating Boolean Expressions
• A boolean expression is one that evaluates as true
or 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 cout<<(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
31
31
Evaluating Boolean Expressions
Evaluating Boolean Expressions
• The unary operator ! Means not, and essentially reverses the
true/false value of an expression
32
32
Selection
Selection
• Computer programs seem smart because of
their ability to use selections or make decisions
• C++ lets you perform selections in a number of
ways:
– The if statement
– The switch statement
– The if operator
– Logical AND and Logical OR
33
33
Some Sample Selection
Some Sample Selection
Statements within a C++ Program
Statements within a C++ Program
34
34
The if
The if Statement
Statement
• 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
35
35
The if
The if Statement
Statement
36
36
Multiple Executable Statement
Multiple Executable Statement
in an if-else
in an if-else
37
37
The if
The if Statement
Statement
• Any C++ expression can be evaluated as part of
an if statement
38
38
The switch Statement
The switch Statement
• 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
• As an alternative to the long string of ifs shown in Figure
2-14, you can use the switch statement
• The switch can contain any number of cases in any order
39
39
The if Operator
The if Operator (
(NEW!
NEW! )
)
• Another alternative to the if statement involves the if
operator (also called the conditional operator), which is
represented by a question mark (?)
• E.g.
• cout<<(driveAge<26)?”The driver is under 26”:”The
driver is at least 26”;
• The if operator provides a concise way to express two
alternatives
• The conditional operator is an example of a ternary
operator, one that takes three operands instead of just
one or two
Ex1-2.cpp
40
40
Logical AND and Logical OR
Logical AND and Logical OR
• In some programming situations, two or more
conditions must be true to initiate an action
• Figure 2-16 works correctly using a nested if—that
is, one if statement within another if statement
• If numVisits is not greater than 5, the statement is
finished—the second comparison does not even
take place
• Alternatively, a logical AND (&&) can be used, as
shown in Figure 2-17
41
41
Logical AND and Logical OR
Logical AND and Logical OR
42
42
Logical AND and Logical OR
Logical AND and Logical OR
• A logical AND is a compound boolean expression in which
two conditions must be true for the entire expression to
evaluate as true
• Table 2-3 shows how an expression using && is evaluated
• An entire expression is true only when the expression on
each side of the && is true
43
43
Using the Logical OR
Using the Logical OR
• In certain programming situations, only one of two
alternatives must be true for some action to take
place
• A logical OR (||) could also be used
• 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
• Table 2-4 shows how C++ evaluates any
expression that uses the || operator
44
44
Using the Logical OR
Using the Logical OR
45
45
Using the Logical OR
Using the Logical OR
• When either expression1 or expression2 is true (or both
are true), the entire expression is true
• On pages 53 and 54 of the textbook, perform the steps
so you can write a program that makes several
decisions
46
46
A Typical Run of the
A Typical Run of the
Decisions.cpp Program
Decisions.cpp Program
47
47
The while Loop
The while Loop
• Loops provide a mechanism with which to perform
statements repeatedly and, just as important, to
stop that performance when warranted
while (boolean expression)
statement;
• In C++, the while statement can be used to loop
• 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
48
48
The while Loop
The while Loop
49
49
The while Loop
The while Loop
50
50
The for Statement
The for Statement
• The for statement represents an alternative to the while
statement
• It is most often used in a definite loop, or a loop that must
execute a definite number of times
• It takes the form:
for (initialize; evaluate; alter)
statement;
Ex1-3.cpp
More examples
More examples
• Ex1-6.cpp
• Ex1-7.cpp
51
51
52
52
Summary
Summary
• C++ provides five simple binary arithmetic
operators for creating arithmetic expressions:
addition (+), subtraction (-), multiplication (*),
division (/), and modulus (%)
• When you mix data types in a binary arithmetic
expression, the result is always the same type as
the type that takes the most memory to store
• C++ employs several shortcut operators for
arithmetic, such as +=, prefix, ++, and postfix ++
• A boolean expression is one that evaluates as true
or false
53
53
Summary
Summary
• C++ uses the if, if-else, switch, and conditional
operator statements to make selections
• You can use the logical AND and OR to combine
boolean evaluations
• C++ uses the while statement, the do statement,
and the for loop to create loops
• Statements that depend on the boolean evaluation
in a decision or a loop are blocked by using curly
braces
• Fields contained within class objects are used in
arithmetic and boolean expressions in the same
manner as are primitive variables
54
54
Summary
Summary
• C++ supports line comments and block
comments
• A preprocessor directive tells the compiler to
do something, such as to include a header
file, before compiling the program
• The cout statement (along with an insertion
operator) is used to display values
• When you create a class, you create your
own C++ data type, which is a complex type
composed of simpler types

More Related Content

PPT
01 c++ Intro.ppt
PPTX
#Code2 create c++ for beginners
PDF
Learning the C Language
PDF
Prog1-L1.pdf
PPTX
Object oriented programming 11 preprocessor directives and program structure
PPTX
Lec01-02 (Topic 1 C++ Fundamentals).pptx
PPSX
Esoft Metro Campus - Programming with C++
PDF
Introduction to the c programming language (amazing and easy book for beginners)
01 c++ Intro.ppt
#Code2 create c++ for beginners
Learning the C Language
Prog1-L1.pdf
Object oriented programming 11 preprocessor directives and program structure
Lec01-02 (Topic 1 C++ Fundamentals).pptx
Esoft Metro Campus - Programming with C++
Introduction to the c programming language (amazing and easy book for beginners)

Similar to Ffghhhhfghhfffhjdsdhjkgffjjjkfdghhftgdhhhggg didi ucch JFK bcom (20)

PDF
Rr
PDF
C pdf
PPT
Introduction To Programming subject1.ppt
PPTX
Unit ii
PPTX
Introduction Of C++
PPTX
computer programming omputer programming
PPTX
Programming Fundamental Slide lecture no.2 (Section E)
PPTX
Chap_________________1_Introduction.pptx
PPTX
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
PPTX
PPTX
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
PPTX
PDF
Lecture1
PPTX
COMPUTER PROGRAMMING LANGUAGE C++ 1.pptx
PPTX
Presentation c++
PPTX
UNIT 5 C PROGRAMMING, PROGRAM STRUCTURE
PPTX
Lecture 2 variables
PPTX
POLITEKNIK MALAYSIA
PPTX
Object oriented programming 7 first steps in oop using c++
PDF
CP c++ programing project Unit 1 intro.pdf
Rr
C pdf
Introduction To Programming subject1.ppt
Unit ii
Introduction Of C++
computer programming omputer programming
Programming Fundamental Slide lecture no.2 (Section E)
Chap_________________1_Introduction.pptx
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
Lecture1
COMPUTER PROGRAMMING LANGUAGE C++ 1.pptx
Presentation c++
UNIT 5 C PROGRAMMING, PROGRAM STRUCTURE
Lecture 2 variables
POLITEKNIK MALAYSIA
Object oriented programming 7 first steps in oop using c++
CP c++ programing project Unit 1 intro.pdf
Ad

More from GauravKumar295392 (7)

PPTX
Lecture 2 DataStrucure - complexity , IS.pptx
PDF
Object Oriented Programming using C++ PCIT102.pdf
PDF
chap3expression-1603gggh13040831 (1).pdf
PDF
062636636366363773737373733+73737733+7.pdf
PPTX
TCS 204-SM0172637373838388383+8474747478484(4.pptx
PDF
Annotations.pdf
PDF
Dbms Model.pdf
Lecture 2 DataStrucure - complexity , IS.pptx
Object Oriented Programming using C++ PCIT102.pdf
chap3expression-1603gggh13040831 (1).pdf
062636636366363773737373733+73737733+7.pdf
TCS 204-SM0172637373838388383+8474747478484(4.pptx
Annotations.pdf
Dbms Model.pdf
Ad

Recently uploaded (20)

PDF
Literature_Review_methods_ BRACU_MKT426 course material
PDF
CRP102_SAGALASSOS_Final_Projects_2025.pdf
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PDF
Empowerment Technology for Senior High School Guide
PPTX
Education and Perspectives of Education.pptx
PPTX
Module on health assessment of CHN. pptx
PDF
Journal of Dental Science - UDMY (2020).pdf
PDF
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
Journal of Dental Science - UDMY (2022).pdf
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
Climate and Adaptation MCQs class 7 from chatgpt
PDF
My India Quiz Book_20210205121199924.pdf
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
Race Reva University – Shaping Future Leaders in Artificial Intelligence
PPTX
DRUGS USED FOR HORMONAL DISORDER, SUPPLIMENTATION, CONTRACEPTION, & MEDICAL T...
PDF
International_Financial_Reporting_Standa.pdf
PDF
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
Literature_Review_methods_ BRACU_MKT426 course material
CRP102_SAGALASSOS_Final_Projects_2025.pdf
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
AI-driven educational solutions for real-life interventions in the Philippine...
Empowerment Technology for Senior High School Guide
Education and Perspectives of Education.pptx
Module on health assessment of CHN. pptx
Journal of Dental Science - UDMY (2020).pdf
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
Share_Module_2_Power_conflict_and_negotiation.pptx
Journal of Dental Science - UDMY (2022).pdf
Cambridge-Practice-Tests-for-IELTS-12.docx
Climate and Adaptation MCQs class 7 from chatgpt
My India Quiz Book_20210205121199924.pdf
Environmental Education MCQ BD2EE - Share Source.pdf
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
Race Reva University – Shaping Future Leaders in Artificial Intelligence
DRUGS USED FOR HORMONAL DISORDER, SUPPLIMENTATION, CONTRACEPTION, & MEDICAL T...
International_Financial_Reporting_Standa.pdf
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf

Ffghhhhfghhfffhjdsdhjkgffjjjkfdghhftgdhhhggg didi ucch JFK bcom

  • 1. 1 1 A A Review Review of Programming and C++ of Programming and C++ COSC1567 COSC1567 C++ Programming C++ Programming Lecture 1
  • 2. 2 2 The Task of Programming The Task of Programming • Programming a computer involves writing instructions 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
  • 3. 3 3 The Task of Programming The Task of Programming • A translator (called either a compiler or an interpreter) checks your program for syntax errors • A logical error occurs when you use a statement that, although syntactically correct, doesn’t do what you intended • You run a program by issuing a command to execute the program statements • You test a program by using sample data to determine whether the program results are correct
  • 4. 4 4 Programming Universals Programming Universals • All programming languages provide methods for directing output to a desired object, such as a monitor screen, printer or file • Similarly, all programming languages provide methods for sending input into the computer program so that it can be manipulated • In addition, all programming languages provide for naming locations in computer memory • These locations commonly are called variables (or attributes)
  • 5. 5 5 Programming Universals Programming Universals • Ideally, variables have meaningful names, although no programming language actually requires that they meet this standard • 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 • 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
  • 6. 6 6 Programming Universals Programming Universals • The type determines what kind of values may be stored in a variable • Most computer languages allow at least two types: one for numbers and one for characters • Numeric variables hold values like 13 or -6 • Character variables hold values like ‘A’ or ‘&’ • Many languages include even more specialized types, such as integer (for storing whole numbers) or floating point (for storing numbers with decimal places)
  • 7. 7 7 Procedural Programming Procedural Programming • Procedural programs consist of a series of steps or procedures that take place one after the other • The programmer determines the exact conditions under which a procedure takes place, how often it takes place, and when the program stops • Programmers write procedural programs in many programming languages, such as COBOL, BASIC, FORTRAN, and RPG • You can also write procedural programs in C++
  • 8. 8 8 A A main( ) main( ) Function in C++ Function in C++ • C++ programs consist of modules called functions • Every statement within every C++ program is contained in a function • Every function consists of two parts: – A function header is the initial line of code in a C++ which always has three parts: • Return type of the function • Name of the function • Types and names of any variables enclosed in parentheses, and which the function receives – A function body
  • 9. 9 9 Creating a Creating a main( ) main( ) Function Function • A C++ program may contain many functions, but every C++ program contains at least one function, and that function is called main( ) • 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 • The body of every function in a C++ program is contained in curly braces, also known as curly brackets
  • 10. 10 10 Creating a Creating a main( ) main( ) Function Function • Every complete C++ statement ends with a semicolon • Often several statements must be grouped together, as when several statements must occur in a loop • In such a case, the statements have their own set of opening and closing braces within the main braces, forming a block
  • 11. 11 11 Working with Variables Working with Variables • In C++, you must name and give a type to variables (sometimes called identifiers) before you can use them • Names of C++ variables can include letters, numbers, and underscores, but must begin with a letter or underscore • No spaces or other special characters are allowed within a C++ variable name • Every programming language contains a few vocabulary words, or keywords, that you need in order to use the language
  • 13. 13 13 Working with Variables Working with Variables • A C++ keyword cannot be used as a variable name • Each named variable must have a type • C++ supports three simple types: – Integer — Floating point — Character • An integer is a whole number, either positive or negative • An integer value may be stored in an integer variable declared with the keyword int • You can also declare an integer variable using short int and long int
  • 14. 14 14 Working with Variables Working with Variables • Real or floating-point numbers are numbers that 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
  • 15. 15 15 Working with Variables Working with Variables • In C++, a character value is always expressed in single 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
  • 16. 16 16 Working with Variables Working with Variables • Explicitly stating the value of a variable is called assignment, and is achieved with the assignment operator = • The variable finalScore is declared and assigned a value at the same time • Assigning a value to a variable upon creation is often referred to as initializing the variable
  • 17. 17 17 The const Qualifier The const Qualifier • A variable that does not change in a program should not be declared as a variable • Instead, it should be a constant • 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
  • 18. 18 18 Creating Comments Creating Comments • Comments are statements that do not affect the compiling or running of a program • Comments are simply explanatory remarks that the programmer includes in a program to clarify what is taking place • 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 • C++ supports both line comments and block comments
  • 19. 19 19 Creating Comments Creating Comments • A line comment begins with two slashes (//) and continues to the end of the line on which it is placed • 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
  • 20. 20 20 Using Libraries and Using Libraries and Preprocessor Directives Preprocessor Directives • Header files are files that contain predefined values and 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
  • 21. 21 21 C++ Binary Arithmetic Operators C++ Binary Arithmetic Operators • Often after data values are input, you perform calculations with them • C++ provides five simple arithmetic operators for creating arithmetic expressions: – addition (+) – subtraction (-) – multiplication (*) – division (/) – modulus (%) • 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 • The results of an arithmetic operation can be stored in memory 2
  • 22. 22 22 C++ Binary Arithmetic Operators C++ Binary Arithmetic Operators
  • 23. 23 23 C++ Binary Arithmetic Operators C++ Binary Arithmetic Operators • In Figure 2-2, each operation is assigned to a result variable of the correct type • 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 • 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
  • 24. 24 24 C++ Binary Arithmetic Operators C++ Binary Arithmetic Operators • The automatic cast that occurs when you assign a value of one type to another is called an implicit cast • The modulus operator (%), which gives the remainder of integer division, can be used only with integers • When more than one arithmetic operator is included in an expression, then multiplication, division, and modulus operations always occur before addition or subtraction • Multiplication, division, and modulus are said to have higher precedence
  • 25. 25 25 Shortcut Arithmetic Operators Shortcut Arithmetic Operators • C++ employs several shortcut operators • When you add two variable values and store the result in a third variable, the expression takes the form result= firstValue + secondValue • When you use an expression like this, both firstValue and secondValue retain their original values; only the result is altered • When you want to increase a value, the expression takes the form firstValue = firstValue + secondValue
  • 26. 26 26 Shortcut Arithmetic Operators Shortcut Arithmetic Operators • 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 • As with the += operator, you must not insert a space within the subtraction, multiplication, or division shortcut operators • 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
  • 27. 27 27 Shortcut Arithmetic Operators Shortcut Arithmetic Operators • As you might expect, you can use two minus signs (--) before or after a variable to decrement it
  • 28. 28 28 Shortcut Arithmetic Operators Shortcut Arithmetic Operators • The prefix and postfix increment and decrement operators are examples of unary operators • Unary operators are those that require only one operand, such as num in the expression ++num • When an expression includes a prefix operator, the mathematical operation takes place before the expression is evaluated • When an expression includes a postfix operator, the mathematical operation takes place after the expression is evaluated
  • 29. 29 29 Shortcut Arithmetic Operators Shortcut Arithmetic Operators • 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
  • 30. 30 30 Evaluating Boolean Expressions Evaluating Boolean Expressions • A boolean expression is one that evaluates as true or 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 cout<<(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
  • 31. 31 31 Evaluating Boolean Expressions Evaluating Boolean Expressions • The unary operator ! Means not, and essentially reverses the true/false value of an expression
  • 32. 32 32 Selection Selection • Computer programs seem smart because of their ability to use selections or make decisions • C++ lets you perform selections in a number of ways: – The if statement – The switch statement – The if operator – Logical AND and Logical OR
  • 33. 33 33 Some Sample Selection Some Sample Selection Statements within a C++ Program Statements within a C++ Program
  • 34. 34 34 The if The if Statement Statement • 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
  • 35. 35 35 The if The if Statement Statement
  • 36. 36 36 Multiple Executable Statement Multiple Executable Statement in an if-else in an if-else
  • 37. 37 37 The if The if Statement Statement • Any C++ expression can be evaluated as part of an if statement
  • 38. 38 38 The switch Statement The switch Statement • 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 • As an alternative to the long string of ifs shown in Figure 2-14, you can use the switch statement • The switch can contain any number of cases in any order
  • 39. 39 39 The if Operator The if Operator ( (NEW! NEW! ) ) • Another alternative to the if statement involves the if operator (also called the conditional operator), which is represented by a question mark (?) • E.g. • cout<<(driveAge<26)?”The driver is under 26”:”The driver is at least 26”; • The if operator provides a concise way to express two alternatives • The conditional operator is an example of a ternary operator, one that takes three operands instead of just one or two Ex1-2.cpp
  • 40. 40 40 Logical AND and Logical OR Logical AND and Logical OR • In some programming situations, two or more conditions must be true to initiate an action • Figure 2-16 works correctly using a nested if—that is, one if statement within another if statement • If numVisits is not greater than 5, the statement is finished—the second comparison does not even take place • Alternatively, a logical AND (&&) can be used, as shown in Figure 2-17
  • 41. 41 41 Logical AND and Logical OR Logical AND and Logical OR
  • 42. 42 42 Logical AND and Logical OR Logical AND and Logical OR • A logical AND is a compound boolean expression in which two conditions must be true for the entire expression to evaluate as true • Table 2-3 shows how an expression using && is evaluated • An entire expression is true only when the expression on each side of the && is true
  • 43. 43 43 Using the Logical OR Using the Logical OR • In certain programming situations, only one of two alternatives must be true for some action to take place • A logical OR (||) could also be used • 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 • Table 2-4 shows how C++ evaluates any expression that uses the || operator
  • 44. 44 44 Using the Logical OR Using the Logical OR
  • 45. 45 45 Using the Logical OR Using the Logical OR • When either expression1 or expression2 is true (or both are true), the entire expression is true • On pages 53 and 54 of the textbook, perform the steps so you can write a program that makes several decisions
  • 46. 46 46 A Typical Run of the A Typical Run of the Decisions.cpp Program Decisions.cpp Program
  • 47. 47 47 The while Loop The while Loop • Loops provide a mechanism with which to perform statements repeatedly and, just as important, to stop that performance when warranted while (boolean expression) statement; • In C++, the while statement can be used to loop • 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
  • 50. 50 50 The for Statement The for Statement • The for statement represents an alternative to the while statement • It is most often used in a definite loop, or a loop that must execute a definite number of times • It takes the form: for (initialize; evaluate; alter) statement; Ex1-3.cpp
  • 51. More examples More examples • Ex1-6.cpp • Ex1-7.cpp 51 51
  • 52. 52 52 Summary Summary • C++ provides five simple binary arithmetic operators for creating arithmetic expressions: addition (+), subtraction (-), multiplication (*), division (/), and modulus (%) • When you mix data types in a binary arithmetic expression, the result is always the same type as the type that takes the most memory to store • C++ employs several shortcut operators for arithmetic, such as +=, prefix, ++, and postfix ++ • A boolean expression is one that evaluates as true or false
  • 53. 53 53 Summary Summary • C++ uses the if, if-else, switch, and conditional operator statements to make selections • You can use the logical AND and OR to combine boolean evaluations • C++ uses the while statement, the do statement, and the for loop to create loops • Statements that depend on the boolean evaluation in a decision or a loop are blocked by using curly braces • Fields contained within class objects are used in arithmetic and boolean expressions in the same manner as are primitive variables
  • 54. 54 54 Summary Summary • C++ supports line comments and block comments • A preprocessor directive tells the compiler to do something, such as to include a header file, before compiling the program • The cout statement (along with an insertion operator) is used to display values • When you create a class, you create your own C++ data type, which is a complex type composed of simpler types