SlideShare a Scribd company logo
1 of 92
An Introduction To Software
Development Using C++
Class #14:
Review For Midterm
What’s Up With This Object
Orientated Stuff?
Procedural Languages
One long piece of code
where data and logic
are all mixed in
together.
1 #
2 # Sample program that demonstrates the print function.
3 #
4
5 # Prints 7
6 print(3 + 4)
7
8 # Prints “Hello World!” in two lines.
9 print("Hello")
10 print("World!")
11
12 # Prints multiple values with a single print function call.
13 print("My favorite numbers are", 3 + 4, "and", 3 + 10)
14
15 # Prints three lines of text with a blank line.
16 print("Goodbye")
17 print()
18 print("Hope to see you again")
What’s Up With This Object
Orientated Stuff?
• Each object represents a different part
of the application.
• Each object contains it’s own data & it’s
own logic.
• The objects communicate between
themselves.
• Objects are designed to represent how
you talk and think about the actual
problem.
• Objects are meant to make thinking
about your program easier.
• Object orientation is just an idea that is
supported by C++
I Know How To Program, Why
Bother With This C++ Stuff?
• Why is so much attention today focused on object-oriented programming
in general and C++ in particular?
ANSWER: Object-oriented programming enables the programmer to build
reusable software components that model items in the real world.
Building software quickly, correctly, and economically has been an elusive
goal in the software industry.
The modular, object-oriented design and implementation approach has
been found to increase productivity 10 to 100 times over conventional
programming languages while reducing development time, errors, and
cost. C++ is extremely popular because it is a superset of the widely used C
programming language. Programmers already familiar with C have an
easier time learning C++.
Image Credit: www.dreamstime.com
What are “Objects”?
Objects (both software and real)
have two ways that they can
be represented:
A. Attributes
B. Behaviors
What are “Objects”?
The gas pedal hides from the driver the complex
mechanisms that actually make the car go faster,
just as the brake pedal hides the mechanisms that
slow the car, and the steering wheel “hides” the
mechanisms that turn the car.
This enables people with little or no knowledge of
how engines, braking and steering mechanisms
work to drive a car easily.
Objects work the same way – they hide your code
from other developers so that they don’t have to
know HOW you did something, just what your
code DOES.
Member Functions and Classes
Performing a task in a program requires a member function, which houses
the program statements that actually perform its task. The member function
hides these statements from its user, just as the accelerator pedal of a car
hides from the driver the mechanisms of making the car go faster.
In C++, we create a program unit called a class to house the set of
member functions that perform the class’s tasks.
For example, a class that represents a bank account might contain one
member function to deposit money to an account, another to withdraw
money from an account and a third to inquire what the account’s current
balance is.
A class is similar in concept to a car’s engineering drawings, which house
the design of an accelerator pedal, steering wheel, and so on.
What Is A Class?
• It’s a blueprint, the definition, the description.
• It is not the thing itself!
Image Credit: www.chickslovethecar.com
Instantiation
You must build an object of a class before a program can perform the tasks
that the class’s member functions define.
The process of doing this is called instantiation. An object is then referred to
as an instance of its class.
Object
• The object is created from the class
• One class can create multiple objects
Image Credit: http://8z4.net/images/blueprint-/5.html
Reuse
You can reuse a class many times to build many objects.
Reuse of existing classes when building new classes and programs saves
time and effort.
Reuse also helps you build more reliable and effective systems, because
existing classes and components often have gone through extensive testing,
debugging and performance tuning.
Messages and
Member Function Calls
When you drive a car, pressing its gas pedal sends a message to the car to
perform a task—that is, to go faster.
Similarly, you send messages to an object.
Each message is implemented as a member function call that tells a member
function of the object to perform its task.
For example, a program might call a particular bank account object’s deposit
member function to increase the account’s balance.
Attributes and Data Members
A car, besides having capabilities to accomplish tasks, also has attributes,
such as its color, its number of doors, the amount of gas in its tank, its current
speed and its record of total miles driven (i.e., its odometer reading).
As you drive an actual car, these attributes are carried along with the car.
Every car maintains its own attributes. For example, each car knows how
much gas is in its own gas tank, but not how much is in the tanks of other
cars.
An object, similarly, has attributes that it carries along as it’s used in a
program. These attributes are specified as part of the object’s class. For
example, a bank account object has a balance attribute that represents the
amount of money in the account. Each bank account object knows the
balance in the account it represents, but not the balances of the other
accounts in the bank. Attributes are specified by the class’s data members.
Encapsulation
Classes encapsulate (i.e., wrap) attributes and member functions into
objects—an object’s attributes and member functions are intimately related.
Objects may communicate with one another, but they’re normally not allowed
to know how other objects are implemented—implementation details are
hidden within the objects themselves.
This information hiding, as we’ll see, is crucial to good software engineering.
Encapsulation
Encapsulated
Taking Apart Our First Program
• Comments: lines 1 & 2
– Comments each begin with //, indicating that the remainder of each line is a
comment. You insert comments to document your programs and to help other
people read and understand them.
– Comments do not cause the computer to perform any action when the
program is run—they’re ignored by the C++ compiler and do not cause any
machine-language object code to be generated.
– A comment beginning with // is called a single-line comment because it
terminates at the end of the current line.
[Note: You also may use C’s style in which a comment—possibly containing
many lines—begins with /* and ends with */.]
// Title: You’re Very 1st Ever C++ Program
// Description: Program to print some text on the screen
Taking Apart Our First Program
• Preprocessor Directive: line 3
– This statement is a preprocessor directive, which is a message to the C++
preprocessor (processing done BEFORE compiling happens). Lines that begin
with # are processed by the preprocessor before the program is compiled.
– This line notifies the preprocessor to include in the program the contents of
the input/output stream header <iostream>.
– This header must be included for any program that outputs data to the screen
or inputs data from the keyboard using C++’s stream input/output.
#include <iostream> // allows program to output data to the screen
Taking Apart Our First Program
• Main Function: line 6
– The main function is a part of every C++ program.
– The parentheses after main indicate that main is a program building block
called a function.
– C++ programs typically consist of one or more functions and classes. Exactly
one function in every program must be named main.
– C++ programs begin executing at function main, even if main is not the first
function in the program.
int main()
Taking Apart Our First Program
• Main Function: line 6
– The keyword int to the left of main indicates that main “returns” an integer
(whole number) value. A keyword is a word in code that is reserved by C++ for
a specific use.
– The left brace, {, (line 7) must begin the body of every function. A
corresponding right brace, }, (line 11) must end each function’s body.
int main()
{
} // end function main
Taking Apart Our First Program
• An Output Statement: line 8
– This command instructs the computer to perform an action—namely, to print
the string of characters contained between the double quotation marks.
– White-space characters in strings are not ignored by the compiler.
– The entire line 8, including std::cout, the << operator, the string “Hello
World!n" and the semicolon (;), is called a statement.
– Every C++ statement must end with a semicolon
(also known as the statement terminator).
– Preprocessor directives (like #include) do not end with a semicolon.
std::cout << “Hello World!n"; // display message
• An Output Statement: line 8
– Output and input in C++ are accomplished with streams of characters.
– Thus, when the preceding statement is executed, it sends the stream of
characters Hello World!n to the standard output stream object—std::cout—
which is normally “connected” to the screen.
std::cout << “Hello World!n"; // display message
Taking Apart Our First Program
• The std Namespace
– The std:: before cout is required when we use names that we’ve brought into
the program by the preprocessor directive #include <iostream>.
– The notation std::cout specifies that we are using a name, in this case cout,
that belongs to “namespace” std.
– The names cin (the standard input stream) and cerr (the standard error
stream) also belong to namespace std.
– For now, you should simply remember to include std:: before
each mention of cout, cin and cerr in a program.
std::cout << “Hello World!n"; // display message
Taking Apart Our First Program
Taking Apart Our First Program
• The Stream Insertion Operator and Escape
Sequences
– The << operator is referred to as the stream insertion operator.
– When this program executes, the value to the operator’s right, the right
operand, is inserted in the output stream.
– Notice that the operator points in the direction of where the data goes. The
right operand’s characters normally print exactly as they appear between the
double quotes.
std::cout << “Hello World!n"; // display message
Taking Apart Our First Program
• The Stream Insertion Operator and Escape
Sequences
– However, the characters n are not printed on the screen. The backslash () is
called an escape character.
– It indicates that a “special” character is to be output. When a backslash is
encountered in a string of characters, the next character is combined with the
backslash to form an escape sequence.
– The escape sequence n means newline. It causes the cursor (i.e.,
the current screen-position indicator) to move to the beginning of
the next line on the screen.
std::cout << “Hello World!n"; // display message
Taking Apart Our 2nd Program
• Variable Declarations
– These are declarations. The identifiers number1, number2 and sum are the
names of variables.
– A variable is a location in the computer’s memory where a value can be stored
for use by a program.
– These declarations specify that the variables number1, number2 and sum are
data of type int, meaning that these variables will hold integer values, i.e.,
whole numbers such as 7, –11, 0 and 31914. All variables must be declared
with a name and a data type before they can be used in a program.
// variable declarations
int number1; // first integer to add
int number2; // second integer to add
int sum; // sum of number1 and number2
Taking Apart Our 2nd Program
• Placement of Variable Declarations
– Declarations of variables can be placed almost anywhere in a program, but
they must appear before their corresponding variables are used in the
program.
// variable declarations
int number1; // first integer to add
int number2; // second integer to add
int sum; // sum of number1 and number2
std::cout << "Enter first integer: "; // prompt user for data
int number1; // first integer to add
std::cin >> number1; // read first integer from user into number1
Image Credit: www.dreamstime.com
Taking Apart Our 2nd Program
• Obtaining the First Value from the User
– This statement uses the standard input stream object cin (of namespace std)
and the stream extraction operator, >>, to obtain a value from the keyboard.
– We like to describe the preceding statement as, “std::cin gives a value to
number1” or simply “std::cin gives number1.”
– When the computer executes the preceding statement, it waits for the user to
enter a value for variable number1.
– The computer converts the character representation of the number to an
integer and assigns (i.e., copies) this number (or value) to the variable
number1. Any subsequent references to number1 in this program will use this
same value
std::cin >> number1; // read first integer from user into number1
Image Credit: alsanda.wordpress.com
Taking Apart Our 2nd Program
• Calculating the Sum of the Values Input by the
User
– The assignment stmt adds the values of variables number1 and number2 and
assigns the result to variable sum using the assignment operator =.
– The statement is read as, “sum gets the value of number1 + number2.”
– Most calculations are performed in assignment statements. The = operator
and the + operator are called binary operators because each has two
operands.
– In the case of the + operator, the two operands are number1 and number2. In
the case of the preceding = operator, the two operands are sum and the value
of the expression number1 + number2.
sum = number1 + number2; // add the numbers; store result in sum
Image Credit: www.clipartpanda.com
Taking Apart Our 2nd Program
• Calculations can also be performed in output
statements.
– We could have combined the separate addition and then print statements into
a single statement.
– This would have eliminated the need for the variable sum.
std::cout << "Sum is " << number1 + number2 << std::endl;
Image Credit: www.property118.com
Let’s Talk About C++ Math!
Normal Stuff
Weird Stuff
5%2 = 1
Image Credit: www.wired.co.uk
Modulo (%) Is Your Friend
• A man has 113 cans of Coke. He also has a group of boxes that can hold 12 cans
each. How many cans will he have left over once he’s loaded all of the boxes?
• On a military base the clock on the wall says that the time is 23:00. What time of
day is this?
• My friend has 10,432 ping pong balls that he needs to put into storage. My car can
transport 7,239 balls. How many will be left after I leave?
What Comes First?
Precedence Rules
• The precedence rules you learned in algebra apply during the evaluation
of arithmetic expressions in C++:
– Unary negation is evaluated next, before multiplication, division, and
remainder.
– Multiplication, division, and remainder are evaluated before addition and
subtraction.
– Addition and subtraction are evaluated before assignment.
– With one exception, operations of equal precedence are left associative,
so they are evaluated from left to right. Assignment operations are right
associative, so consecutive instances of these are evaluated from right to left.
– You can use parentheses to change the order of evaluation
• "PMDAS", which is turned into the phrase "Push My Dear Aunt Sally". It
stands for "Parentheses, Multiplication and Division, and Addition and
Subtraction".
-5
2+3*4/6
sum = 2+3
2+3*4/6
sum = 12
(2+3)*4/5
Image Credit: www.pinterest.com
How To Make Decisions In C++
• We’ll now introduce a simple version of C++’s if statement that allows a program
to take alternative action based on whether a condition is true or false.
• If the condition is true, the statement in the body of the if statement is executed. If
the condition is false, the body statement is not executed.
• Conditions in if statements can be formed by using the equality operators and
relational operators.
• The relational operators all have the same level of precedence and associate left to
right. The equality operators both have the same level of precedence, which is
lower than that of the relational operators, and associate left to right.
Image Creditpositivityworks.wordpress.com
Equality and Relational Operators.
Under The Hood w/ Program #3
• using Directives
– These statements are using directives that eliminate the need to repeat the
std:: prefix as we did in earlier programs.
– We can now write cout instead of std::cout, cin instead of std::cin and endl
instead of std::endl, respectively, in the remainder of the program!!!
– In place of these 3 lines, many programmers prefer to use the directive:
which enables a program to use all the names in any standard C++ header
(such as <iostream>) that a program might include. From this point forward,
we’ll use this technique in our programs.
using std::cout; // program uses cout
using std::cin; // program uses cin
using std::endl; // program uses endl
using namespace std;
Image Credit: osdelivers.blackducksoftware.com
Under The Hood w/ Program #3
• Comparing Numbers
– The if statement compares the values of variables number1 and number2 to
test for equality.
– If the values are equal, the statement displays a line of text indicating that the
numbers are equal.
– If the conditions are true in one or more of the if statements starting in the
other lines, the corresponding body statement displays an appropriate line of
text.
– Each if statement the program has a single statement in its body and each
body statement is indented.
if ( number1 == number2 )
cout << number1 << " == " << number2 << endl;
Image Credit: www.sellerexpress.com
Why OO?
• Object-Oriented Programming has the following advantages
over conventional approaches:
– OOP provides a clear modular structure for programs which makes it
good for defining abstract datatypes where implementation details are
hidden and the unit has a clearly defined interface.
– OOP makes it easy to maintain and modify existing code as new
objects can be created with small differences to existing ones.
– OOP provides a good framework for code libraries where supplied
software components can be easily adapted and modified by the
programmer. This is particularly useful for developing graphical user
interfaces.
Image Credit: betanews.com
Let’s Get Some Class
• Class GradeBook
– Before function main can create a GradeBook object, we must tell the
compiler what member functions and data members belong to the class. The
GradeBook class definition contains a member function called displayMessage
that displays a message on the screen.
– We need to make an object of class GradeBook and call its displayMessage
member function to display the welcome message.
– By convention, the name of a user-defined class begins with a capital letter,
and for readability, each subsequent word in the class name begins with a
capital letter. The class definition terminates with a semicolon.
// GradeBook class definition
class GradeBook
{
public:
// function that displays a welcome message to the
GradeBook user
void displayMessage()
{
cout << "Welcome to the Grade Book!" << endl;
} // end function displayMessage
}; // end class GradeBook
Image Credit: simpsons.wikia.com
Let’s Get Some Class
• Class GradeBook
– The class definition begins with the keyword class followed by the class name
GradeBook. By convention, the name of a user-defined class begins with a
capital letter, and for readability, each subsequent word in the class name
begins with a capital letter.
– Every class’s body is enclosed in a pair of left and right braces ({ and })
– The class definition terminates with a semicolon.
// GradeBook class definition
class GradeBook
{
public:
// function that displays a welcome message to the
GradeBook user
void displayMessage()
{
cout << "Welcome to the Grade Book!" << endl;
} // end function displayMessage
}; // end class GradeBook
Image Credit: www.aptce.org
Let’s Get Some Class
• Class GradeBook
– The next line contains the keyword public, which is an access specifier. After
this we define member function displayMessage. This member function
appears after access specifier public: to indicate that the function is “available
to the public”—that is, it can be called by other functions in the program (such
as main)
– Access specifiers are always followed by a colon (:).
// GradeBook class definition
class GradeBook
{
public:
// function that displays a welcome message to the
GradeBook user
void displayMessage()
{
cout << "Welcome to the Grade Book!" << endl;
} // end function displayMessage
}; // end class GradeBook
Image Credit: sahamparsa.blogspot.com
Let’s Get Some Class
• Each function in a program performs a task and may return a value when it
completes its task—for example, a function might perform a calculation, then
return the result of that calculation.
• When you define a function, you must specify a return type to indicate the type of
the value returned by the function when it completes its task.
• The keyword void to the left of the function name displayMessage is the function’s
return type.
• Return type void indicates that displayMessage will not return any data to its
calling function when it completes its task.
void displayMessage()
Return type Function
Image Credit: www.iconshut.com
Let’s Get Some Class
• The name of the member function, displayMessage, follows the return type. By
convention, function names begin with a lowercase first letter and all subsequent
words in the name begin with a capital letter.
• The parentheses after the member function name indicate that this is a function.
An empty set of parentheses indicates that this member function does not require
additional data to perform its task.
• Every function’s body is delimited by left and right braces ({ and }). The body of a
function contains statements that perform the function’s task. In this case,
member function displayMessage contains one statement that displays the
message "Welcome to the Grade Book!". After this statement executes, the
function has completed its task.
void displayMessage()
{
cout << "Welcome to the Grade Book!" << endl;
} // end function displayMessage
{}
The UML
(Unified Modeling Language)
• Although many different OOAD processes exist, a single graphical language for
communicating the results of any OOAD process has come into wide use. This
language, known as the Unified Modeling Language (UML), is now the most widely
used graphical scheme for modeling object-oriented systems.
• In the UML, each class is modeled in a UML class diagram as a rectangle with three
compartments. The top compartment contains the class’s name centered
horizontally and in boldface type. The middle compartment contains the class’s
attributes, which correspond to data members in C++.
• This compartment is currently empty, because class GradeBook does not have any
attributes. The bottom compartment contains the class’s operations, which
correspond to member functions in C++.
Defining a Member Function
with a Parameter
Pressing on a car’s gas pedal sends two
messages to the car:
1. Go faster
2. Go how much faster?
So the message to the car includes both the task
to perform and additional information that helps
the car perform the task.
This additional information is known as a
parameter — the value of the parameter helps
the car determine how fast to accelerate.
Functions, Parameters, & Arguments
• A member function can require one or more parameters that represent additional
data it needs to perform its task.
• A function call supplies values—called arguments—for each of the function’s
parameters.
• For example, to make a deposit into a bank account, suppose a deposit member
function of an Account class specifies a parameter that represents the deposit
amount.
• When the deposit member function is called, an argument value representing
the deposit amount is copied to the member function’s parameter.
• The member function then adds that amount to the account balance.
int makeDeposit(depositAmount)
Image Credit: uldissprogis.com
Let’s Take A Time Out!
Let’s Talk About Strings
• We create a variable of type string called nameOfCourse that will be used to store
the course name entered by the user.
• A variable of type string represents a string of characters such as
“CS101 Introduction to C++ Programming".
• A string is actually an object of the C++ Standard Library class string.
• This class is defined in header <string>, and the name string, like cout, belongs to
namespace std.
• To enable the program to compile, we include the <string> header. The using
directive allows us to simply write string rather than std::string. For now, you
can think of string variables like variables of other types such as int.
#include <string> // program uses C++ standard string class using namespace std;
Why Make Things Harder?
• In this example, we’d like the user to type the complete course name and
press Enter to submit it to the program, and we’d like to store the entire
course name in the string variable nameOfCourse.
• The function call getline( cin, nameOfCourse ) reads characters (including
the space characters that separate the words in the input) from the
standard input stream object cin (i.e., the keyboard) until the newline
character is encountered, places the characters in the string variable
nameOfCourse and discards the newline character.
• When you press Enter while typing program input, a newline is inserted in
the input stream.
• The <string> header must be included in the program to use function
getline, which belongs to namespace std.
getline( cin, nameOfCourse ); // read a course name with blanks
Image Credit: www.amazon.com
Functions, Parameters, & Arguments
• The next line calls myGradeBook’s displayMessage member function.
• The nameOfCourse variable in parentheses is the argument that’s passed to
member function displayMessage so that it can perform its task.
• The value of variable nameOfCourse in main is copied to member function
displayMessage’s parameter courseName.
• When you execute this program, member function displayMessage outputs as
part of the welcome message the course name you type (in our sample execution,
“COP2271 Introduction to C++ Programming”).
myGradeBook.displayMessage(nameOfCourse);
// call object's displayMessage function
Argument
Member Function
Image Credit: mathinsight.org
Functions, Parameters, & Arguments
• To specify in a function definition that the function requires data to perform its
task, you place additional information in the function’s parameter list, which is
located in the parentheses following the function name.
• The parameter list may contain any number of parameters, including none at all
to indicate that a function does not require any parameters.
• Member function displayMessage’s parameter list declares that
the function requires one parameter.
• Each parameter specifies a type and an identifier. The type string and the identifier
courseName indicate that member function displayMessage requires a string to
perform its task.
• The member function body uses the parameter courseName to access the value
that’s passed to the function in the function call.
void displayMessage( string courseName )
Image Credit: commons.wikimedia.org
Functions, Parameters, & Arguments
• A function can specify multiple parameters by separating each from the next with
a comma.
• The number and order of arguments in a function call must match the number
and order of parameters in the parameter list of the called member function’s
header.
• Also, the argument types in the function call must be consistent with the types of
the corresponding parameters in the function header.
• In our example, the one string argument in the function call (i.e., nameOfCourse)
exactly matches the one string parameter in the member-function definition (i.e.,
courseName).
void displayMessage( string courseName )
myGradeBook.displayMessage(nameOfCourse); // call object's displayMessage
function Image Credit: sbkb.org
Updated UML Class Diagram for
Class GradeBook
• This GradeBook class contains public member function displayMessage. However, this version
of displayMessage has a parameter.
• The UML models a parameter by listing the parameter name, followed by a colon and the
parameter type in the parentheses following the operation name.
• The UML has its own data types similar to those of C++. The UML is language independent—
it’s used with many different programming languages—so its terminology does not exactly
match that of C++.
• For example, the UML type String corresponds to the C++ type string.
• Member function displayMessage of class GradeBook has a string parameter named
courseName, so the diagram lists courseName : String between the parentheses following
the operation name displayMessage.
• This version of the GradeBook class still does not have any data members.
Local Variables
• We have been declaring all of a program’s variables in its main function.
• Variables declared in a function definition’s body are known as local variables and
can be used only from the line of their declaration in the function to closing right
brace (}) of the block in which they’re declared.
• A local variable must be declared before it can be used in a function.
• A local variable cannot be accessed outside the function in which it’s declared.
When a function terminates, the values of its local variables are lost.
Image Credit: deniseleeyohn.com
Class Attributes
• A class normally consists of one or more member functions that manipulate the
attributes that belong to a particular object of the class.
• Attributes are represented as variables in a class definition. Such variables are
called data members and are declared inside a class definition but outside the
bodies of the class’s member-function definitions.
• Each object of a class maintains its own copy of its attributes in memory. These
attributes exist throughout the life of the object.
• The example in this section demonstrates a GradeBook class that contains a
courseName data member to represent a particular GradeBook object’s
course name.
Image Credit: colleendilen.com
Access Specifiers:
public and private
• Most data-member declarations appear after the private access specifier. Variables or
functions declared after access specifier private are accessible only to member functions of
the class for which they’re declared.
• Thus, data member courseName can be used only in member functions setCourseName,
getCourseName and displayMessage of class GradeBook.
• The default access for class members is private so all members after the class header and
before the first access specifier (if there are any) are private. The access specifiers public and
private may be repeated, but this is unnecessary and can be confusing.
• Declaring data members with access specifier private is known as data hiding.
• When a program creates a GradeBook object, data member courseName is encapsulated
(hidden) in the object and can be accessed only by member functions of the object’s class. In
class GradeBook, member functions setCourseName and getCourseName manipulate the
data member courseName directly.
Image Credit: engagor.com
Key Point
• The statements each use variable courseName even though it was not
declared in any of the member functions. We can do this because
courseName is a data member of the class
private:
string courseName; // course name for
this GradeBook
void setCourseName( string name )
{
courseName = name; // store the
course name in the object
} // end function setCourseName
string getCourseName()
{
return courseName; // return the
object's courseName
} // end function getCourseName
Image Credit: www.omgtop5.com
Initializing Objects with Constructors
• When an object of class GradeBook is created, its data member courseName is
initialized to the empty string by default.
• What if you want to provide a course name when you create a GradeBook object?
• Each class you declare can provide a constructor that can be used to initialize an
object of the class when the object is created. A constructor is a special member
function that must be defined with the same name as the class, so that the
compiler can distinguish it from the class’s other member
functions.
• An important difference between constructors and other functions is that
constructors cannot return values, so they cannot specify a return type (not even
void).
• Normally, constructors are declared public.
Image Credit: forums.autodesk.com
Initializing Objects with Constructors
• C++ requires a constructor call for each object that’s created, which helps ensure
that each object is initialized properly before it’s used in a program.
• The constructor call occurs implicitly when the object is created. If a class does not
explicitly include a constructor, the compiler provides a default constructor—that
is, a constructor with no parameters.
• For example, when we create a GradeBook object, the default constructor is
called. The default constructor provided by the compiler creates a GradeBook
object without giving any initial values to the object’s fundamental type data
members.
Image Credit: www.itcuties.com
Defining a Constructor
• Defining a Constructor
– We define a constructor for class GradeBook. Notice that the constructor has
the same name as its class, GradeBook.
– A constructor specifies in its parameter list the data it requires to perform its
task. When you create a new object, you place this data in the parentheses
that follow the object name.
– The program shows that that class GradeBook’s constructor has a string
parameter called name. The constructor does not specify a return type,
because constructors cannot return values (or even void).
// constructor initializes courseName with string supplied as argument
GradeBook( string name )
{
setCourseName( name ); // call set function to initialize courseName
} // end GradeBook constructor
Image Credit: www.ciconstructors.com
Adding the Constructor to Class
GradeBook’s UML Class Diagram
• This UML class diagram of the GradeBook class our program, which has a
constructor with a name parameter of type string (represented by type String in
the UML).
• Like operations, the UML models constructors in the third compartment of a class
in a class diagram.
• To distinguish a constructor from a class’s operations, the UML places the word
“constructor” between guillemets (« and ») before the constructor’s name.
• By convention, you list the class’s constructor before other operations in the third
compartment.
The Compilation and Linking Process
• The diagram shown shows the compilation and
linking process that results in an executable
GradeBook application that can be used by
instructors.
• Often a class’s interface and implementation
will be created and compiled by one
programmer and used by a separate
programmer who implements the client code
that uses the class. So, the diagram shows
what’s required by both the class-
implementation programmer and the client-
code programmer.
• The dashed lines in the diagram show the
pieces required by the class-implementation
programmer, the client-code programmer and
the GradeBook application user, respectively.
Selection Statements in
C++
•C++ provides three types of selection statements.
•The if selection statement either performs (selects) an action if
a condition is true or skips the action if the condition is false.
•The if…else selection statement performs an action if a
condition is true or performs a different action if the condition is
false.
Image Credit: www.bhamrail.com
if / if … else
•The if selection statement is a single-selection
statement because it selects or ignores a single action.
•The if…else statement is called a double-selection
statement because it selects between two different
actions.
•The switch selection statement is called a multiple-
selection statement because it selects among many
different actions.
Image Credit: en.wikipedia.org
if Selection Statement
•Programs use selection statements to choose among alternative courses of
action.
•Pseudocode
–Suppose the passing grade on an exam is 60.
•If student’s grade is greater than or equal to 60
•Print “Passed”
–The preceding pseudocode If statement can be written in
C++ as:
if ( grade >= 60 )
cout << "Passed";
•The C++ code corresponds closely to the pseudocode. This is
one of the properties of pseudocode that make it such a useful
program development tool.
Image Credit: www.if-insurance.com
Notes About If
•Decisions can be based on conditions containing
relational or equality operators.
•Actually, in C++, a decision can be based on any
expression—if the expression evaluates to zero, it’s
treated as false; if the expression evaluates to nonzero,
it’s treated as true.
•C++ provides the data type bool for variables that can
hold only the values true and false—each of these is a
C++ keyword.
Image Credit: www.daniellestrickland.com
if…else Double-Selection Statement
•The if single-selection statement performs an indicated action
only when the condition is true; otherwise the action is skipped.
•The if…else double-selection statement allows you to specify an
action to perform when the condition is true and a different
action to perform when the condition is false.
•Pseudocode:
–If student’s grade is greater than or equal to 60
– Print “Passed”
–Else
– Print “Failed”
Image Credit: twitter.com
C++ Code – Using If
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else
if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else
if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else
if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";
Image Credit: folding.stanford.edu
C++ Code – Using Else…If
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";
Image Credit: www.dental.pacific.edu
C++’s While Repetition Statement
• When the while statement begins execution, product’s value is 3.
• Each repetition multiplies product by 3, so product takes on the values 9, 27, 81
and 243 successively.
• When product becomes 243, the while statement condition—product <= 100—
becomes false.
• This terminates the repetition, so the final value of product is 243.
• At this point, program execution continues with the next statement after the while
statement
int product = 3;
while ( product <= 100 )
product = 3 * product;
Image Credit: www.mikevaleriani.com
Notes on Integer Division
and Truncation
• The averaging calculation performed in response to the function call in the
program produces an integer result.
• The sample execution indicates that the sum of the grade values is 846, which,
when divided by 10, should yield 84.6—a number with a decimal point.
• However, the result of the calculation total / 10 is the integer 84, because total and
10 are both integers. Dividing two integers results in integer division—
any fractional part of the calculation is lost (i.e., truncated).
• In the program, if we used gradeCounter rather than 10, the output for this
program would display an incorrect value, 76.
• This would occur because in the final iteration of the
while statement, gradeCounter was incremented to
the value 11.
Image suwaibah1317.blogspot.com
Converting Between Fundamental
Types Explicitly and Implicitly
• In our code, the variable average is declared to be of type double to capture the
fractional result of our calculation.
• However, total and gradeCounter are both integer variables.
• Recall that dividing two integers results in integer division, in which any fractional
part of the calculation is lost truncated).
• In the following statement:
• the division occurs first—the result’s fractional part is lost before it’s assigned to
average.
average = total / gradeCounter;
Image Credit: www.fastbooking.com
Converting Between Fundamental
Types Explicitly and Implicitly
• To perform a floating-point calculation with integers, we must create temporary
floatingpoint values.
• C++ provides the unary cast operator to accomplish this task.
• We use the cast operator static_cast<double>(total) to create a temporary
floating-point copy of its operand in parentheses—total.
• Using a cast operator in this manner is called explicit conversion. The value stored
in total is still an integer.
• The calculation now consists of a floating-point value (the temporary double
version of total) divided by the integer gradeCounter.
Image Credit: www.mag-corp.com
Assignment Operators
• C++ provides several assignment operators for
abbreviating assignment expressions.
• For example, the statement:
can be abbreviated with the addition assignment operator += as:
which adds the value of the expression on the operator’s right to the value of the
variable on the operator’s left and stores the result in the left-side variable.
c = c + 3;
c += 3;
Image Credit: www.wpclipart.com
Increment and Decrement
Operators
• In addition to the arithmetic assignment operators,
C++ also provides two unary operators for adding 1 to
or subtracting 1 from the value of a numeric variable.
• These are the unary increment operator, ++, and the unary decrement operator, --.
• A program can increment by 1 the value of a variable called c using the increment
operator, ++, rather than the expression c = c + 1 or c += 1.
• An increment or decrement operator that’s prefixed to (placed before) a variable is
referred to as the prefix increment or prefix decrement operator, respectively.
• An increment or decrement operator that’s postfixed to (placed after) a variable is
referred to as the postfix increment or postfix decrement operator, respectively.
Image Credit: www.property118.com
for Repetition Statement
• In addition to while, C++ provides the for repetition statement,
which specifies the counter-controlled repetition details in a single line of code.
• When the for statement begins executing, the control variable counter is declared
and initialized to 1. Then, the loop-continuation condition counter <= 10 is
checked. The initial value of counter is 1, so the condition is satisfied and the body
statement prints the value of counter, namely 1.
• Then, the expression ++counter increments control variable counter and the loop
begins again with the loop-continuation test. The control variable is now equal to
2, so the final value is not exceeded and the program performs the body statement
again.
• This process continues until the loop body has executed 10 times and the control
variable counter is incremented to 11—this causes the loop-continuation test to
fail and repetition to terminate.
• The program continues by performing the first statement after the for statement.
Image Credit: blog.hubspot.com2
for Statement Header Components
• Notice that the for statement header “does it all”—it specifies each of the items
needed for counter controlled repetition with a control variable.
• If there’s more than one statement in the body of the for, braces are required to
enclose the body of the loop.
do…while Repetition Statement
• The do…while repetition statement is similar to the while statement.
• In the while statement, the loop-continuation condition test occurs at the
beginning of the loop before the body of the loop executes. The do…while
statement tests the loop-continuation condition after the loop body executes;
therefore, the loop body always executes at least once.
• When a do…while terminates, execution continues with the statement after the
while clause.
• It’s not necessary to use braces in the do…while statement if there’s only one
statement in the body; however, most programmers include the braces to avoid
confusion between the while and do…while statements.
Image Credit: www.iconshock.com
One More Data Type: Char
• Character types: They can represent a single character, such as 'A' or '$'. The most
basic type is char, which is a one-byte character
• Note that when assigning a value to a char variable, you need to use single quotes:
x = 'a';
• It now becomes easy to switch between characters and numbers:
char x,y;
x = 97;
y = ‘b';
cout << static_cast<char>(x) << endl;
cout << static_cast<int>(y) << endl;
Results in:
a
98
Image Credit: www.activityvillage.co.uk
Reading Character Input
• The user enters letter grades for a course in member function inputGrades.
• In the while header the parenthesized assignment (grade = cin.get()) executes
first.
• The cin.get() function reads one character from the keyboard and stores that
character in integer variable grade.
• Normally, characters are stored in variables of type char; however, characters can
be stored in any integer data type, because types short, int and long are
guaranteed to be at least as big as type char.
• Thus, we can treat a character either as an integer or as a character, depending on
its use. For example, the statement
prints the character a and its integer value as follows:
cout << "The character (" << 'a' << ") has the value "
<< static_cast< int > ( 'a' ) << endl;
The character (a) has the value 97
Image Credit: phillyvirtual.com
switch Multiple-Selection
Statement
• C++ provides the switch multiple-selection statement
to perform many different actions based on the
possible values of a variable or expression.
• Each action is associated with the value of a constant
integral expression (i.e., any combination of
character and integer constants that evaluates to a
constant integer value).
Image Credit: www.bhamrail.com
switch Statement Details
• The switch statement consists of a series of case labels and an optional
default case.
• These are used in this example to determine which counter to increment, based
on a grade.
• When the flow of control reaches the switch, the program evaluates the
expression in the parentheses (i.e., grade) following keyword switch.
This is called the controlling expression.
• The switch statement compares the value of the controlling expression with
each case label.
• Assume the user enters the letter C as a grade. The program compares C to
each case in the switch. If a match occurs, the program executes the statements
for that case. For the letter C, the program increments cCount by 1. The break
statement causes program control to proceed with the first statement after the
switch Image Credit: www.eldontaylor.com
switch Statement Details
• The cases in our switch explicitly test for the lowercase
and uppercase versions of the letters A, B, C, D and F.
• Note the cases that test for the values 'A' and 'a‘
(both of which represent the grade A).
• Listing cases consecutively with no statements between them enables the cases to
perform the same set of statements—when the controlling expression evaluates to
either 'A' or 'a', the associated statements will execute.
• Each case can have multiple statements. The switch selection statement does not
require braces around multiple statements in each case.
• Without break statements, each time a match occurs in the switch, the statements
for that case and subsequent cases execute until a break statement or the end of
the switch is encountered.
Image Credit: www.joytime.org
Providing a default Case
• If no match occurs between the controlling expression’s value and a case label, the
default case executes.
• We use the default case in this example to process all controlling-expression
values that are neither valid grades nor newline, tab or space characters.
• If no match occurs, the default case executes, and the program prints an error
message indicating that an incorrect letter grade was entered.
• If no match occurs in a switch statement that does not contain a default case,
program control continues with the first statement after the switch.
Image Credit: devblackops.io
break Statement
• The break statement, when executed in a while, for, do…while or switch
statement, causes immediate exit from that statement.
• Program execution continues with the next statement.
• Common uses of the break statement are to escape early from a loop or to skip
the remainder of a switch statement.
Image Credit: hisamazinggloryministries.org
continue Statement
• The continue statement, when executed in a while, for or do…while statement,
skips the remaining statements in the body of that statement and proceeds with
the next iteration of the loop.
• In while and do…while statements, the loop-continuation test evaluates
immediately after the continue statement executes. In the for statement, the
increment expression executes, then the loop-continuation test evaluates.
Image Creditgorselbilgi.com
Logical Operators
• C++ provides logical operators that are used to form more complex conditions by
combining simple conditions.
• The logical operators are && (logical AND), || (logical OR) and ! (logical NOT, also
called logical negation).
Image Credit: mncriticalthinking.com
Logical AND (&&) Operator
• Suppose that we wish to ensure that two conditions are both true before we
choose a certain path of execution. In this case, we can use the && (logical AND)
operator, as follows:
• This if statement contains two simple conditions. The condition gender == 1 is
used here to determine whether a person is a female. The condition age >= 65
determines whether a person is a senior citizen. The simple condition to the left of
the && operator evaluates first. If necessary, the simple condition to the right of
the && operator evaluates next.
• As we’ll discuss shortly, the right side of a logical
AND expression is evaluated only if the left side is true.
if ( gender == 1 && age >= 65 )
++seniorFemales;
Image Credit: mncriticalthinking.com
&& (logical AND) operator
truth table
Logical OR (||) Operator
• Now let’s consider the || (logical OR) operator.
• Suppose we wish to ensure that either or both of two conditions are true before
we choose a certain path of execution. In this case, we use the || operator, as in
the following program segment:
• This preceding condition contains two simple conditions. The simple condition
semesterAverage >= 90 evaluates to determine whether the student deserves an
“A” in the course because of a solid performance throughout the semester. The
simple condition finalExam >= 90 evaluates to determine whether the student
deserves an “A” in the course because of an outstanding performance on the final
exam.
• The if statement then considers the combined condition and awards the student
an “A” if either or both of the simple conditions are true. The message “Student
grade is A” prints unless both of the simple conditions are false.
if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 ) )
cout << "Student grade is A" << endl;
Image Credit: www.playbuzz.com
Logical OR (||) Operator
Logical Negation (!) Operator
• C++ provides the ! (logical NOT, also called logical negation) operator to “reverse” a
condition’s meaning.
• The unary logical negation operator has only a single condition as an operand.
• The unary logical negation operator is placed before a condition when we are
interested in choosing a path of execution if the original condition (without the
logical negation operator) is false, such as in the following program segment:
• The parentheses around the condition grade == sentinelValue are
needed because the logical negation operator has a higher
precedence than the equality operator.
if ( !( grade == sentinelValue ) )
cout << "The next grade is " << grade << endl;
Image Credit: www.ppcplans.com
Logical Negation (!) Operator

