Module 3:
Programming Concepts
(Using C++)
Slide 1
Reference:
Slide 2
Object Oriented Programming
• Abbreviated OOP
• Used for many modern programs
• Program is viewed as interacting objects
– Each object contains algorithms to describe its behavior
– Program design phase involves designing objects and
their algorithms
Slide 3
OOP Characteristics
• Encapsulation
– Information hiding
– Objects contain their own data and algorithms
• Inheritance
– Writing reusable code
– Objects can inherit characteristics from other objects
• Polymorphism
– A single name can have multiple meanings depending
on its context
Slide 4
C++ History
• C developed by Dennis Ritchie at AT&T
Bell Labs in the 1970s.
– Used to maintain UNIX systems
– Many commercial applications written in c
• C++ developed by Bjarne Stroustrup at AT&T
Bell Labs in the 1980s.
– Overcame several shortcomings of C
– Incorporated object oriented programming
– C remains a subset of C++
Slide 5
C++ Basics
Created by David Mann, North Idaho College
Slide 6
2.1
Variables
• Variables are like small blackboards
– We can write a number on them
– We can change the number
– We can erase the number
• C++ variables are names for memory locations
– We can write a value in them
– We can change the value stored there
– We cannot erase the memory location
• Some value is always there
Slide 7
Identifiers
• Variables names are called identifiers
• Choosing variable names
– Use meaningful names that represent data to
be stored
– First character must be
• a letter
• the underscore character
– Remaining characters must be
• letters
• numbers
• underscore character
Slide 8
Keywords
• Keywords (also called reserved words)
– Are used by the C++ language
– Must be used as they are defined in
the programming language
– Cannot be used as identifiers
Slide 9
Declaring Variables
• Before use, variables must be declared
– Tells the compiler the type of data to store
Examples: int number_of_bars;
double one_weight, total_weight;
– int is an abbreviation for integer.
• could store 3, 102, 3211, -456, etc.
• number_of_bars is of type integer
– double represents numbers with a fractional
component
• could store 1.34, 4.0, -345.6, etc.
• one_weight and total_weight are both of type double
Slide 10
Declaring Variables
Two locations for variable declarations
• Immediately prior to use – At the beginning
int main() int main()
{
…
{
int sum; int sum;
sum = score1 + score 2; …
… sum = score1 +
return 0; score2;
} …
return 0; Slide 11
Declaring Variables
• Declaration syntax:
– Type_name Variable_1 , Variable_2, . . . ;
• Declaration Examples:
– double average, m_score, total_score;
– double moon_distance;
– int age, num_students;
– int cars_waiting;
Slide 12
Assignment Statements
• An assignment statement changes the value of a variable
– total_weight = one_weight + number_of_bars;
• total_weight is set to the sum one_weight + number_of_bars
– Assignment statements end with a semi-colon
– The single variable to be changed is always on the left
of the assignment operator ‘=‘
– On the right of the assignment operator can be
• Constants -- age = 21;
• Variables -- my_cost = your_cost;
• Expressions -- circumference = diameter * 3.14159;
Slide 13
Assignment Statements
• The ‘=‘ operator in C++ is not an equal sign
– The following statement cannot be true in algebra
number_of_bars = number_of_bars + 3;
– In C++ it means the new value of number_of_bars
is the previous value of number_of_bars plus 3
Slide 14
Initializing Variables
• Declaring a variable does not give it a value
– Giving a variable its first value is initializing the variable
• Variables are initialized in assignment statements
double mpg; // declare the variable
mpg = 26.3; // initialize the variable
• Declaration and initialization can be combined
using two methods
– Method 1
double mpg = 26.3, area = 0.0 , volume;
– Method 2
double mpg(26.3), area(0.0), volume;
Slide 15
2.2
Input and Output
• A data stream is a sequence of data
– Typically in the form of characters or numbers
• An input stream is data for the program to use
– Typically originates
• at the keyboard
• at a file
• An output stream is the program’s output
– Destination is typically
• the monitor
• a file
Slide 16
Include Directives
• Include Directives add library files to our programs
– To make the definitions of the cin and cout available to
the program:
#include <iostream>
• Using Directives include a collection of defined
names
– To make the names cin and cout available to our program:
using namespace std;
Slide 17
2.4
Flow of Control
• Flow of control
– The order in which statements are executed
• Branch
– Lets program choose between two alternatives
Slide 18
Implementing the Branch
• if-else statement is used in C++ to perform a
branch
– if (hours > 40)
gross_pay = rate * 40 + 1.5 * rate * (hours -
40);
else
gross_pay = rate * hours;
Slide 19
Simple Loops
• When an action must be repeated, a loop is used
• C++ includes several ways to create loops
• Consider the while-loop
• Example: while (count_down > 0)
{
cout << "Hello ";
count_down -= 1;
}
• Output: Hello Hello Hello
when count_down starts at 3
Slide 20
3.2
Predefined Functions
C++ comes with libraries of predefined
functions
Example: sqrt function
the_root = sqrt(9.0);
returns, or computes, the square root
of a number
The number, 9, is called the argument
the_root will contain 3.0
Slide 21
Function Calls
• sqrt(9.0) is a function call
– It invokes, or sets in action, the sqrt function
– The argument (9), can also be a variable or an
expression
• A function call can be used like any expression
– bonus = sqrt(sales) / 10;
– Cout << “The side of a square with area “ << area
<< “ is “
<< sqrt(area);
Slide 22
Function Call Syntax
• Function_name (Argument_List)
– Argument_List is a comma separated list:
(Argument_1, Argument_2, … , Argument_Last)
• Example:
– side = sqrt(area);
– cout << “2.5 to the power 3.0 is “
<< pow(2.5, 3.0);
Slide 23
Function Libraries
• Predefined functions are found in libraries
• The library must be “included” in a program
to make the functions available
• An include directive tells the compiler which
library header file to include.
• To include the math library containing sqrt():
#include <cmath>
• Newer standard libraries, such as cmath, also require
the directive
using namespace std;
Slide 24
Other Predefined Functions
• abs(x) --- int value = abs(-8);
– Returns absolute value of argument x
– Return value is of type int
– Argument is of type x
– Found in the library cstdlib
• fabs(x) --- double value = fabs(-8.0);
– Returns the absolute value of argument x
– Return value is of type double
– Argument is of type double
– Found in the library cmath
Slide 25
Type Casting
• Recall the problem with integer division:
int total_candy = 9, number_of_people = 4;
double candy_per_person;
candy_per_person = total_candy / number_of_people;
– candy_per_person = 2, not 2.25!
• A Type Cast produces a value of one type
from another type
– static_cast<double>(total_candy) produces a double
representing the integer value of total_candy
Slide 26
Type Cast Example
• int total_candy = 9, number_of_people = 4;
double candy_per_person;
candy_per_person = static_cast<double>(total_candy)
/ number_of_people;
– candy_per_person now is 2.25!
– This would also work:
candy_per_person = total_candy /
static_cast<double>( number_of_people);
– This would not!
candy_per_person = static_cast<double>( total_candy /
number_of_people);
Integer division occurs before type cast
Slide 27
3.3
User-Defined Functions
• Two components of a function definition
– Function declaration (or function prototype)
• Shows how the function is called
• Must appear in the code before the function can be called
• Syntax:
Type_returned Function_Name(Parameter_List);
;
//Comment describing what function does
– Function definition
• Describes how the function does its task
• Can appear before or after the function is called
• Syntax:
Type_returned Function_Name(Parameter_List)
{
//code to make the function work
}
Slide 28
Function Declaration
• Tells the return type
• Tells the name of the function
• Tells how many arguments are needed
• Tells the types of the arguments
• Tells the formal parameter names
– Formal parameters are like placeholders for the actual
arguments used when the function is called
– Formal parameter names can be any valid identifier
• Example:
double total_cost(int number_par, double price_par);
// Compute total cost including 5% sales tax on
// number_par items at cost of price_par each
Slide 29
Function Definition
• Provides the same information as the declaration
• Describes how the function does its task
function header
• Example:
double total_cost(int number_par, double price_par)
{
const double TAX_RATE = 0.05; //5% tax
double subtotal;
subtotal = price_par * number_par;
return (subtotal + subtotal * TAX_RATE);
}
function body
Slide 30
The Return Statement
• Ends the function call
• Returns the value calculated by the function
• Syntax:
return expression;
– expression performs the calculation
or
– expression is a variable containing the
calculated value
• Example:
return subtotal + subtotal * TAX_RATE;
Slide 31
3.5
Local Variables
• Variables declared in a function:
– Are local to that function, they cannot be used
from outside the function
– Have the function as their scope
• Variables declared in the main part of a
program:
– Are local to the main part of the program, they
cannot be used from outside the main part
– Have the main part as their scope
Slide 32
Global Constants
• Global Named Constant
– Available to more than one function as well as the
main part of the program
– Declared outside any function body
– Declared outside the main function body
– Declared before any function that uses it
• Example: const double PI = 3.14159;
double volume(double);
int main()
{…}
– PI is available to the main function and to function volume
Slide 33
Global Variables
• Global Variable -- rarely used when more
than one function must use a common
variable
– Declared just like a global constant except const
is not used
– Generally make programs more difficult to
understand and maintain
Slide 34
Formal Parameters
are Local Variables
• Formal Parameters are actually variables that are
local to the function definition
– They are used just as if they were declared in the
function body
– Do NOT re-declare the formal parameters in the
function body, they are declared in the function
declaration
• The call-by-value mechanism
– When a function is called the formal parameters
are initialized to the values of the
arguments in the function call
Slide 35
Namespaces Revisited
• The start of a file is not always the best place
for
using namespace std;
• Different functions may use different
namespaces
– Placing using namespace std; inside the starting
brace of a function
• Allows the use of different namespaces in different
functions
• Makes the “using” directive local to
the function
Slide 36