More Related Content

What's hot

Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)Ranel Padon
 
An introduction to programming
An introduction to programmingAn introduction to programming
An introduction to programmingrprajat007
 
Introduction to Visual Basic 6.0 Fundamentals
Introduction to Visual Basic 6.0 FundamentalsIntroduction to Visual Basic 6.0 Fundamentals
Introduction to Visual Basic 6.0 FundamentalsSanay Kumar
 
Joel Landis Net Portfolio
Joel Landis Net PortfolioJoel Landis Net Portfolio
Joel Landis Net Portfoliojlshare
 
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsSAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsGaruda Trainings
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
Introduction to java netbeans
Introduction to java netbeansIntroduction to java netbeans
Introduction to java netbeansShrey Goswami
 
Java files and io streams
Java files and io streamsJava files and io streams
Java files and io streamsRubaNagarajan
 
Fundamentals of Language Processing
Fundamentals of Language ProcessingFundamentals of Language Processing
Fundamentals of Language ProcessingHemant Sharma
 
C#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developersC#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developersSanjaya Prakash Pradhan
 
Compiler Design(Nanthu)
Compiler Design(Nanthu)Compiler Design(Nanthu)
Compiler Design(Nanthu)guest91cc85
 

What's hot (20)

Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
 
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
 
An introduction to programming
An introduction to programmingAn introduction to programming
An introduction to programming
 
Introduction to Java Applications
Introduction to Java ApplicationsIntroduction to Java Applications
Introduction to Java Applications
 
Introduction to Visual Basic 6.0 Fundamentals
Introduction to Visual Basic 6.0 FundamentalsIntroduction to Visual Basic 6.0 Fundamentals
Introduction to Visual Basic 6.0 Fundamentals
 
Mvc by asp.net development company in india - part 2
Mvc by asp.net development company in india  - part 2Mvc by asp.net development company in india  - part 2
Mvc by asp.net development company in india - part 2
 
Joel Landis Net Portfolio
Joel Landis Net PortfolioJoel Landis Net Portfolio
Joel Landis Net Portfolio
 
Basic java
Basic java Basic java
Basic java
 
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsSAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
Introduction to java netbeans
Introduction to java netbeansIntroduction to java netbeans
Introduction to java netbeans
 
MVC by asp.net development company in india
MVC by asp.net development company in indiaMVC by asp.net development company in india
MVC by asp.net development company in india
 
jQuery plugins & JSON
jQuery plugins & JSONjQuery plugins & JSON
jQuery plugins & JSON
 
Java files and io streams
Java files and io streamsJava files and io streams
Java files and io streams
 
Class 1 blog
Class 1 blogClass 1 blog
Class 1 blog
 
Assembler
AssemblerAssembler
Assembler
 
Fundamentals of Language Processing
Fundamentals of Language ProcessingFundamentals of Language Processing
Fundamentals of Language Processing
 
Linkers
LinkersLinkers
Linkers
 
C#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developersC#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developers
 
Compiler Design(Nanthu)
Compiler Design(Nanthu)Compiler Design(Nanthu)
Compiler Design(Nanthu)
 

Viewers also liked

8门编程语言的设计思考
8门编程语言的设计思考8门编程语言的设计思考
8门编程语言的设计思考Ray Song
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language CourseVivek chan
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarSivakumar R D .
 
Practicle application of maxima and minima
Practicle application of maxima and minimaPracticle application of maxima and minima
Practicle application of maxima and minimaBritish Council
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
Control structure C++
Control structure C++Control structure C++
Control structure C++Anil Kumar
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programAAKASH KUMAR
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Rasan Samarasinghe
 

Viewers also liked (20)

8门编程语言的设计思考
8门编程语言的设计思考8门编程语言的设计思考
8门编程语言的设计思考
 
C++ 11
C++ 11C++ 11
C++ 11
 
098ca session7 c++
098ca session7 c++098ca session7 c++
098ca session7 c++
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
OOP
OOPOOP
OOP
 
class c++
class c++class c++
class c++
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
Set Theory In C++
Set Theory In C++Set Theory In C++
Set Theory In C++
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
Practicle application of maxima and minima
Practicle application of maxima and minimaPracticle application of maxima and minima
Practicle application of maxima and minima
 
Pointer in c++ part1
Pointer in c++ part1Pointer in c++ part1
Pointer in c++ part1
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
C++11
C++11C++11
C++11
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ program
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 

Similar to Intro To C++ - Class 14 - Midterm Review

Intro to C++ - Class 2 - Objects & Classes
Intro to C++ - Class 2 - Objects & ClassesIntro to C++ - Class 2 - Objects & Classes
Intro to C++ - Class 2 - Objects & ClassesBlue Elephant Consulting
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]Rome468
 
Book management system
Book management systemBook management system
Book management systemSHARDA SHARAN
 
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)pbarasia
 
Cs6301 programming and datastactures
Cs6301 programming and datastacturesCs6301 programming and datastactures
Cs6301 programming and datastacturesK.s. Ramesh
 
Principal of objected oriented programming
Principal of objected oriented programming Principal of objected oriented programming
Principal of objected oriented programming Rokonuzzaman Rony
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...NicheTech Com. Solutions Pvt. Ltd.
 
object oriented programming part inheritance.pptx
object oriented programming part inheritance.pptxobject oriented programming part inheritance.pptx
object oriented programming part inheritance.pptxurvashipundir04
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNicole Gomez
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verQrembiezs Intruder
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEMMansi Tyagi
 
His162013 140529214456-phpapp01
His162013 140529214456-phpapp01His162013 140529214456-phpapp01
His162013 140529214456-phpapp01Getachew Ganfur
 
Principles of object oriented programing
Principles of object oriented programingPrinciples of object oriented programing
Principles of object oriented programingAhammed Alamin
 

Similar to Intro To C++ - Class 14 - Midterm Review (20)

Intro to C++ - Class 2 - Objects & Classes
Intro to C++ - Class 2 - Objects & ClassesIntro to C++ - Class 2 - Objects & Classes
Intro to C++ - Class 2 - Objects & Classes
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]
 
Book management system
Book management systemBook management system
Book management system
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)
 
Cs6301 programming and datastactures
Cs6301 programming and datastacturesCs6301 programming and datastactures
Cs6301 programming and datastactures
 
73d32 session1 c++
73d32 session1 c++73d32 session1 c++
73d32 session1 c++
 
ArduinoWorkshop2.pdf
ArduinoWorkshop2.pdfArduinoWorkshop2.pdf
ArduinoWorkshop2.pdf
 
Principal of objected oriented programming
Principal of objected oriented programming Principal of objected oriented programming
Principal of objected oriented programming
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
 
object oriented programming part inheritance.pptx
object oriented programming part inheritance.pptxobject oriented programming part inheritance.pptx
object oriented programming part inheritance.pptx
 
C++
C++C++
C++
 
Intro To C++ - Class 3 - Sample Program
Intro To C++ - Class 3 - Sample ProgramIntro To C++ - Class 3 - Sample Program
Intro To C++ - Class 3 - Sample Program
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEM
 
C++ for hackers
C++ for hackersC++ for hackers
C++ for hackers
 
His162013 140529214456-phpapp01
His162013 140529214456-phpapp01His162013 140529214456-phpapp01
His162013 140529214456-phpapp01
 
Principles of object oriented programing
Principles of object oriented programingPrinciples of object oriented programing
Principles of object oriented programing
 
C question
C questionC question
C question
 

Recently uploaded

Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 

Recently uploaded (20)

Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

Intro To C++ - Class 14 - Midterm Review

  • 1. An Introduction To Software Development Using C++ Class #14: Review For Midterm
  • 2. What’s Up With This Object Orientated Stuff? Procedural Languages One long piece of code where data and logic are all mixed in together. 1 # 2 # Sample program that demonstrates the print function. 3 # 4 5 # Prints 7 6 print(3 + 4) 7 8 # Prints “Hello World!” in two lines. 9 print("Hello") 10 print("World!") 11 12 # Prints multiple values with a single print function call. 13 print("My favorite numbers are", 3 + 4, "and", 3 + 10) 14 15 # Prints three lines of text with a blank line. 16 print("Goodbye") 17 print() 18 print("Hope to see you again")
  • 3. What’s Up With This Object Orientated Stuff? • Each object represents a different part of the application. • Each object contains it’s own data & it’s own logic. • The objects communicate between themselves. • Objects are designed to represent how you talk and think about the actual problem. • Objects are meant to make thinking about your program easier. • Object orientation is just an idea that is supported by C++
  • 4. I Know How To Program, Why Bother With This C++ Stuff? • Why is so much attention today focused on object-oriented programming in general and C++ in particular? ANSWER: Object-oriented programming enables the programmer to build reusable software components that model items in the real world. Building software quickly, correctly, and economically has been an elusive goal in the software industry. The modular, object-oriented design and implementation approach has been found to increase productivity 10 to 100 times over conventional programming languages while reducing development time, errors, and cost. C++ is extremely popular because it is a superset of the widely used C programming language. Programmers already familiar with C have an easier time learning C++. Image Credit: www.dreamstime.com
  • 5. What are “Objects”? Objects (both software and real) have two ways that they can be represented: A. Attributes B. Behaviors
  • 6. What are “Objects”? The gas pedal hides from the driver the complex mechanisms that actually make the car go faster, just as the brake pedal hides the mechanisms that slow the car, and the steering wheel “hides” the mechanisms that turn the car. This enables people with little or no knowledge of how engines, braking and steering mechanisms work to drive a car easily. Objects work the same way – they hide your code from other developers so that they don’t have to know HOW you did something, just what your code DOES.
  • 7. Member Functions and Classes Performing a task in a program requires a member function, which houses the program statements that actually perform its task. The member function hides these statements from its user, just as the accelerator pedal of a car hides from the driver the mechanisms of making the car go faster. In C++, we create a program unit called a class to house the set of member functions that perform the class’s tasks. For example, a class that represents a bank account might contain one member function to deposit money to an account, another to withdraw money from an account and a third to inquire what the account’s current balance is. A class is similar in concept to a car’s engineering drawings, which house the design of an accelerator pedal, steering wheel, and so on.
  • 8. What Is A Class? • It’s a blueprint, the definition, the description. • It is not the thing itself! Image Credit: www.chickslovethecar.com
  • 9. Instantiation You must build an object of a class before a program can perform the tasks that the class’s member functions define. The process of doing this is called instantiation. An object is then referred to as an instance of its class.
  • 10. Object • The object is created from the class • One class can create multiple objects Image Credit: http://8z4.net/images/blueprint-/5.html
  • 11. Reuse You can reuse a class many times to build many objects. Reuse of existing classes when building new classes and programs saves time and effort. Reuse also helps you build more reliable and effective systems, because existing classes and components often have gone through extensive testing, debugging and performance tuning.
  • 12. Messages and Member Function Calls When you drive a car, pressing its gas pedal sends a message to the car to perform a task—that is, to go faster. Similarly, you send messages to an object. Each message is implemented as a member function call that tells a member function of the object to perform its task. For example, a program might call a particular bank account object’s deposit member function to increase the account’s balance.
  • 13. Attributes and Data Members A car, besides having capabilities to accomplish tasks, also has attributes, such as its color, its number of doors, the amount of gas in its tank, its current speed and its record of total miles driven (i.e., its odometer reading). As you drive an actual car, these attributes are carried along with the car. Every car maintains its own attributes. For example, each car knows how much gas is in its own gas tank, but not how much is in the tanks of other cars. An object, similarly, has attributes that it carries along as it’s used in a program. These attributes are specified as part of the object’s class. For example, a bank account object has a balance attribute that represents the amount of money in the account. Each bank account object knows the balance in the account it represents, but not the balances of the other accounts in the bank. Attributes are specified by the class’s data members.
  • 14. Encapsulation Classes encapsulate (i.e., wrap) attributes and member functions into objects—an object’s attributes and member functions are intimately related. Objects may communicate with one another, but they’re normally not allowed to know how other objects are implemented—implementation details are hidden within the objects themselves. This information hiding, as we’ll see, is crucial to good software engineering.
  • 16. Taking Apart Our First Program • Comments: lines 1 & 2 – Comments each begin with //, indicating that the remainder of each line is a comment. You insert comments to document your programs and to help other people read and understand them. – Comments do not cause the computer to perform any action when the program is run—they’re ignored by the C++ compiler and do not cause any machine-language object code to be generated. – A comment beginning with // is called a single-line comment because it terminates at the end of the current line. [Note: You also may use C’s style in which a comment—possibly containing many lines—begins with /* and ends with */.] // Title: You’re Very 1st Ever C++ Program // Description: Program to print some text on the screen
  • 17. Taking Apart Our First Program • Preprocessor Directive: line 3 – This statement is a preprocessor directive, which is a message to the C++ preprocessor (processing done BEFORE compiling happens). Lines that begin with # are processed by the preprocessor before the program is compiled. – This line notifies the preprocessor to include in the program the contents of the input/output stream header <iostream>. – This header must be included for any program that outputs data to the screen or inputs data from the keyboard using C++’s stream input/output. #include <iostream> // allows program to output data to the screen
  • 18. Taking Apart Our First Program • Main Function: line 6 – The main function is a part of every C++ program. – The parentheses after main indicate that main is a program building block called a function. – C++ programs typically consist of one or more functions and classes. Exactly one function in every program must be named main. – C++ programs begin executing at function main, even if main is not the first function in the program. int main()
  • 19. Taking Apart Our First Program • Main Function: line 6 – The keyword int to the left of main indicates that main “returns” an integer (whole number) value. A keyword is a word in code that is reserved by C++ for a specific use. – The left brace, {, (line 7) must begin the body of every function. A corresponding right brace, }, (line 11) must end each function’s body. int main() { } // end function main
  • 20. Taking Apart Our First Program • An Output Statement: line 8 – This command instructs the computer to perform an action—namely, to print the string of characters contained between the double quotation marks. – White-space characters in strings are not ignored by the compiler. – The entire line 8, including std::cout, the << operator, the string “Hello World!n" and the semicolon (;), is called a statement. – Every C++ statement must end with a semicolon (also known as the statement terminator). – Preprocessor directives (like #include) do not end with a semicolon. std::cout << “Hello World!n"; // display message
  • 21. • An Output Statement: line 8 – Output and input in C++ are accomplished with streams of characters. – Thus, when the preceding statement is executed, it sends the stream of characters Hello World!n to the standard output stream object—std::cout— which is normally “connected” to the screen. std::cout << “Hello World!n"; // display message Taking Apart Our First Program
  • 22. • The std Namespace – The std:: before cout is required when we use names that we’ve brought into the program by the preprocessor directive #include <iostream>. – The notation std::cout specifies that we are using a name, in this case cout, that belongs to “namespace” std. – The names cin (the standard input stream) and cerr (the standard error stream) also belong to namespace std. – For now, you should simply remember to include std:: before each mention of cout, cin and cerr in a program. std::cout << “Hello World!n"; // display message Taking Apart Our First Program
  • 23. Taking Apart Our First Program • The Stream Insertion Operator and Escape Sequences – The << operator is referred to as the stream insertion operator. – When this program executes, the value to the operator’s right, the right operand, is inserted in the output stream. – Notice that the operator points in the direction of where the data goes. The right operand’s characters normally print exactly as they appear between the double quotes. std::cout << “Hello World!n"; // display message
  • 24. Taking Apart Our First Program • The Stream Insertion Operator and Escape Sequences – However, the characters n are not printed on the screen. The backslash () is called an escape character. – It indicates that a “special” character is to be output. When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. – The escape sequence n means newline. It causes the cursor (i.e., the current screen-position indicator) to move to the beginning of the next line on the screen. std::cout << “Hello World!n"; // display message
  • 25. Taking Apart Our 2nd Program • Variable Declarations – These are declarations. The identifiers number1, number2 and sum are the names of variables. – A variable is a location in the computer’s memory where a value can be stored for use by a program. – These declarations specify that the variables number1, number2 and sum are data of type int, meaning that these variables will hold integer values, i.e., whole numbers such as 7, –11, 0 and 31914. All variables must be declared with a name and a data type before they can be used in a program. // variable declarations int number1; // first integer to add int number2; // second integer to add int sum; // sum of number1 and number2
  • 26. Taking Apart Our 2nd Program • Placement of Variable Declarations – Declarations of variables can be placed almost anywhere in a program, but they must appear before their corresponding variables are used in the program. // variable declarations int number1; // first integer to add int number2; // second integer to add int sum; // sum of number1 and number2 std::cout << "Enter first integer: "; // prompt user for data int number1; // first integer to add std::cin >> number1; // read first integer from user into number1 Image Credit: www.dreamstime.com
  • 27. Taking Apart Our 2nd Program • Obtaining the First Value from the User – This statement uses the standard input stream object cin (of namespace std) and the stream extraction operator, >>, to obtain a value from the keyboard. – We like to describe the preceding statement as, “std::cin gives a value to number1” or simply “std::cin gives number1.” – When the computer executes the preceding statement, it waits for the user to enter a value for variable number1. – The computer converts the character representation of the number to an integer and assigns (i.e., copies) this number (or value) to the variable number1. Any subsequent references to number1 in this program will use this same value std::cin >> number1; // read first integer from user into number1 Image Credit: alsanda.wordpress.com
  • 28. Taking Apart Our 2nd Program • Calculating the Sum of the Values Input by the User – The assignment stmt adds the values of variables number1 and number2 and assigns the result to variable sum using the assignment operator =. – The statement is read as, “sum gets the value of number1 + number2.” – Most calculations are performed in assignment statements. The = operator and the + operator are called binary operators because each has two operands. – In the case of the + operator, the two operands are number1 and number2. In the case of the preceding = operator, the two operands are sum and the value of the expression number1 + number2. sum = number1 + number2; // add the numbers; store result in sum Image Credit: www.clipartpanda.com
  • 29. Taking Apart Our 2nd Program • Calculations can also be performed in output statements. – We could have combined the separate addition and then print statements into a single statement. – This would have eliminated the need for the variable sum. std::cout << "Sum is " << number1 + number2 << std::endl; Image Credit: www.property118.com
  • 30. Let’s Talk About C++ Math! Normal Stuff Weird Stuff 5%2 = 1 Image Credit: www.wired.co.uk
  • 31. Modulo (%) Is Your Friend • A man has 113 cans of Coke. He also has a group of boxes that can hold 12 cans each. How many cans will he have left over once he’s loaded all of the boxes? • On a military base the clock on the wall says that the time is 23:00. What time of day is this? • My friend has 10,432 ping pong balls that he needs to put into storage. My car can transport 7,239 balls. How many will be left after I leave?
  • 32. What Comes First? Precedence Rules • The precedence rules you learned in algebra apply during the evaluation of arithmetic expressions in C++: – Unary negation is evaluated next, before multiplication, division, and remainder. – Multiplication, division, and remainder are evaluated before addition and subtraction. – Addition and subtraction are evaluated before assignment. – With one exception, operations of equal precedence are left associative, so they are evaluated from left to right. Assignment operations are right associative, so consecutive instances of these are evaluated from right to left. – You can use parentheses to change the order of evaluation • "PMDAS", which is turned into the phrase "Push My Dear Aunt Sally". It stands for "Parentheses, Multiplication and Division, and Addition and Subtraction". -5 2+3*4/6 sum = 2+3 2+3*4/6 sum = 12 (2+3)*4/5 Image Credit: www.pinterest.com
  • 33. How To Make Decisions In C++ • We’ll now introduce a simple version of C++’s if statement that allows a program to take alternative action based on whether a condition is true or false. • If the condition is true, the statement in the body of the if statement is executed. If the condition is false, the body statement is not executed. • Conditions in if statements can be formed by using the equality operators and relational operators. • The relational operators all have the same level of precedence and associate left to right. The equality operators both have the same level of precedence, which is lower than that of the relational operators, and associate left to right. Image Creditpositivityworks.wordpress.com
  • 35. Under The Hood w/ Program #3 • using Directives – These statements are using directives that eliminate the need to repeat the std:: prefix as we did in earlier programs. – We can now write cout instead of std::cout, cin instead of std::cin and endl instead of std::endl, respectively, in the remainder of the program!!! – In place of these 3 lines, many programmers prefer to use the directive: which enables a program to use all the names in any standard C++ header (such as <iostream>) that a program might include. From this point forward, we’ll use this technique in our programs. using std::cout; // program uses cout using std::cin; // program uses cin using std::endl; // program uses endl using namespace std; Image Credit: osdelivers.blackducksoftware.com
  • 36. Under The Hood w/ Program #3 • Comparing Numbers – The if statement compares the values of variables number1 and number2 to test for equality. – If the values are equal, the statement displays a line of text indicating that the numbers are equal. – If the conditions are true in one or more of the if statements starting in the other lines, the corresponding body statement displays an appropriate line of text. – Each if statement the program has a single statement in its body and each body statement is indented. if ( number1 == number2 ) cout << number1 << " == " << number2 << endl; Image Credit: www.sellerexpress.com
  • 37. Why OO? • Object-Oriented Programming has the following advantages over conventional approaches: – OOP provides a clear modular structure for programs which makes it good for defining abstract datatypes where implementation details are hidden and the unit has a clearly defined interface. – OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones. – OOP provides a good framework for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces. Image Credit: betanews.com
  • 38. Let’s Get Some Class • Class GradeBook – Before function main can create a GradeBook object, we must tell the compiler what member functions and data members belong to the class. The GradeBook class definition contains a member function called displayMessage that displays a message on the screen. – We need to make an object of class GradeBook and call its displayMessage member function to display the welcome message. – By convention, the name of a user-defined class begins with a capital letter, and for readability, each subsequent word in the class name begins with a capital letter. The class definition terminates with a semicolon. // GradeBook class definition class GradeBook { public: // function that displays a welcome message to the GradeBook user void displayMessage() { cout << "Welcome to the Grade Book!" << endl; } // end function displayMessage }; // end class GradeBook Image Credit: simpsons.wikia.com
  • 39. Let’s Get Some Class • Class GradeBook – The class definition begins with the keyword class followed by the class name GradeBook. By convention, the name of a user-defined class begins with a capital letter, and for readability, each subsequent word in the class name begins with a capital letter. – Every class’s body is enclosed in a pair of left and right braces ({ and }) – The class definition terminates with a semicolon. // GradeBook class definition class GradeBook { public: // function that displays a welcome message to the GradeBook user void displayMessage() { cout << "Welcome to the Grade Book!" << endl; } // end function displayMessage }; // end class GradeBook Image Credit: www.aptce.org
  • 40. Let’s Get Some Class • Class GradeBook – The next line contains the keyword public, which is an access specifier. After this we define member function displayMessage. This member function appears after access specifier public: to indicate that the function is “available to the public”—that is, it can be called by other functions in the program (such as main) – Access specifiers are always followed by a colon (:). // GradeBook class definition class GradeBook { public: // function that displays a welcome message to the GradeBook user void displayMessage() { cout << "Welcome to the Grade Book!" << endl; } // end function displayMessage }; // end class GradeBook Image Credit: sahamparsa.blogspot.com
  • 41. Let’s Get Some Class • Each function in a program performs a task and may return a value when it completes its task—for example, a function might perform a calculation, then return the result of that calculation. • When you define a function, you must specify a return type to indicate the type of the value returned by the function when it completes its task. • The keyword void to the left of the function name displayMessage is the function’s return type. • Return type void indicates that displayMessage will not return any data to its calling function when it completes its task. void displayMessage() Return type Function Image Credit: www.iconshut.com
  • 42. Let’s Get Some Class • The name of the member function, displayMessage, follows the return type. By convention, function names begin with a lowercase first letter and all subsequent words in the name begin with a capital letter. • The parentheses after the member function name indicate that this is a function. An empty set of parentheses indicates that this member function does not require additional data to perform its task. • Every function’s body is delimited by left and right braces ({ and }). The body of a function contains statements that perform the function’s task. In this case, member function displayMessage contains one statement that displays the message "Welcome to the Grade Book!". After this statement executes, the function has completed its task. void displayMessage() { cout << "Welcome to the Grade Book!" << endl; } // end function displayMessage {}
  • 43. The UML (Unified Modeling Language) • Although many different OOAD processes exist, a single graphical language for communicating the results of any OOAD process has come into wide use. This language, known as the Unified Modeling Language (UML), is now the most widely used graphical scheme for modeling object-oriented systems. • In the UML, each class is modeled in a UML class diagram as a rectangle with three compartments. The top compartment contains the class’s name centered horizontally and in boldface type. The middle compartment contains the class’s attributes, which correspond to data members in C++. • This compartment is currently empty, because class GradeBook does not have any attributes. The bottom compartment contains the class’s operations, which correspond to member functions in C++.
  • 44. Defining a Member Function with a Parameter Pressing on a car’s gas pedal sends two messages to the car: 1. Go faster 2. Go how much faster? So the message to the car includes both the task to perform and additional information that helps the car perform the task. This additional information is known as a parameter — the value of the parameter helps the car determine how fast to accelerate.
  • 45. Functions, Parameters, & Arguments • A member function can require one or more parameters that represent additional data it needs to perform its task. • A function call supplies values—called arguments—for each of the function’s parameters. • For example, to make a deposit into a bank account, suppose a deposit member function of an Account class specifies a parameter that represents the deposit amount. • When the deposit member function is called, an argument value representing the deposit amount is copied to the member function’s parameter. • The member function then adds that amount to the account balance. int makeDeposit(depositAmount) Image Credit: uldissprogis.com
  • 46. Let’s Take A Time Out!
  • 47. Let’s Talk About Strings • We create a variable of type string called nameOfCourse that will be used to store the course name entered by the user. • A variable of type string represents a string of characters such as “CS101 Introduction to C++ Programming". • A string is actually an object of the C++ Standard Library class string. • This class is defined in header <string>, and the name string, like cout, belongs to namespace std. • To enable the program to compile, we include the <string> header. The using directive allows us to simply write string rather than std::string. For now, you can think of string variables like variables of other types such as int. #include <string> // program uses C++ standard string class using namespace std;
  • 48. Why Make Things Harder? • In this example, we’d like the user to type the complete course name and press Enter to submit it to the program, and we’d like to store the entire course name in the string variable nameOfCourse. • The function call getline( cin, nameOfCourse ) reads characters (including the space characters that separate the words in the input) from the standard input stream object cin (i.e., the keyboard) until the newline character is encountered, places the characters in the string variable nameOfCourse and discards the newline character. • When you press Enter while typing program input, a newline is inserted in the input stream. • The <string> header must be included in the program to use function getline, which belongs to namespace std. getline( cin, nameOfCourse ); // read a course name with blanks Image Credit: www.amazon.com
  • 49. Functions, Parameters, & Arguments • The next line calls myGradeBook’s displayMessage member function. • The nameOfCourse variable in parentheses is the argument that’s passed to member function displayMessage so that it can perform its task. • The value of variable nameOfCourse in main is copied to member function displayMessage’s parameter courseName. • When you execute this program, member function displayMessage outputs as part of the welcome message the course name you type (in our sample execution, “COP2271 Introduction to C++ Programming”). myGradeBook.displayMessage(nameOfCourse); // call object's displayMessage function Argument Member Function Image Credit: mathinsight.org
  • 50. Functions, Parameters, & Arguments • To specify in a function definition that the function requires data to perform its task, you place additional information in the function’s parameter list, which is located in the parentheses following the function name. • The parameter list may contain any number of parameters, including none at all to indicate that a function does not require any parameters. • Member function displayMessage’s parameter list declares that the function requires one parameter. • Each parameter specifies a type and an identifier. The type string and the identifier courseName indicate that member function displayMessage requires a string to perform its task. • The member function body uses the parameter courseName to access the value that’s passed to the function in the function call. void displayMessage( string courseName ) Image Credit: commons.wikimedia.org
  • 51. Functions, Parameters, & Arguments • A function can specify multiple parameters by separating each from the next with a comma. • The number and order of arguments in a function call must match the number and order of parameters in the parameter list of the called member function’s header. • Also, the argument types in the function call must be consistent with the types of the corresponding parameters in the function header. • In our example, the one string argument in the function call (i.e., nameOfCourse) exactly matches the one string parameter in the member-function definition (i.e., courseName). void displayMessage( string courseName ) myGradeBook.displayMessage(nameOfCourse); // call object's displayMessage function Image Credit: sbkb.org
  • 52. Updated UML Class Diagram for Class GradeBook • This GradeBook class contains public member function displayMessage. However, this version of displayMessage has a parameter. • The UML models a parameter by listing the parameter name, followed by a colon and the parameter type in the parentheses following the operation name. • The UML has its own data types similar to those of C++. The UML is language independent— it’s used with many different programming languages—so its terminology does not exactly match that of C++. • For example, the UML type String corresponds to the C++ type string. • Member function displayMessage of class GradeBook has a string parameter named courseName, so the diagram lists courseName : String between the parentheses following the operation name displayMessage. • This version of the GradeBook class still does not have any data members.
  • 53. Local Variables • We have been declaring all of a program’s variables in its main function. • Variables declared in a function definition’s body are known as local variables and can be used only from the line of their declaration in the function to closing right brace (}) of the block in which they’re declared. • A local variable must be declared before it can be used in a function. • A local variable cannot be accessed outside the function in which it’s declared. When a function terminates, the values of its local variables are lost. Image Credit: deniseleeyohn.com
  • 54. Class Attributes • A class normally consists of one or more member functions that manipulate the attributes that belong to a particular object of the class. • Attributes are represented as variables in a class definition. Such variables are called data members and are declared inside a class definition but outside the bodies of the class’s member-function definitions. • Each object of a class maintains its own copy of its attributes in memory. These attributes exist throughout the life of the object. • The example in this section demonstrates a GradeBook class that contains a courseName data member to represent a particular GradeBook object’s course name. Image Credit: colleendilen.com
  • 55. Access Specifiers: public and private • Most data-member declarations appear after the private access specifier. Variables or functions declared after access specifier private are accessible only to member functions of the class for which they’re declared. • Thus, data member courseName can be used only in member functions setCourseName, getCourseName and displayMessage of class GradeBook. • The default access for class members is private so all members after the class header and before the first access specifier (if there are any) are private. The access specifiers public and private may be repeated, but this is unnecessary and can be confusing. • Declaring data members with access specifier private is known as data hiding. • When a program creates a GradeBook object, data member courseName is encapsulated (hidden) in the object and can be accessed only by member functions of the object’s class. In class GradeBook, member functions setCourseName and getCourseName manipulate the data member courseName directly. Image Credit: engagor.com
  • 56. Key Point • The statements each use variable courseName even though it was not declared in any of the member functions. We can do this because courseName is a data member of the class private: string courseName; // course name for this GradeBook void setCourseName( string name ) { courseName = name; // store the course name in the object } // end function setCourseName string getCourseName() { return courseName; // return the object's courseName } // end function getCourseName Image Credit: www.omgtop5.com
  • 57. Initializing Objects with Constructors • When an object of class GradeBook is created, its data member courseName is initialized to the empty string by default. • What if you want to provide a course name when you create a GradeBook object? • Each class you declare can provide a constructor that can be used to initialize an object of the class when the object is created. A constructor is a special member function that must be defined with the same name as the class, so that the compiler can distinguish it from the class’s other member functions. • An important difference between constructors and other functions is that constructors cannot return values, so they cannot specify a return type (not even void). • Normally, constructors are declared public. Image Credit: forums.autodesk.com
  • 58. Initializing Objects with Constructors • C++ requires a constructor call for each object that’s created, which helps ensure that each object is initialized properly before it’s used in a program. • The constructor call occurs implicitly when the object is created. If a class does not explicitly include a constructor, the compiler provides a default constructor—that is, a constructor with no parameters. • For example, when we create a GradeBook object, the default constructor is called. The default constructor provided by the compiler creates a GradeBook object without giving any initial values to the object’s fundamental type data members. Image Credit: www.itcuties.com
  • 59. Defining a Constructor • Defining a Constructor – We define a constructor for class GradeBook. Notice that the constructor has the same name as its class, GradeBook. – A constructor specifies in its parameter list the data it requires to perform its task. When you create a new object, you place this data in the parentheses that follow the object name. – The program shows that that class GradeBook’s constructor has a string parameter called name. The constructor does not specify a return type, because constructors cannot return values (or even void). // constructor initializes courseName with string supplied as argument GradeBook( string name ) { setCourseName( name ); // call set function to initialize courseName } // end GradeBook constructor Image Credit: www.ciconstructors.com
  • 60. Adding the Constructor to Class GradeBook’s UML Class Diagram • This UML class diagram of the GradeBook class our program, which has a constructor with a name parameter of type string (represented by type String in the UML). • Like operations, the UML models constructors in the third compartment of a class in a class diagram. • To distinguish a constructor from a class’s operations, the UML places the word “constructor” between guillemets (« and ») before the constructor’s name. • By convention, you list the class’s constructor before other operations in the third compartment.
  • 61. The Compilation and Linking Process • The diagram shown shows the compilation and linking process that results in an executable GradeBook application that can be used by instructors. • Often a class’s interface and implementation will be created and compiled by one programmer and used by a separate programmer who implements the client code that uses the class. So, the diagram shows what’s required by both the class- implementation programmer and the client- code programmer. • The dashed lines in the diagram show the pieces required by the class-implementation programmer, the client-code programmer and the GradeBook application user, respectively.
  • 62. Selection Statements in C++ •C++ provides three types of selection statements. •The if selection statement either performs (selects) an action if a condition is true or skips the action if the condition is false. •The if…else selection statement performs an action if a condition is true or performs a different action if the condition is false. Image Credit: www.bhamrail.com
  • 63. if / if … else •The if selection statement is a single-selection statement because it selects or ignores a single action. •The if…else statement is called a double-selection statement because it selects between two different actions. •The switch selection statement is called a multiple- selection statement because it selects among many different actions. Image Credit: en.wikipedia.org
  • 64. if Selection Statement •Programs use selection statements to choose among alternative courses of action. •Pseudocode –Suppose the passing grade on an exam is 60. •If student’s grade is greater than or equal to 60 •Print “Passed” –The preceding pseudocode If statement can be written in C++ as: if ( grade >= 60 ) cout << "Passed"; •The C++ code corresponds closely to the pseudocode. This is one of the properties of pseudocode that make it such a useful program development tool. Image Credit: www.if-insurance.com
  • 65. Notes About If •Decisions can be based on conditions containing relational or equality operators. •Actually, in C++, a decision can be based on any expression—if the expression evaluates to zero, it’s treated as false; if the expression evaluates to nonzero, it’s treated as true. •C++ provides the data type bool for variables that can hold only the values true and false—each of these is a C++ keyword. Image Credit: www.daniellestrickland.com
  • 66. if…else Double-Selection Statement •The if single-selection statement performs an indicated action only when the condition is true; otherwise the action is skipped. •The if…else double-selection statement allows you to specify an action to perform when the condition is true and a different action to perform when the condition is false. •Pseudocode: –If student’s grade is greater than or equal to 60 – Print “Passed” –Else – Print “Failed” Image Credit: twitter.com
  • 67. C++ Code – Using If if ( studentGrade >= 90 ) // 90 and above gets "A" cout << "A"; else if ( studentGrade >= 80 ) // 80-89 gets "B" cout << "B"; else if ( studentGrade >= 70 ) // 70-79 gets "C" cout << "C"; else if ( studentGrade >= 60 ) // 60-69 gets "D" cout << "D"; else // less than 60 gets "F" cout << "F"; Image Credit: folding.stanford.edu
  • 68. C++ Code – Using Else…If if ( studentGrade >= 90 ) // 90 and above gets "A" cout << "A"; else if ( studentGrade >= 80 ) // 80-89 gets "B" cout << "B"; else if ( studentGrade >= 70 ) // 70-79 gets "C" cout << "C"; else if ( studentGrade >= 60 ) // 60-69 gets "D" cout << "D"; else // less than 60 gets "F" cout << "F"; Image Credit: www.dental.pacific.edu
  • 69. C++’s While Repetition Statement • When the while statement begins execution, product’s value is 3. • Each repetition multiplies product by 3, so product takes on the values 9, 27, 81 and 243 successively. • When product becomes 243, the while statement condition—product <= 100— becomes false. • This terminates the repetition, so the final value of product is 243. • At this point, program execution continues with the next statement after the while statement int product = 3; while ( product <= 100 ) product = 3 * product; Image Credit: www.mikevaleriani.com
  • 70. Notes on Integer Division and Truncation • The averaging calculation performed in response to the function call in the program produces an integer result. • The sample execution indicates that the sum of the grade values is 846, which, when divided by 10, should yield 84.6—a number with a decimal point. • However, the result of the calculation total / 10 is the integer 84, because total and 10 are both integers. Dividing two integers results in integer division— any fractional part of the calculation is lost (i.e., truncated). • In the program, if we used gradeCounter rather than 10, the output for this program would display an incorrect value, 76. • This would occur because in the final iteration of the while statement, gradeCounter was incremented to the value 11. Image suwaibah1317.blogspot.com
  • 71. Converting Between Fundamental Types Explicitly and Implicitly • In our code, the variable average is declared to be of type double to capture the fractional result of our calculation. • However, total and gradeCounter are both integer variables. • Recall that dividing two integers results in integer division, in which any fractional part of the calculation is lost truncated). • In the following statement: • the division occurs first—the result’s fractional part is lost before it’s assigned to average. average = total / gradeCounter; Image Credit: www.fastbooking.com
  • 72. Converting Between Fundamental Types Explicitly and Implicitly • To perform a floating-point calculation with integers, we must create temporary floatingpoint values. • C++ provides the unary cast operator to accomplish this task. • We use the cast operator static_cast<double>(total) to create a temporary floating-point copy of its operand in parentheses—total. • Using a cast operator in this manner is called explicit conversion. The value stored in total is still an integer. • The calculation now consists of a floating-point value (the temporary double version of total) divided by the integer gradeCounter. Image Credit: www.mag-corp.com
  • 73. Assignment Operators • C++ provides several assignment operators for abbreviating assignment expressions. • For example, the statement: can be abbreviated with the addition assignment operator += as: which adds the value of the expression on the operator’s right to the value of the variable on the operator’s left and stores the result in the left-side variable. c = c + 3; c += 3; Image Credit: www.wpclipart.com
  • 74. Increment and Decrement Operators • In addition to the arithmetic assignment operators, C++ also provides two unary operators for adding 1 to or subtracting 1 from the value of a numeric variable. • These are the unary increment operator, ++, and the unary decrement operator, --. • A program can increment by 1 the value of a variable called c using the increment operator, ++, rather than the expression c = c + 1 or c += 1. • An increment or decrement operator that’s prefixed to (placed before) a variable is referred to as the prefix increment or prefix decrement operator, respectively. • An increment or decrement operator that’s postfixed to (placed after) a variable is referred to as the postfix increment or postfix decrement operator, respectively. Image Credit: www.property118.com
  • 75. for Repetition Statement • In addition to while, C++ provides the for repetition statement, which specifies the counter-controlled repetition details in a single line of code. • When the for statement begins executing, the control variable counter is declared and initialized to 1. Then, the loop-continuation condition counter <= 10 is checked. The initial value of counter is 1, so the condition is satisfied and the body statement prints the value of counter, namely 1. • Then, the expression ++counter increments control variable counter and the loop begins again with the loop-continuation test. The control variable is now equal to 2, so the final value is not exceeded and the program performs the body statement again. • This process continues until the loop body has executed 10 times and the control variable counter is incremented to 11—this causes the loop-continuation test to fail and repetition to terminate. • The program continues by performing the first statement after the for statement. Image Credit: blog.hubspot.com2
  • 76. for Statement Header Components • Notice that the for statement header “does it all”—it specifies each of the items needed for counter controlled repetition with a control variable. • If there’s more than one statement in the body of the for, braces are required to enclose the body of the loop.
  • 77. do…while Repetition Statement • The do…while repetition statement is similar to the while statement. • In the while statement, the loop-continuation condition test occurs at the beginning of the loop before the body of the loop executes. The do…while statement tests the loop-continuation condition after the loop body executes; therefore, the loop body always executes at least once. • When a do…while terminates, execution continues with the statement after the while clause. • It’s not necessary to use braces in the do…while statement if there’s only one statement in the body; however, most programmers include the braces to avoid confusion between the while and do…while statements. Image Credit: www.iconshock.com
  • 78. One More Data Type: Char • Character types: They can represent a single character, such as 'A' or '$'. The most basic type is char, which is a one-byte character • Note that when assigning a value to a char variable, you need to use single quotes: x = 'a'; • It now becomes easy to switch between characters and numbers: char x,y; x = 97; y = ‘b'; cout << static_cast<char>(x) << endl; cout << static_cast<int>(y) << endl; Results in: a 98 Image Credit: www.activityvillage.co.uk
  • 79. Reading Character Input • The user enters letter grades for a course in member function inputGrades. • In the while header the parenthesized assignment (grade = cin.get()) executes first. • The cin.get() function reads one character from the keyboard and stores that character in integer variable grade. • Normally, characters are stored in variables of type char; however, characters can be stored in any integer data type, because types short, int and long are guaranteed to be at least as big as type char. • Thus, we can treat a character either as an integer or as a character, depending on its use. For example, the statement prints the character a and its integer value as follows: cout << "The character (" << 'a' << ") has the value " << static_cast< int > ( 'a' ) << endl; The character (a) has the value 97 Image Credit: phillyvirtual.com
  • 80. switch Multiple-Selection Statement • C++ provides the switch multiple-selection statement to perform many different actions based on the possible values of a variable or expression. • Each action is associated with the value of a constant integral expression (i.e., any combination of character and integer constants that evaluates to a constant integer value). Image Credit: www.bhamrail.com
  • 81. switch Statement Details • The switch statement consists of a series of case labels and an optional default case. • These are used in this example to determine which counter to increment, based on a grade. • When the flow of control reaches the switch, the program evaluates the expression in the parentheses (i.e., grade) following keyword switch. This is called the controlling expression. • The switch statement compares the value of the controlling expression with each case label. • Assume the user enters the letter C as a grade. The program compares C to each case in the switch. If a match occurs, the program executes the statements for that case. For the letter C, the program increments cCount by 1. The break statement causes program control to proceed with the first statement after the switch Image Credit: www.eldontaylor.com
  • 82. switch Statement Details • The cases in our switch explicitly test for the lowercase and uppercase versions of the letters A, B, C, D and F. • Note the cases that test for the values 'A' and 'a‘ (both of which represent the grade A). • Listing cases consecutively with no statements between them enables the cases to perform the same set of statements—when the controlling expression evaluates to either 'A' or 'a', the associated statements will execute. • Each case can have multiple statements. The switch selection statement does not require braces around multiple statements in each case. • Without break statements, each time a match occurs in the switch, the statements for that case and subsequent cases execute until a break statement or the end of the switch is encountered. Image Credit: www.joytime.org
  • 83. Providing a default Case • If no match occurs between the controlling expression’s value and a case label, the default case executes. • We use the default case in this example to process all controlling-expression values that are neither valid grades nor newline, tab or space characters. • If no match occurs, the default case executes, and the program prints an error message indicating that an incorrect letter grade was entered. • If no match occurs in a switch statement that does not contain a default case, program control continues with the first statement after the switch. Image Credit: devblackops.io
  • 84. break Statement • The break statement, when executed in a while, for, do…while or switch statement, causes immediate exit from that statement. • Program execution continues with the next statement. • Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch statement. Image Credit: hisamazinggloryministries.org
  • 85. continue Statement • The continue statement, when executed in a while, for or do…while statement, skips the remaining statements in the body of that statement and proceeds with the next iteration of the loop. • In while and do…while statements, the loop-continuation test evaluates immediately after the continue statement executes. In the for statement, the increment expression executes, then the loop-continuation test evaluates. Image Creditgorselbilgi.com
  • 86. Logical Operators • C++ provides logical operators that are used to form more complex conditions by combining simple conditions. • The logical operators are && (logical AND), || (logical OR) and ! (logical NOT, also called logical negation). Image Credit: mncriticalthinking.com
  • 87. Logical AND (&&) Operator • Suppose that we wish to ensure that two conditions are both true before we choose a certain path of execution. In this case, we can use the && (logical AND) operator, as follows: • This if statement contains two simple conditions. The condition gender == 1 is used here to determine whether a person is a female. The condition age >= 65 determines whether a person is a senior citizen. The simple condition to the left of the && operator evaluates first. If necessary, the simple condition to the right of the && operator evaluates next. • As we’ll discuss shortly, the right side of a logical AND expression is evaluated only if the left side is true. if ( gender == 1 && age >= 65 ) ++seniorFemales; Image Credit: mncriticalthinking.com
  • 88. && (logical AND) operator truth table
  • 89. Logical OR (||) Operator • Now let’s consider the || (logical OR) operator. • Suppose we wish to ensure that either or both of two conditions are true before we choose a certain path of execution. In this case, we use the || operator, as in the following program segment: • This preceding condition contains two simple conditions. The simple condition semesterAverage >= 90 evaluates to determine whether the student deserves an “A” in the course because of a solid performance throughout the semester. The simple condition finalExam >= 90 evaluates to determine whether the student deserves an “A” in the course because of an outstanding performance on the final exam. • The if statement then considers the combined condition and awards the student an “A” if either or both of the simple conditions are true. The message “Student grade is A” prints unless both of the simple conditions are false. if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 ) ) cout << "Student grade is A" << endl; Image Credit: www.playbuzz.com
  • 90. Logical OR (||) Operator
  • 91. Logical Negation (!) Operator • C++ provides the ! (logical NOT, also called logical negation) operator to “reverse” a condition’s meaning. • The unary logical negation operator has only a single condition as an operand. • The unary logical negation operator is placed before a condition when we are interested in choosing a path of execution if the original condition (without the logical negation operator) is false, such as in the following program segment: • The parentheses around the condition grade == sentinelValue are needed because the logical negation operator has a higher precedence than the equality operator. if ( !( grade == sentinelValue ) ) cout << "The next grade is " << grade << endl; Image Credit: www.ppcplans.com

Editor's Notes

  1. New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.