SlideShare a Scribd company logo
Topics
Topics this week
this week

Computer Programming
Computer Programming

Programming Life-Cycle Phases
Programming Life-Cycle Phases

Creating an Algorithm
Creating an Algorithm

Machine Language vs. High Level
Machine Language vs. High Level
Languages
Languages

Compilation and Execution Processes
Compilation and Execution Processes

Problem-Solving Techniques
Problem-Solving Techniques
What is Computer Programming?
What is Computer Programming?

It is the process of planning
It is the process of planning and
and
implementing
implementing a sequence of steps (called
a sequence of steps (called
instructions) for a computer to follow in
instructions) for a computer to follow in
order to solve a problem.
order to solve a problem.
STEP 1
STEP 2
STEP 3
. . .
99.99% of Programs
99.99% of Programs
 Getting some information into the
Getting some information into the
program
program
 Doing something with the
Doing something with the
information
information
 Displaying results
Displaying results
Nearly all of programs you write will involve:
Nearly all of programs you write will involve:
Previously we spoke about:
Previously we spoke about:
Programming Life Cycle
Programming Life Cycle
1 Problem-Solving Phase
Problem-Solving Phase
• Analysis and Specification
Analysis and Specification
• General Solution (Algorithm)
General Solution (Algorithm)
• Test/Verify (Desk check)
Test/Verify (Desk check)
2 Implementation Phase
Implementation Phase
• Concrete Solution (Program)
Concrete Solution (Program)
• Test/Verify
Test/Verify
3 Maintenance Phase
Maintenance Phase
• Use
Use
• Maintain (update, maintain)
Maintain (update, maintain)
A Tempting Shortcut?
A Tempting Shortcut?
GOAL
THINKING
Problem solving
CODE
Implementation
REVISE
REVISE
REVISE
DEBUG
DEBUG
DEBUG
TEST
CODE
Shortcut?
No thinking
Problem-Solving Phase
Problem-Solving Phase

ANALYZE
ANALYZE the problem and
the problem and SPECIFY
SPECIFY
what
what the solution must do.
the solution must do.

Develop
Develop and write down on a piece
and write down on a piece
of paper
of paper GENERAL SOLUTION
GENERAL SOLUTION
(ALGORITHM) to solve the problem
(ALGORITHM) to solve the problem

VERIFY
VERIFY that your solution really
that your solution really
solves the problem
solves the problem.
.

How will you know whether your
How will you know whether your
solution is correct?
solution is correct?
Example
Example
A programmer needs an algorithm to
A programmer needs an algorithm to
determine an employee’s weekly wages.
determine an employee’s weekly wages.
First think:
First think:

How would the calculations be done by
How would the calculations be done by
hand?
hand?

Is there anything that is fixed or constant?
Is there anything that is fixed or constant?

Is there anything that changes/varies
Is there anything that changes/varies
every time I do the sum?
every time I do the sum?
Analysis: One Employee’s Wages
Analysis: One Employee’s Wages
Assumptions/Known:
Assumptions/Known:
40 hours is a normal week
40 hours is a normal week
Normal Hourly Rate of pay
Normal Hourly Rate of pay
£4.00/hour
£4.00/hour
Overtime rate of pay £6.00/hour
Overtime rate of pay £6.00/hour
Variables/Things that change
Variables/Things that change
Actual hours worked in one week:
Actual hours worked in one week:
If HoursWorked are more than 40.0 then
If HoursWorked are more than 40.0 then
wages = (40.0 * NormalRate) + (HoursWorked - 40.0)
wages = (40.0 * NormalRate) + (HoursWorked - 40.0)
* OvertimeRate
* OvertimeRate
otherwise,
otherwise,
wages = HoursWorked * NormalRate
wages = HoursWorked * NormalRate
Processes/Algorithm: Calculate Weekly Wages
Processes/Algorithm: Calculate Weekly Wages
Desk Check Calculations (use for testing algorithm)
Desk Check Calculations (use for testing algorithm)
Use 2 examples of 30 hours and 50 hours
Use 2 examples of 30 hours and 50 hours
Why?
Why?
Case 1: 30 hours worked
30 x £ 4.00 = £120.00
___________
£ 120.00
Case 2: 50 hours worked
40 x £ 4.00 = £160.00
10 x £6.00 = £60.00
___________
£ 220.00
What are the employee’s wages in each case?
IPO Chart
IPO Chart
Inputs-Process-Outputs
Inputs-Process-Outputs
Inputs
Information the
computer needs
Processes
Things computer needs to do with Inputs
Outputs
Results
computer must
display
NormalHours
HoursWorked
NormalRate
OvertimeRate
If HoursWorked are more than 40.0 then
wages = (40.0 * NormalRate) + (HoursWorked
- 40.0) * OvertimeRate
otherwise,
wages = HoursWorked * NormalRate
Wages
General Algorithm to Determine an
General Algorithm to Determine an
Employee’s Weekly Wages
Employee’s Weekly Wages
1.
1. Initialise
Initialise employee’s NormalRate and
employee’s NormalRate and
OvertimeRate.
OvertimeRate.
2.
2. Get the HoursWorked this week from
Get the HoursWorked this week from
user
user
3.
3. Calculate the wages
Calculate the wages
4.
4. Display the answer
Display the answer
It is written in English!
We call this pseudocode:
Implementation
Implementation
 We cannot simply write this pseudocode
We cannot simply write this pseudocode
algorithm as a program.
algorithm as a program.
 It is merely a program DESIGN
It is merely a program DESIGN
 YOU have to convert the DESIGN to your
YOU have to convert the DESIGN to your
chosen
chosen programming language
programming language (ours at
(ours at
present is C++)
present is C++)
 A good design is one that can be easily
A good design is one that can be easily
converted into code not just C++.
converted into code not just C++.
 A poor design is difficult to convert
A poor design is difficult to convert
 A design should be “language” independent
A design should be “language” independent
• i.e. We can write the code in Java, VB etc
i.e. We can write the code in Java, VB etc
So what is a Programming Language?
So what is a Programming Language?

It is a language with strict
It is a language with strict
grammatical rules, symbols, and
grammatical rules, symbols, and
special words used to construct a
special words used to construct a
computer program.
computer program.
• Syntax = grammar
Syntax = grammar
• Semantics = meaning
Semantics = meaning
Why a programming language? What is
Why a programming language? What is
wrong with English?
wrong with English?
 Computers do not understand English!
Computers do not understand English!
 English is a
English is a natural language
natural language and
and
requires each of us to understand
requires each of us to understand
meaning by context.
meaning by context.
 For Example
For Example
• Lung Cancer in Women explodes
Lung Cancer in Women explodes
• Red Tape Holds Up New Bridges
Red Tape Holds Up New Bridges
• Hospitals are sued by 7 Foot Doctors
Hospitals are sued by 7 Foot Doctors
• Star's Broken Leg Hits Box Office
Star's Broken Leg Hits Box Office
• Villagers Grill Gas Men
Villagers Grill Gas Men
Computers are really stupid!
Computers are really stupid!
 Computers do not understand anything!
Computers do not understand anything!
• well not quite they understand what a 1
well not quite they understand what a 1
and a 0 is.
and a 0 is.
 Computers follow instructions
Computers follow instructions
• Instructions have to be written in 1s
Instructions have to be written in 1s
and 0s
and 0s
• Such instructions are called machine
Such instructions are called machine
code.
code.
• We do not write in machine code
We do not write in machine code
Machine language
Machine language
 Machine languages
Machine languages
11000000 000000000001
11000000 000000000001
000000000010
000000000010
Add contents of memory location 1 to
Add contents of memory location 1 to
contents of memory location 2
contents of memory location 2
 Not easy to write programs in!
Not easy to write programs in!
Assembly
Assembly
 ADD 1
ADD 1 2
2
 Needs an assembler to translate to machine
Needs an assembler to translate to machine
language (an assembler is software that
language (an assembler is software that
converts the program into machine code)
converts the program into machine code)
Opcode
Levels of
Levels of Programming Languages
Programming Languages
Levels of Computer Languages:
Levels of Computer Languages:

Low (a long way from English)
Low (a long way from English)
• machine language, assembly language
machine language, assembly language
• not portable
not portable

High (Closer to English)
High (Closer to English)
• COBOL, Pascal, FORTRAN, Logo, Basic
COBOL, Pascal, FORTRAN, Logo, Basic,
,
Visual Basic, Prolog,
Visual Basic, Prolog, C, C++ and Java
C, C++ and Java
High level languages
High level languages

Deliberately terse (concise).
Deliberately terse (concise).

Must be unambiguous.
Must be unambiguous.

Must be flexible enough to easily
Must be flexible enough to easily
implement algorithms.
implement algorithms.

Fairly portable
Fairly portable
Creating
Creating machine (
machine (executable
executable) code from
) code from C+
C+
+
+ source code :
source code : Compilation and linking
Compilation and linking
source code
source code
compiler
object code
object code linked to
libraries
.exe file
.exe file
Implementation Phase: Test
Implementation Phase: Test

TESTING your program means running
TESTING your program means running
(executing) your program on the computer,
(executing) your program on the computer,
to see if it produces correct results.
to see if it produces correct results.
(Verification)
(Verification)

if it does not, then you must find out what is
if it does not, then you must find out what is
wrong with your program or algorithm and
wrong with your program or algorithm and
fix it--this is called debugging
fix it--this is called debugging .
.

Compilers do not fix logic errors.
Compilers do not fix logic errors.
Maintenance Phase
Maintenance Phase

USE and MODIFY the program to meet
USE and MODIFY the program to meet
changing requirements or correct errors
changing requirements or correct errors
that show up when using it
that show up when using it

maintenance begins when your program
maintenance begins when your program
is put into use and accounts for the
is put into use and accounts for the
majority of effort on most programs
majority of effort on most programs

You will not be concerned very much with
You will not be concerned very much with
this phase while you learn.
this phase while you learn.

But when you are in industry this is a
But when you are in industry this is a
massive part of your job!
massive part of your job!
The Basic Control Structures
The Basic Control Structures
in programming
in programming
 a
a sequence
sequence is a series of
is a series of
statements that execute one after
statements that execute one after
another
another
 selection
selection (branch) is used to
(branch) is used to
execute different statements
execute different statements
depending on certain conditions
depending on certain conditions
(Boolean conditions)
(Boolean conditions)
 Iteration
Iteration (repetition) is used to
(repetition) is used to
repeat statements while certain
repeat statements while certain
conditions are met. Often requires
conditions are met. Often requires
the use of loops.
the use of loops.
Organising Structures
Organising Structures
(functions in C++)
(functions in C++)

Stepwise refinement
Stepwise refinement
• Breaking big problems into smaller bits
Breaking big problems into smaller bits

“
“Natural” problem solving strategy
Natural” problem solving strategy

Most common approach in programming
Most common approach in programming

Different people can work on different “bits”
Different people can work on different “bits”

Nearly all high level languages support this
Nearly all high level languages support this
Stepwise refinement
Stepwise refinement

the breaking down of problems into a
the breaking down of problems into a
series of single-function tasks and
series of single-function tasks and
single-function subtasks.
single-function subtasks.

We previously discussed functions.
We previously discussed functions.
SEQUENCES
SEQUENCES
Statement Statement Statement . . .
1. Get the user to input a number
2. Calculate the result e.g. number * 10
3. Display the result
Note the logical order!
SELECTION (branch)
SELECTION (branch)
IF Condition THEN Statement1 ELSE Statement2
Statement1
Statement
Statement2
Condition . . .
True
False
1. Get the user to input a number
2. IF the number is greater than 0 then
1. Calculate the result = number * 10
3. ELSE
1. Calculate the result = number * (-10)
4. Display the result
LOOP (repetition)
LOOP (repetition)
Statement1
Condition
. . .
False
True
WHILE Condition DO Statement1
So Statement1 is executed as long as the condition is
true.
Loop (repetition) Example
Loop (repetition) Example
1. Repeat While there are more numbers
to process
1. Get the user to input a number
2. IF the number is greater than 0 then
1. Calculate the result = number *
10
3. ELSE (otherwise)
1. Calculate the result = number (-
10)
4. Display the result
2. End repeat
function
function
FUNCTION1 . . .
FUNCTION1
a meaningful collection
of SEQUENCE,
SELECTION, LOOP
STATEMENTS &/OR
FUNCTIONS
Subprogram CalculateResult
Subprogram CalculateResult
Precondition: Needs a number to work with
Postcondition: returns a result depending on the
number
1. if the number is greater than 0 then
1. Calculate the result = number * 10
2. else
1. Calculate the result = number (-10)
3. return the result
Use of subprogram
Use of subprogram
1. Get the user to input a number
2. Repeat While there are more numbers to process
1. result =CalculateResult(number)
2. Display the result
3. Get the user to enter next number
3. End repeat
1. Get the user to input a number
2. Repeat While there are more numbers to process
1. IF the number is greater than 0 then
1. Calculate the result = number * 10
2. ELSE (otherwise)
1. Calculate the result = number * -10
3. Display the result
4. Get the user to enter next number
3. End repeat
#include <iostream>
using namespace std;
double CalculateResult(double number);
int main() {
float n;
float answer;
cout << "Please enter a number: "; //1) get the user to enter a number
cin >> n;
while (n != 0) { //2) loop use the value 0 to stop loop
answer = CalculateResult(n); //2.1) call function
cout << "The answer is " << answer << endl; //2.2) display answer
cout << "Please enter a number: "; //2.3) ask for next number
cin >> n;
} // 3) end loop
return 0;
}
double CalculateResult(double number) { // subprogram/function definition
float result;
if (number > 0)
result = number * 10.0;
else
result = number * -10.0;
return result;
}//see calculate1.cpp
Problem Solving Techniques
Problem Solving Techniques

OVERCOME MENTAL BLOCK -- by rewriting the
OVERCOME MENTAL BLOCK -- by rewriting the
problem in your own words
problem in your own words

DRAW A FIGURE/DIAGRAM
DRAW A FIGURE/DIAGRAM

ASK QUESTIONS –
ASK QUESTIONS –
• What is the data, What sort of data is it? what would
What is the data, What sort of data is it? what would
be good identifiers (names) for the data.
be good identifiers (names) for the data.
• How much data is there, where does it come from? Is
How much data is there, where does it come from? Is
it given? Do you get it from the user? do you calculate
it given? Do you get it from the user? do you calculate
it? do you get it from a file?
it? do you get it from a file?
• Can you identify what is input and what is to be
Can you identify what is input and what is to be
output?
output?
• What are
What are the processes
the processes?
?

Do you need to repeat steps
Do you need to repeat steps
• What are the conditions?
What are the conditions?

Do you need to do different things in different situations?
Do you need to do different things in different situations?
• What are the conditions
What are the conditions
Problem Solving Techniques
Problem Solving Techniques

LOOK FOR FAMILIAR THINGS -- certain
LOOK FOR FAMILIAR THINGS -- certain
situations arise
situations arise again and again. E.g. creating
again and again. E.g. creating
tables, adding up lists of numbers, reading from
tables, adding up lists of numbers, reading from
files.
files.

Do you know any equations?
Do you know any equations?
• Find the area of a room, find the stopping distance of a
Find the area of a room, find the stopping distance of a
car.
car.

SOLVE BY ANALOGY -- it may give you a place to
SOLVE BY ANALOGY -- it may give you a place to
start.
start. In a broader sense than looking for
In a broader sense than looking for
familiar things.
familiar things.
• E.g. Finding the student with the highest and lowest
E.g. Finding the student with the highest and lowest
score is analogous to finding the highest and lowest
score is analogous to finding the highest and lowest
temperature.
temperature.
Problem Solving
Problem Solving

USE MEANS-ENDS ANALYSIS
USE MEANS-ENDS ANALYSIS
• Where you often know start conditions and know
Where you often know start conditions and know
what the end goal is.
what the end goal is.
• Identify intermediate goals then think how you
Identify intermediate goals then think how you
get from start to the intermediary goals
get from start to the intermediary goals
• E.g. How do you find your way to the canteen/bar
E.g. How do you find your way to the canteen/bar
from here?
from here?

Setup intermediary goals: get to reception, past
Setup intermediary goals: get to reception, past
bookshop, security and lifts then canteen.
bookshop, security and lifts then canteen.

Get to stairs, get to reception, go down the stairs
Get to stairs, get to reception, go down the stairs
More Problem Solving Techniques
More Problem Solving Techniques
 Stepwise refinement -- break up large
Stepwise refinement -- break up large
problems into manageable units.
problems into manageable units.
 SIMPLIFY
SIMPLIFY
• Can you solve a simpler but related
Can you solve a simpler but related
problem?
problem?
• E.g. Bobs DIY:- Do not attempt to solve the general
E.g. Bobs DIY:- Do not attempt to solve the general
problem but solve the simpler cases
problem but solve the simpler cases
 BUILDING-BLOCK APPPROACH -- can you
BUILDING-BLOCK APPPROACH -- can you
solve small pieces of the problem? And then
solve small pieces of the problem? And then
join them up
join them up
• E.g. a large application like a word processor has
E.g. a large application like a word processor has
many functions. (Text manipulation, Tables,
many functions. (Text manipulation, Tables,
drawing)
drawing)
• Do not try to solve all at once.
Do not try to solve all at once.
Result of Problem solving
Result of Problem solving
1.
1. One or more pages of rough work that sketches
One or more pages of rough work that sketches
your ideas of problem requirements, of user
your ideas of problem requirements, of user
inputs, of outputs, of constants, of conditions
inputs, of outputs, of constants, of conditions
for repetition and selection, of assumptions.
for repetition and selection, of assumptions.
2.
2. A formal written design that includes:
A formal written design that includes:
1.
1. inputs, Processes, Outputs, assumptions.
inputs, Processes, Outputs, assumptions.
Create an IPO chart
Create an IPO chart
2.
2. Write steps to process input unambiguously
Write steps to process input unambiguously
using a semi formal notation (PDL, Flowchart
using a semi formal notation (PDL, Flowchart
or structure diagram?) Can you translate
or structure diagram?) Can you translate
each step of the plan into C++ easily?
each step of the plan into C++ easily?
3.
3. Verification/testing procedures documented
Verification/testing procedures documented
(A test table).
(A test table).
What we are aiming for is a
What we are aiming for is a Structured
Structured
Systematic
Systematic Approach to
Approach to Programming
Programming
Advantages:
Advantages:
 Not one giant step, but breaks in to smaller
Not one giant step, but breaks in to smaller
and smaller chunks.
and smaller chunks.
 Programmer concentrates on details
Programmer concentrates on details
 Easy to do in teams
Easy to do in teams
 Easy to keep track of development
Easy to keep track of development
 Creates more reliable and robust programs.
Creates more reliable and robust programs.
 Makes more possible reuse and extensibility.
Makes more possible reuse and extensibility.
Structured Programming
Structured Programming

Errors isolated
Errors isolated

Design written in code
Design written in code

Improves reliability
Improves reliability

Minimizes risk of Failure
Minimizes risk of Failure

Faster development
Faster development

Full documentation
Full documentation
• Maintainability
Maintainability

So find a solution, write it down in
So find a solution, write it down in
English.
English.

Write it down more formally in Pseudo-
Write it down more formally in Pseudo-
code (PDL), or as a structure diagram or
code (PDL), or as a structure diagram or
a flow chart.
a flow chart.

Start your programming environment and
Start your programming environment and
convert your pseudo-code to C++
convert your pseudo-code to C++

Tell the computer to convert the C++ to
Tell the computer to convert the C++ to
machine language (compile)
machine language (compile)

Tell the computer to load the machine
Tell the computer to load the machine
language into memory and execute
language into memory and execute
(Run).
(Run).
Summary
Summary
Note
Note

Learning C++ syntax by heart is
Learning C++ syntax by heart is
useless!
useless!

Experience essential
Experience essential

You will need to build up a virtual
You will need to build up a virtual
scrapbook of techniques to be
scrapbook of techniques to be
successfu
successful
l
“
“Get some information in,
Get some information in,
Do something with it,
Do something with it,
Display the result.”
Display the result.”
“
“Get some information in,
Get some information in,
Do something with it,
Do something with it,
Display the result.”
Display the result.”
Topics
Topics
 Structure of a simple C++ Program
Structure of a simple C++ Program
 TYPES of information
TYPES of information
• Simple and Complex
Simple and Complex
 Variables, Constants and Literals
Variables, Constants and Literals
 Identifiers: to Name memory
Identifiers: to Name memory
 Declarations
Declarations
 Getting information into your program
Getting information into your program
 Operator basics
Operator basics
Shortest C++ Program
Shortest C++ Program.
.
A Skeleton program
A Skeleton program
int main ( ) {
return 0;
}
//already run and discussed
type of returned value name of function
What happens?
What happens?

The operating system (Windows )
The operating system (Windows )

“
“Loads” the program
Loads” the program

Think of it as WINDOWS calling the “main” function.
Think of it as WINDOWS calling the “main” function.

Instructions “in main” are carried out one at a time.
Instructions “in main” are carried out one at a time.

Notice the “int” in front of “main” this line is like a
Notice the “int” in front of “main” this line is like a
contract to the operating system
contract to the operating system
• “
“I will send you a piece of information in the form of an
I will send you a piece of information in the form of an
integer.”
integer.”
• Hence the NEED for a return instruction. return 0 sends a
Hence the NEED for a return instruction. return 0 sends a
zero to windows XP
zero to windows XP
Discussion of structure
Discussion of structure

Your program must have a function called
Your program must have a function called
“main”
“main”

Note that Main, MAIN, mAiN will cause an
Note that Main, MAIN, mAiN will cause an
error
error

The round brackets ‘(‘ and ‘)’after main
The round brackets ‘(‘ and ‘)’after main
tells the computer that main is a
tells the computer that main is a function
function
rather than a variable
rather than a variable

The curly brackets (parentheses) ‘{‘ and
The curly brackets (parentheses) ‘{‘ and
‘}’ mark the beginning and end of
‘}’ mark the beginning and end of
instructions that form the
instructions that form the body
body of main.
of main.
• i.e. They are
i.e. They are blocks
blocks

The semi-colon ‘;’ after return 0 is an
The semi-colon ‘;’ after return 0 is an
instruction terminator or separator.
instruction terminator or separator.
#include <iostream>
using namespace std;
int main ( )
{
cout << “Hello World” << endl;
return 0;
}
//already run
The “Hello World” Program
The “Hello World” Program
uses complex information i.e. the display (cout)
uses complex information i.e. the display (cout)
needs more effort
needs more effort
Instructions to tell computer that
I want to use standard complex
OBJECTS for input and output
Discussion of Hello World Program
Discussion of Hello World Program
 There are now two instructions in main
There are now two instructions in main
• we added a display information instruction using a
we added a display information instruction using a
complex OBJECT cout
complex OBJECT cout
• cout represents the display screen. That is why it is
cout represents the display screen. That is why it is
complex. It hides all the complicated business of
complex. It hides all the complicated business of
displaying things from you. All you need to know is
displaying things from you. All you need to know is
how to send information to cout.
how to send information to cout.
• cout receives information using the “<<“ send to
cout receives information using the “<<“ send to
operator.
operator.
• So we literally send the string “Hello World” to the
So we literally send the string “Hello World” to the
display!
display!
• endl is also sent to the display, this is interpreted by
endl is also sent to the display, this is interpreted by
cout as a new-line command.
cout as a new-line command.
Discussion of Hello World
Discussion of Hello World
 So cout OBJECT represents our screen.
So cout OBJECT represents our screen.
 Screens are hardware.
Screens are hardware.
 Sending information to screens varies
Sending information to screens varies
greatly from machine to machine.
greatly from machine to machine.
 So cout became “standard”.
So cout became “standard”.
 Customised cout’s were created for all the
Customised cout’s were created for all the
major types of computer in the world.
major types of computer in the world.
 So that you can write one piece of code
So that you can write one piece of code
that should compile on all the main types
that should compile on all the main types
of computer in the world.
of computer in the world.
Discussion of Hello World
Discussion of Hello World

Because cout is NOT “BUILT IN” we need to tell
Because cout is NOT “BUILT IN” we need to tell
the computer that we want to make use of the
the computer that we want to make use of the
“standard” facilities for input and output
“standard” facilities for input and output

HENCE the lines
HENCE the lines
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
This is one of the original reasons for
C++’s popularity i.e., its relative ease
of porting from one type of computer to
another
Some Definitions
Some Definitions

Statements
Statements
• A statement is what programmers often call an
A statement is what programmers often call an
instruction.
instruction.
• Your code consists of many instructions
Your code consists of many instructions
• Your code consist of many statements
Your code consist of many statements
• Statements must end with a semi-colon
Statements must end with a semi-colon

blocks
blocks
• Any section of code which is surrounded by
Any section of code which is surrounded by
curly brackets is a
curly brackets is a block { }
block { }
Example
Example
A Block of
A Block of 4
4 statements
statements
{
{
cout <<"A fraction: "<<5.0/8.0 <<endl;
cout <<"A fraction: "<<5.0/8.0 <<endl;
cout <<"Big # : "<<
cout <<"Big # : "<<
7000.0*7000.0<<endl;
7000.0*7000.0<<endl;
cout <<8 + 5 <<" is the sum of 8 & 5n";
cout <<8 + 5 <<" is the sum of 8 & 5n";
cout << “Hello world”;
cout << “Hello world”;
}
}
Block denoted by
Curly braces
TYPES of information computers use
TYPES of information computers use

Simple (needs little or no effort to use)
Simple (needs little or no effort to use)
• To hold whole numbers (integers)
To hold whole numbers (integers)
• To hold numbers with fractions (float and
To hold numbers with fractions (float and
double)
double)
• To hold individual characters (char)
To hold individual characters (char)

Complex (needs a little more work to use)
Complex (needs a little more work to use)
• Strings
Strings
• Records
Records
• cin and cout
cin and cout
Simple Information
Simple Information

integer (whole numbers)
integer (whole numbers)
• For counting things
For counting things
• To represent values which only have
To represent values which only have
whole numbers
whole numbers

Pounds, Pence?
Pounds, Pence?

Grades, Scores (Chelsea 10 : United 0)
Grades, Scores (Chelsea 10 : United 0)

Categories
Categories
int
Simple Information
Simple Information

Floating points numbers
Floating points numbers
• For representing numbers that may
For representing numbers that may
contain fractions
contain fractions
• Averages, measurements.
Averages, measurements.
• pi, e, phi
pi, e, phi
float double
Simple information
Simple information

Single characters
Single characters

Can represents your initials
Can represents your initials

Can represent single key responses
Can represent single key responses
to questions
to questions
• ‘
‘y’ for yes and ‘n’ for no
y’ for yes and ‘n’ for no

Not much else
Not much else
What about Strings
What about Strings

In some languages this is a simple piece
In some languages this is a simple piece
of information
of information

In C++ it is not. A string is complex in
In C++ it is not. A string is complex in
that it is made up of lots of chars.
that it is made up of lots of chars.

In C++ we use the “standard” string
In C++ we use the “standard” string
facilities
facilities
#include <string>
string
Recap!
Recap!

Your programs will initially entail
Your programs will initially entail
• Getting information into the computer
Getting information into the computer

This information will either be whole numbers,
This information will either be whole numbers,
floating point numbers, single characters or
floating point numbers, single characters or
strings.
strings.

More complex information we will cover at a later
More complex information we will cover at a later
date.
date.
• Doing something (operate on) with the
Doing something (operate on) with the
information (int, float, double, char or string)
information (int, float, double, char or string)
• Displaying results
Displaying results
Constants, Variables and
Constants, Variables and
Literals
Literals
Remember at school
Remember at school
Area of a circle is
Area of a circle is π
πr
r2
2
Circumference of a circle is 2
Circumference of a circle is 2π
πr
r
π
π is a
is a constant
constant representing the number
representing the number
3.1415925
3.1415925…
…..
..
r is a
r is a variable
variable representing the radius of a
representing the radius of a
circle
circle
2 literally represents itself, it is a
2 literally represents itself, it is a literal
literal
Fundamental building blocks of programs
Key programming concept
Key programming concept

Programs use, variables, constants
Programs use, variables, constants
and literals to store information
and literals to store information
needed to solve problems
needed to solve problems

Remember the bank problem or
Remember the bank problem or
Bobs DIY (looked at) we used
Bobs DIY (looked at) we used
variables to hold values for wall
variables to hold values for wall
height and widths etc.
height and widths etc.
Fundamental task is
Fundamental task is
Getting information in to the computer
Getting information in to the computer

Key ideas
Key ideas
• We enter values of
We enter values of literals
literals directly into
directly into
code.
code.
• We enter values of
We enter values of constants
constants directly into
directly into
code
code
• We have a choice on how we enter values of
We have a choice on how we enter values of
variables
variables.
.

We can enter values directly
We can enter values directly

Values can be set interactively with a user.
Values can be set interactively with a user.

Values can be set interactively with a file on disk.
Values can be set interactively with a file on disk.
Using literals
Using literals

char, string, integer, float and
char, string, integer, float and
double values are referred to by
double values are referred to by
value not by a name.
value not by a name.

We type these directly into code
We type these directly into code
#include <iostream>
using namespace std;
int main() {
cout <<“The sum of one plus three is “ << 1 + 3 <<
endl;
return 0
}
string literal
2 integer
literals
Char literals
Char literals
#include <iostream>
using namespace std;
int main() {
cout <<“First letter of the alphabet is “ << ‘A’ << endl;
return 0;
}
//see char1.cpp
char literals
in SINGLE QUOTES
floating point literals
floating point literals

floating point number can contain
floating point number can contain
fractions.
fractions.

floating point literals are doubles
floating point literals are doubles
#include <iostream>
using namespace std;
int main() {
cout <<“one point one plus three point two is “ << 1.1 + 3.2 << endl;
return 0;
}//this is Float1.cpp
2 double
literals
Discussion
Discussion

You can enter information directly into code using
You can enter information directly into code using
literals
literals

This is obviously very limiting if a program wanted
This is obviously very limiting if a program wanted
to reuse a value we need to keep typing in its
to reuse a value we need to keep typing in its
value every time.
value every time.

Also if a program makes use of a value many
Also if a program makes use of a value many
times it is hard work to change all the CORRECT
times it is hard work to change all the CORRECT
references in a long program, especially if the
references in a long program, especially if the
number, say 10 refers to a count in one part of
number, say 10 refers to a count in one part of
the program and the number 10 means a grade in
the program and the number 10 means a grade in
another.
another.

How can we differentiate between them?
How can we differentiate between them?

It can also be very confusing for another person to
It can also be very confusing for another person to
understand what the numbers mean
understand what the numbers mean.
.
Solution
Solution
Variables and Constants
Variables and Constants
 These are NAMED areas of memory.
These are NAMED areas of memory.
 The programmer instructs the
The programmer instructs the
computer to reserve space for the
computer to reserve space for the
kind of information he/she wants and
kind of information he/she wants and
at the same time tell the computer
at the same time tell the computer
the name that will be used to refer to
the name that will be used to refer to
that bit of information.
that bit of information.
 This kind of instruction is called a
This kind of instruction is called a
DECLARATION
DECLARATION
DECLARATION
DECLARATION

We can declare
We can declare
• integers
integers
• floating point numbers (doubles)
floating point numbers (doubles)
• chars
chars
• strings
strings
Constants and Variable
Constants and Variable
Declarations
Declarations
 When a
When a variable
variable is declared the
is declared the
computer marks the bit of memory
computer marks the bit of memory
reserved so that it allows its contents
reserved so that it allows its contents
to change (vary) at any time. In
to change (vary) at any time. In
particular at run time
particular at run time
 When a
When a constant
constant is declared the
is declared the
computer effectively locks the
computer effectively locks the
memory reserved and prevents the
memory reserved and prevents the
contents being updated.
contents being updated.
Creating Constants and
Creating Constants and
Variables
Variables
#include <iostream>
using namespace std;
int main() {
const double Pi = 3.142;
double radius;
double Area, Circumference;
Area = Pi*radius*radius;
Circumference = 2*Pi*radius;
return 0;
}
//see constants.cpp //also calculates phi
Declarations are instructions to reserve memory
space big enough to store our information.
It also creates an identifier (a name) for us to
refer to this memory space
Rules for Creating Constants
Rules for Creating Constants
const type identifier = value;
<type>
choose one of
int
char
float
double
string
<identifier>
You create a
name. It must
obey the rules
for identifiers
(see rules in a
minute)
<value>
You provide the
constant value
e.g. for Pi value
was 3.141592
Examples
Examples
const int maxnumber = 10;
const double Pi = 3.142;
const char AGrade = ‘A’;
const string MyName = “Vas”;
Rules for Creating Variables
Rules for Creating Variables
type identifier;
or
Type identifier = value;
or
type identifier, identifier, …;
Examples
Examples
int number;
double Result;
char response;
string UserName;
int n1, n2, n3, n4;
Declare a double variable and set its initial value
double x = 5.6;
Rules for Creating Identifiers
Rules for Creating Identifiers

A
An identifier must start with a letter or underscore,
n identifier must start with a letter or underscore,
and be followed by zero or more letters
and be followed by zero or more letters
(A-Z, a-z), digits (0-9), or underscores
(A-Z, a-z), digits (0-9), or underscores

VALID
VALID
age_of_dog
age_of_dog taxRateY2K
taxRateY2K
PrintHeading
PrintHeading ageOfHorse
ageOfHorse

NOT VALID (Why?)
NOT VALID (Why?)
age# 2000TaxRate
age# 2000TaxRate Age-Of-Cat
Age-Of-Cat
Age of Cat
Age of Cat
Meaningful Identifiers
Meaningful Identifiers
Age-Of-Cat
Age-Of-Cat Age of Cat
Age of Cat
ILLEGAL!!
Use underscore to link words or
run words together and capitalise the start of each word
Age_Of_Cat
Age_Of_Cat AgeOfCat
AgeOfCat
LEGAL!!
More About Identifiers
More About Identifiers

C++ is case sensitive so
C++ is case sensitive so
NUMBER
NUMBER Number number
Number number
are all legitimate but DIFFERENT identifiers
are all legitimate but DIFFERENT identifiers
BE CONSISTENT in your code!
BE CONSISTENT in your code!

It is NOT good practice to have long identifiers
It is NOT good practice to have long identifiers

Why?
Why?
Long Identifier Names
Long Identifier Names

Some C++ compilers recognize only the
Some C++ compilers recognize only the first 32
first 32
characters
characters of an identifier as significant
of an identifier as significant

then these identifiers are considered the same:
then these identifiers are considered the same:
age_Of_This_Old_Rhinoceros_At_My_Zoo
age_Of_This_Old_Rhinoceros_At_My_Zoo
age_Of_This_Old_Rhinoceros_At_My_Safari
age_Of_This_Old_Rhinoceros_At_My_Safari

Also it is very annoying to keep typing in!
Also it is very annoying to keep typing in!
Meaningful Identifiers
Meaningful Identifiers

It is common sense to try to create
It is common sense to try to create
identifiers that are:
identifiers that are:

Meaningful:- they describe the
Meaningful:- they describe the
information they refer to
information they refer to
• E.g. Height, Count, BloodPressure,
E.g. Height, Count, BloodPressure,
CarSpeed
CarSpeed

Terse:- They are only as long as
Terse:- They are only as long as
necessary to convey meaning.
necessary to convey meaning.
Reserved Words
Reserved Words
• Identifiers CANNOT be a reserved word.
Identifiers CANNOT be a reserved word.
• Reserved words are built in words
Reserved words are built in words that have
that have
special meanings in the language.
special meanings in the language.
• They must be used only for their specified
They must be used only for their specified
purpose. Using them for any other purpose will
purpose. Using them for any other purpose will
result in a error.
result in a error.
• e.g. do
e.g. doif
if switch
switch
while
while else
else return
return
*
Reserved Words
Reserved Words

C++ is case sensitive. ALL reserved
C++ is case sensitive. ALL reserved
words are lower case
words are lower case
WHILE While while
Are all different identifiers only the last is
a reserved word
Operators
Operators
 All the data types we have seen (int, float,
All the data types we have seen (int, float,
double, char and string) have a set of
double, char and string) have a set of
operators that can be applied to them
operators that can be applied to them
 E.g. Numerical data uses the familiar + - /
E.g. Numerical data uses the familiar + - /
for add subtract and divide.
for add subtract and divide.
 The asterisk * is used for multiplication
The asterisk * is used for multiplication
 These work in the usual manner
These work in the usual manner
string operators
string operators
 arithmetic is not meaningful when applied to
arithmetic is not meaningful when applied to
strings
strings
 You do not multiply first names!
You do not multiply first names!
 strings operators do other things
strings operators do other things
 E.g. The + operator applied to strings joins
E.g. The + operator applied to strings joins
them (concatenates) together
them (concatenates) together
 We will see other operations we want to do with
We will see other operations we want to do with
strings; like searching a string for a substring
strings; like searching a string for a substring
or comparing strings.
or comparing strings.
Expressions
Expressions
A VALID arrangement of variables,
A VALID arrangement of variables,
constants, literals and operators
constants, literals and operators
Expressions are evaluated and
Expressions are evaluated and
compute a VALUE of a given type
compute a VALUE of a given type
E.g. Expression 9 + 4
E.g. Expression 9 + 4
computes to 13
computes to 13
A special OPERATOR
A special OPERATOR
The assignment operator
=
Causes much confusion!
IT DOES NOT WORK LIKE
EQUALS IN MATHS
variable = expression
variable = expression
number = 4;
number = 4;
result = 10 * number;
result = 10 * number;
number = number + 1;
number = number + 1;
expression simply consists of the literal int 4. number
“takes the value of” 4
Interpretation of =
“Takes the value of”
KEY POINT: expression is evaluated BEFORE it is applied
expression evaluates to 40. result
“takes the value of” 40
expression evaluates to 5 number
“takes the value of” 5
Using assignments to get
Using assignments to get
information into the computer
information into the computer
int myage;
int myage;
string myname;
string myname;
double mysalary;
double mysalary;
myage = 21;
myage = 21;
myname = “Vas”;
myname = “Vas”;
mysalary = 1000.00;
mysalary = 1000.00;
Interactive input formally covered
Interactive input formally covered
later
later

using cin and cout
using cin and cout

using data files
using data files
Programming in C++
Programming in C++
Lecture 2b
Lecture 2b
Types, Operators, Expressions
Types, Operators, Expressions
Overview
Overview
 Types
Types
• Binary arithmetic
Binary arithmetic
 Operators
Operators
• Arithmetic, logical, assignment
Arithmetic, logical, assignment
 Expressions/Statements
Expressions/Statements
• Declarations
Declarations
• Assignments
Assignments
• Other one-line operations
Other one-line operations
 More program examples
More program examples
Types
Types
 “
“Type” in C++ refers to the kind of data or
Type” in C++ refers to the kind of data or
information that is to be stored in the
information that is to be stored in the
variable
variable
 A variable is a quantity that can be
A variable is a quantity that can be
changed during a program
changed during a program
 Functions have return types, i.e. can return
Functions have return types, i.e. can return
expressions to the calling function
expressions to the calling function
 Arguments to functions each have their
Arguments to functions each have their
own type (these are passed to the function)
own type (these are passed to the function)
 Variables have types
Variables have types
Why Type?
Why Type?
 Why do we have to specify types of variables,
Why do we have to specify types of variables,
functions, arguments?
functions, arguments?
 Has to do with computer memory
Has to do with computer memory
 Different kinds of data require different amounts of
Different kinds of data require different amounts of
memory to store
memory to store
• A single character can have only one of 128 values
A single character can have only one of 128 values
(a-z,A-Z,0-9,punctuation, some others)
(a-z,A-Z,0-9,punctuation, some others)
• An integer (in the mathematical sense) can have an
An integer (in the mathematical sense) can have an
infinite number of values, on a computer however
infinite number of values, on a computer however
this is limited to ~65,000 values, depends on how
this is limited to ~65,000 values, depends on how
many bits are used
many bits are used
• Therefore, more memory is needed to store an
Therefore, more memory is needed to store an
integer than a character
integer than a character
Computer Memory
Computer Memory
 Memory in computers is made up of
Memory in computers is made up of
transistors
transistors
 Transistor: just a switch that can be either
Transistor: just a switch that can be either
on or off, easier to have just two electrical
on or off, easier to have just two electrical
states rather that 10 (i.e. to represent 0-9)
states rather that 10 (i.e. to represent 0-9)
 “
“on” state corresponds to the value 1, “off”
on” state corresponds to the value 1, “off”
state corresponds to the value 0
state corresponds to the value 0
 Everything in memory has to be made up of
Everything in memory has to be made up of
0s and 1s – i.e., has to be stored as a
0s and 1s – i.e., has to be stored as a
number in base 2 (binary)
number in base 2 (binary)
 Important to understand different bases
Important to understand different bases
Reminder:Converting Between
Reminder:Converting Between
Bases
Bases

To convert numbers in some other base
To convert numbers in some other base
into base 10 (decimal) values:
into base 10 (decimal) values:
• For each position, starting with position 0, the
For each position, starting with position 0, the
least significant digit (rightmost), take the digit
least significant digit (rightmost), take the digit
in that position and multiply it by the base
in that position and multiply it by the base
raised to the power of that position; add the
raised to the power of that position; add the
values together
values together
• 10 in base 2 = 1x2
10 in base 2 = 1x21
1
+ 0x2
+ 0x20
0
= 2+0 = 2
= 2+0 = 2
• 100101 in base 2 = 1x2
100101 in base 2 = 1x25
5
+ 1x2
+ 1x22
2
+ 1x2
+ 1x20
0
= 32 +
= 32 +
4 + 1 = 37
4 + 1 = 37
Converting Between Bases
Converting Between Bases

Hexadecimal (base 16) uses the digits 0-9 +
Hexadecimal (base 16) uses the digits 0-9 +
A-E (A=10, B=11,…E=15) and prefix 0x to
A-E (A=10, B=11,…E=15) and prefix 0x to
differentiate from decimal //a zero 0 not an o
differentiate from decimal //a zero 0 not an o

To convert binary to hexadecimal, group
To convert binary to hexadecimal, group
binary digits in groups of 4, convert each
binary digits in groups of 4, convert each
group of 4 into decimal, and use the
group of 4 into decimal, and use the
appropriate hex digit for that group of 4
appropriate hex digit for that group of 4

100101 in base 2 = 0010 0101
100101 in base 2 = 0010 0101
first hex digit = 0010 or 2
first hex digit = 0010 or 2
second hex digit = 0101 or 5
second hex digit = 0101 or 5
0x25 = 2x16
0x25 = 2x161
1
+ 5x16
+ 5x160
0
= 32 + 5 = 37
= 32 + 5 = 37

See
See OctalandHex.cpp
OctalandHex.cpp
Converting Between Bases
Converting Between Bases

Octal (base 8) numbers prefixed with 0
Octal (base 8) numbers prefixed with 0
(zero)
(zero)

052 in base 8 = 5x8
052 in base 8 = 5x81
1
+ 2x8
+ 2x80
0
= 40+ 2 = 42
= 40+ 2 = 42

Octal conversion to binary: same as hex, but
Octal conversion to binary: same as hex, but
group digits into groups of 3
group digits into groups of 3

100101 in base 2 = 100 101
100101 in base 2 = 100 101
first octal digit = 100 or 4
first octal digit = 100 or 4
second octal digit = 101 or 5
second octal digit = 101 or 5
045 = 4x8
045 = 4x81
1
+ 5x8
+ 5x80
0
= 32 + 5 = 37
= 32 + 5 = 37

See OctalandHex.cpp
See OctalandHex.cpp
Common Bases
Common Bases

Binary, octal (base 8), hexadecimal
Binary, octal (base 8), hexadecimal
(base 16) all common bases in
(base 16) all common bases in
programming
programming

Useful because powers of 2 and easy
Useful because powers of 2 and easy
to convert between
to convert between

Computer memory almost always in
Computer memory almost always in
powers of 2
powers of 2
Back to Types
Back to Types
 Types typically defined in pieces of memory that are
Types typically defined in pieces of memory that are
powers of 2
powers of 2
 Smallest piece of memory: 1 bit (Binary DigIT)
Smallest piece of memory: 1 bit (Binary DigIT)
• Can hold 0 or 1 (equivalent to 1 transistor)
Can hold 0 or 1 (equivalent to 1 transistor)
 8 bits = 1 byte, 4 bits is a nibble
8 bits = 1 byte, 4 bits is a nibble
• 1 byte can have any value between 0000 0000 and
1 byte can have any value between 0000 0000 and
1111 1111 – i.e., between 0 – 255.
1111 1111 – i.e., between 0 – 255.
• 1111 1111 binary
1111 1111 binary
hex digit: 1111 = 8+4+2+1 = 15 = E
hex digit: 1111 = 8+4+2+1 = 15 = E
0xEE = 15x16
0xEE = 15x161
1
+ 15x16
+ 15x160
0
= 240 + 15 = 255
= 240 + 15 = 255
• More than number of values needed for characters –
More than number of values needed for characters –
1 byte typically used for character type
1 byte typically used for character type
Numeric Types
Numeric Types
 16 bits = 2 bytes can have any value from
16 bits = 2 bytes can have any value from
0000 0000 0000 0000– 1111 1111 1111 1111
0000 0000 0000 0000– 1111 1111 1111 1111
or 0 – 65,535. (Shortcut: 65,535 = 2
or 0 – 65,535. (Shortcut: 65,535 = 216
16
-1)
-1)
• Was used for a long time for integer values
Was used for a long time for integer values
• If used to store negative integers, could only store
If used to store negative integers, could only store
up to +/- 32,768 (approx) why?
up to +/- 32,768 (approx) why?
 32-bit integers now more common
32-bit integers now more common
• Ever heard of 32-bit operating system? Means that
Ever heard of 32-bit operating system? Means that
main data types used are 32-bit
main data types used are 32-bit
 Amount of memory given to each type
Amount of memory given to each type
dependent on the machine and operating
dependent on the machine and operating
system
system
Type Sizes
Type Sizes

Many different types in C++ (more to
Many different types in C++ (more to
come)
come)
• char: a single character
char: a single character

Often 1 byte, 128 values
Often 1 byte, 128 values
• int: an integer value
int: an integer value

Often 32 bits/4 bytes, 4 billion values
Often 32 bits/4 bytes, 4 billion values
• float: a floating-point number
float: a floating-point number

Often 4 bytes
Often 4 bytes
• double: a double-precision floating-point
double: a double-precision floating-point
number
number

Double the size of a float, often 64 bits or 8 bytes
Double the size of a float, often 64 bits or 8 bytes
Operators
Operators

Arithmetic: + - * / % -(unary e.g. -
Arithmetic: + - * / % -(unary e.g. -
(x+y))
(x+y))

Increment/decrement: ++ --
Increment/decrement: ++ --

Relational: > >= < <=
Relational: > >= < <=

Equality: == !=
Equality: == !=

Assignment: = += -= *=
Assignment: = += -= *=

Logical: || &&
Logical: || &&

Reference/Dereference: & * -- for later
Reference/Dereference: & * -- for later
Expressions
Expressions
 Built up out of constant values (e.g.,
Built up out of constant values (e.g.,
5 or 10.7), variables (x, y, etc) and
5 or 10.7), variables (x, y, etc) and
operators
operators
 Number and type of variables has to
Number and type of variables has to
match what the operator expects –
match what the operator expects –
like a function
like a function
 Some exceptions when working with
Some exceptions when working with
numerical variables!
numerical variables!
Type conversions (coercion)
Type conversions (coercion)
 Some types can automatically be
Some types can automatically be
converted to others
converted to others
 int, float, double can often be treated the
int, float, double can often be treated the
same for calculation purposes
same for calculation purposes
• int values will be converted up into floats for
int values will be converted up into floats for
calculations.
calculations.
 But major differences between integer and
But major differences between integer and
floating-point arithmetic!
floating-point arithmetic!
• Fractions just dropped in integer arithmetic
Fractions just dropped in integer arithmetic
• Use modulus (%) operator to get remainders
Use modulus (%) operator to get remainders
• Integer much faster to perform
Integer much faster to perform
Expression Examples
Expression Examples

See/code examplesin.cpp
See/code examplesin.cpp

Many examples follow
Many examples follow

x, y, z are integer variables
x, y, z are integer variables

f and d are float variables
f and d are float variables
Arithmetic
Arithmetic
y = 5;
y = 5; // y is now 5
// y is now 5
x = y + 3; // x is now 8
x = y + 3; // x is now 8
f = 2 * 4; // f is now 8.0
f = 2 * 4; // f is now 8.0
g = f / 3.0; // g is now 2.6…67
g = f / 3.0; // g is now 2.6…67
y = x / 3; // y is now 2
y = x / 3; // y is now 2
z = x % 3; // z is now 2
z = x % 3; // z is now 2
See ExamplesinCpp.cpp
See ExamplesinCpp.cpp
Increment/Decrement
Increment/Decrement
x = 5;
x = 5;
f = 2.5;
f = 2.5;
x++;
x++; // x is now 6
// x is now 6
f--;
f--; // f is now 1.5
// f is now 1.5
++f;
++f; // f is now 2.5
// f is now 2.5
--x;
--x; // x is now 5
// x is now 5
y = ++x – 2; // x = 6, y = 2
y = ++x – 2; // x = 6, y = 2
g = f-- + 2; // f = 1.5, g = 4.5!
g = f-- + 2; // f = 1.5, g = 4.5!
//see
//see ExamplesinCpp2.cpp
ExamplesinCpp2.cpp
Relational
Relational
x = 5;
x = 5;
f = 6.0;
f = 6.0;
y = (x > f); // y = 0 (false)
y = (x > f); // y = 0 (false)
g = (x <= f); // g = 1 (true)
g = (x <= f); // g = 1 (true)
// usually used in conditionals
// usually used in conditionals
if (x > f) {
if (x > f) {
// do something
// do something
}
}
See conditional1.cpp
See conditional1.cpp
Relational conditions:Common
Relational conditions:Common
errors
errors
if (x = 5);
if (x = 5);
if ((x=5)&&(y=7))
if ((x=5)&&(y=7))
if ((x>0)&&(x<=))
if ((x>0)&&(x<=))
Must use if (x==4)
Must use if (x==4)
Or if (y!=10)
Or if (y!=10)
Equality & Assignment
Equality & Assignment
x = 5; // sets value of x to 5
x = 5; // sets value of x to 5
if (x == 5) // returns true/false
if (x == 5) // returns true/false
x += 3;
x += 3; // x is now 8
// x is now 8
if (x != 5) {
if (x != 5) {
cout << “x is not 5n”;
cout << “x is not 5n”;
}
}
x *= 2; // x is now 16
x *= 2; // x is now 16
See conditional2.cpp
See conditional2.cpp
Logical
Logical
x = 5;
x = 5;
y = 2;
y = 2;
if ( (x >= 5) && (y < 2) ) {
if ( (x >= 5) && (y < 2) ) {
cout << “Both true.n”;
cout << “Both true.n”;
} else if ( (x >= 5) || (y < 2) ) {
} else if ( (x >= 5) || (y < 2) ) {
cout << “One is true.n”;
cout << “One is true.n”;
} else {
} else {
cout << “Both false!n”;
cout << “Both false!n”;
}
}
Programming in C++
Programming in C++
Lecture 2c
Lecture 2c
Elements of a Program
Elements of a Program
Overview of Lecture
Overview of Lecture
 Overview of Computers & Programming
Overview of Computers & Programming
• Assembly language vs. C/C++
Assembly language vs. C/C++
• Compiled vs. interpreted languages
Compiled vs. interpreted languages
• Procedural programming vs. Object-oriented
Procedural programming vs. Object-oriented
programming
programming
 Elements of a Program
Elements of a Program
• Statements
Statements
• Functions
Functions
• Variables
Variables
 Types
Types
• Computer memory & binary arithmetic
Computer memory & binary arithmetic
• C++ types
C++ types
What Is A Computer?
What Is A Computer?

CPU/processor just does a few basic
CPU/processor just does a few basic
things:
things:
• Arithmetic unit (adds, subtracts, multiplies,
Arithmetic unit (adds, subtracts, multiplies,
divides), sometimes called the ALU the
divides), sometimes called the ALU the
Arithmetic
Arithmetic and
and Logic Unit
Logic Unit
• Memory control (loads and stores integer and
Memory control (loads and stores integer and
floating-point values from memory)
floating-point values from memory)
• Think of address and data buses etc
Think of address and data buses etc

Everything a computer does is
Everything a computer does is
accomplished with these simple operations
accomplished with these simple operations
Assembly Language
Assembly Language
 Computer processors each have their own
Computer processors each have their own
built-in assembly language, this is code that
built-in assembly language, this is code that
the CPU understands
the CPU understands
• E.g., Intel CPUs have their own language that differs
E.g., Intel CPUs have their own language that differs
from the language of Motorola Power PC CPUs
from the language of Motorola Power PC CPUs
 These have a limited range of commands,
These have a limited range of commands,
LOAD, ADD, SUB, MOV etc
LOAD, ADD, SUB, MOV etc
 Each command typically does very little
Each command typically does very little
• Arithmetic commands, load/store from memory
Arithmetic commands, load/store from memory
 Code not totally unreadable, but close,
Code not totally unreadable, but close,
fortunately we do not generally write in
fortunately we do not generally write in
assembly language any more, but it is good to
assembly language any more, but it is good to
know about it.
know about it.
C++ versus Assembly
C++ versus Assembly
 Here is some simple C++ code:
Here is some simple C++ code:
 assume x, y and z have been defined
assume x, y and z have been defined
as integers
as integers
 || means the logical or operator
|| means the logical or operator
x = y + 2;
x = y + 2;
if ( (x > 0) || ( (y-x) <= z) )
if ( (x > 0) || ( (y-x) <= z) )
x = y + z;
x = y + z;
 We will also see three similar lines of code in
We will also see three similar lines of code in
Intel x86 assembly language in a moment...
Intel x86 assembly language in a moment...
Truth table for Logical or
Truth table for Logical or
A
A B
B A || B
A || B
False
False False
False False
False
True
True False
False True
True
False
False True
True True
True
True
True True
True True
True
Truth table for Logical or
Truth table for Logical or
continued
continued
The
The
predicate A
predicate A
is: It is
is: It is
Tuesday
Tuesday
The
The
predicate B
predicate B
is: It is
is: It is
raining
raining
A || B
A || B
False
False False
False False
False
True
True False
False True
True
False
False True
True True
True
True
True True
True True
True
Truth table for And (&&)
Truth table for And (&&)
A
A B
B A && B
A && B
False
False False
False False
False
True
True False
False False
False
False
False True
True False
False
True
True True
True true
true
MOV AX, y // put y into AX
MOV BX, x // put x into BX
MOV CX, z // put z into CX
ADD AX, x // add to the contents of AX the
value
// x and store in AX
CMP AX, 0 // check whether the contents of
AX=0
MOV DX, BX //move contents of BX into DX
SUB DX, AX //subtract the value of contents of
//AX and place in DX
CMP DX, CX //compare contents of CX and DX
With more code here
.
.
.
Note it is difficult to understand and quite tedious
The C++ Programming Language
The C++ Programming Language

C++ is a higher-level language
C++ is a higher-level language
compared to assembly
compared to assembly
• Much more human-readable
Much more human-readable
• Fewer lines of code for same task
Fewer lines of code for same task

C is a lower-level language compared to
C is a lower-level language compared to
others (like C++ and Java which are
others (like C++ and Java which are
Object Oriented Programming
Object Oriented Programming
languages)
languages)
• Direct control over memory allocation and
Direct control over memory allocation and
cleanup (as we will see)
cleanup (as we will see)
Compiled vs. Interpreted
Compiled vs. Interpreted

For a program to run, the source code
For a program to run, the source code
must be translated into the assembly
must be translated into the assembly
language of the machine the program will
language of the machine the program will
run on.
run on.
• Compiled language: the source code is
Compiled language: the source code is
translated once and the executable form is run.
translated once and the executable form is run.
(C++ and Pascal)
(C++ and Pascal)
• Interpreted language: an interpreter runs each
Interpreted language: an interpreter runs each
time the program is started, and it does the
time the program is started, and it does the
translation on-the-fly (Visual Basic, Perl, other
translation on-the-fly (Visual Basic, Perl, other
scripting languages and Java).
scripting languages and Java).
• Java is compiled and interpreted requires a JVM
Java is compiled and interpreted requires a JVM

JVM: Java Virtual Machine
JVM: Java Virtual Machine
Procedural vs. Object-Oriented
Procedural vs. Object-Oriented

Procedural Programming
Procedural Programming
• A program viewed as a series of instructions to
A program viewed as a series of instructions to
the computer
the computer
• Instructions are organized into functions and
Instructions are organized into functions and
libraries of functions
libraries of functions

Object-Oriented Programming
Object-Oriented Programming
• A program viewed as a set of objects that
A program viewed as a set of objects that
interact with each other
interact with each other
• An object encapsulates (hides and binds)
An object encapsulates (hides and binds)
functions with the data that the object’s
functions with the data that the object’s
functions operate on
functions operate on
Procedural vs. Object-Oriented
Procedural vs. Object-Oriented
 OOP good for complex systems – nice to
OOP good for complex systems – nice to
break down into small independent objects
break down into small independent objects
 Procedural perhaps a bit more intuitive,
Procedural perhaps a bit more intuitive,
especially for beginners (where we will
especially for beginners (where we will
commence)
commence)
 C is a procedural language, no OO
C is a procedural language, no OO
capabilities
capabilities
 Java and C++ are Object-Oriented
Java and C++ are Object-Oriented
Languages, Java is pure Object Oriented
Languages, Java is pure Object Oriented
i.e. everything is an object in Java.
i.e. everything is an object in Java.
Explanation of OOP and
Explanation of OOP and
Procedural Programming
Procedural Programming

Perhaps one of the best definitions of the
Perhaps one of the best definitions of the
difference between these two paradigms is
difference between these two paradigms is
as follows:
as follows:

Consider a chair: a
Consider a chair: a procedural
procedural
programmer
programmer is interested in in the wood,
is interested in in the wood,
hammer, screws, screw driver etc i.e.,
hammer, screws, screw driver etc i.e.,
everything that went into making the
everything that went into making the
chair, however the
chair, however the Object Oriented
Object Oriented
Programmer
Programmer would be interested only in
would be interested only in
the chair i.e. the finished article
the chair i.e. the finished article
Procedural Programming
Procedural Programming
 Program is a set of
Program is a set of sequential
sequential steps to be
steps to be
executed by the computer, one after
executed by the computer, one after
another, this is the
another, this is the Sequential Paradigm
Sequential Paradigm
 However we do
However we do Not
Not necessarily run the
necessarily run the
same steps every time the program runs,
same steps every time the program runs,
can have
can have selection
selection/decisions
/decisions
• May want to skip steps under certain conditions
May want to skip steps under certain conditions
(selection)
(selection)
• May want to repeat steps under certain
May want to repeat steps under certain
conditions (
conditions (iteration
iteration)
)
• May need to save some information to use later
May need to save some information to use later
in the program (when computing a sum)
in the program (when computing a sum)
Programming Paradigms
Programming Paradigms
 There are three essential programming
There are three essential programming
paradigms (the word paradigm is from the Greek
paradigms (the word paradigm is from the Greek
word meaning example)
word meaning example)
 Sequential:
Sequential: code is executed one after the after
code is executed one after the after
top-down:
top-down:Sequential Paradigm
Sequential Paradigm
 Selection
Selection/decisions. Achieved in C/C++ using
/decisions. Achieved in C/C++ using
the
the if, if-else
if, if-else or
or switch-case
switch-case statements to be met
statements to be met
in later lectures.
in later lectures.
 Iteration
Iteration:To be achieved in the C++/Java
:To be achieved in the C++/Java
languages using the
languages using the for
for loop
loop, while
, while loop
loop or
or the
the
do-while
do-while loop, more in later lectures
loop, more in later lectures
Elements of a Program
Elements of a Program
 Individual steps/commands to the computer
Individual steps/commands to the computer
• These are called Statements, a semicolon delimits a
These are called Statements, a semicolon delimits a
valid C++ statement.
valid C++ statement.
 Technique to organize code so it is easy to debug, fix, and
Technique to organize code so it is easy to debug, fix, and
maintain.
maintain. Code and fix
Code and fix is the most common way that one
is the most common way that one
programs, but perhaps the worst, SSADM is a better way.
programs, but perhaps the worst, SSADM is a better way.
SSADM: Structured, System Analysis and Design
SSADM: Structured, System Analysis and Design
Methodology
Methodology
• Functions
Functions
 Way to save information that may change each time the
Way to save information that may change each time the
program runs
program runs
• Variables vary in a program
Variables vary in a program
 If we want to change what steps get executed:
If we want to change what steps get executed:
• Control flow – topic coming soon
Control flow – topic coming soon
Code and Fix
Code and Fix

Write some code
Write some code

Fix problems just created
Fix problems just created
• Problems
Problems
• Software complete after n fixes
Software complete after n fixes
• Subsequent fixes are very expensive (time and
Subsequent fixes are very expensive (time and
resources)
resources)
• Previous fixes fail to work
Previous fixes fail to work
• Poor fit to users’ needs (reflects programmers
Poor fit to users’ needs (reflects programmers
view rather that that of the clients)
view rather that that of the clients)
Design
Installation
Operation and
Maintenance
Analysis and
Specification
Implementation
Testing
Developing software: The traditional approach
The Waterfall Model
The Waterfall Model
 Criticisms
Criticisms
• Requirements must be fixed before system is designed
Requirements must be fixed before system is designed
• Design and code produce inconsistencies that are
Design and code produce inconsistencies that are
difficult to fix
difficult to fix
• Problems are not discovered until the Testing stage
Problems are not discovered until the Testing stage
• System performance can not be tested until near
System performance can not be tested until near
completion
completion
• System underperformance is difficult to fix at this stage
System underperformance is difficult to fix at this stage
 Problems
Problems
• Ageing technique
Ageing technique
• Less effective for new software paradigms of OOD (UML)
Less effective for new software paradigms of OOD (UML)
• Costs can spiral out of control
Costs can spiral out of control
• Projects can and usually do overrun (inefficient)
Projects can and usually do overrun (inefficient)
Initial
Planning
Final
Product
Analysis
Testing and
Quality
Assurance
Reviewing
Prototypes
Building
Prototypes
Developing software: the modern approach (RAD)
Functions
Functions
 Already have seen the main()
Already have seen the main()
function
function
 Functions are used to group
Functions are used to group
individual statements that together
individual statements that together
accomplish a single larger task
accomplish a single larger task
 E.g., the main() function contains
E.g., the main() function contains
many statements that together
many statements that together
accomplish the task of printing a
accomplish the task of printing a
message to the screen or file
message to the screen or file
Simple Example
Simple Example
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
void printHello() {cout<< “Hellon”};
void printHello() {cout<< “Hellon”};
void printBye() {cout<<“Byen”};
void printBye() {cout<<“Byen”};
int main()
int main()
{
{
printHello(); // this is a call to the
printHello(); // this is a call to the
// function printHello()
// function printHello()
printBye(); // this is a call to the
printBye(); // this is a call to the
// function prinBye
// function prinBye
return 0;
return 0;
}
}
See program fuctions1.cpp
See program fuctions1.cpp
See program fuctions1b.cpp (//does not compile)
See program fuctions1b.cpp (//does not compile)
as //there are no function prototypes
as //there are no function prototypes
Function Elements
Function Elements
 Return-type
Return-type
• Specifies what kind of information the function will return
Specifies what kind of information the function will return
• void
void means nothing is returned (called a procedure in other
means nothing is returned (called a procedure in other
languages)
languages)
 Name
Name
• Must be unique within the program
Must be unique within the program
• It is used to call (invoke) the function – i.e., to cause the functio
It is used to call (invoke) the function – i.e., to cause the function
statements to be executed
statements to be executed
 Arguments
Arguments
• Optional information that is used by the function
Optional information that is used by the function
 Body
Body
• The actual statements within the function groups
The actual statements within the function groups
Variables
Variables

Used to store information within the
Used to store information within the
program
program

Values can change as the program
Values can change as the program
runs (i.e., are variable)
runs (i.e., are variable)
• Obtained through calculations
Obtained through calculations
• From input
From input
• From function results
From function results
Simple Examples
Simple Examples
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
int main()
int main()
{
{
int x = 5;//obsolete here as not used
int x = 5;//obsolete here as not used
char letter = ‘g’;
char letter = ‘g’;
cout <<“Please enter a character”;
cout <<“Please enter a character”;
cin >> letter;
cin >> letter;
cout << “the character input was “ << letter << endl;
cout << “the character input was “ << letter << endl;
return 0;
return 0;
}
}
//see letter.cpp
//see letter.cpp
Variable Elements
Variable Elements
 Type
Type
• Indicates what kind of information can be
Indicates what kind of information can be
stored in the variable
stored in the variable
 Name
Name
• Must be unique within a given function
Must be unique within a given function
 Except for special
Except for special global variables
global variables, which must
, which must
have unique names within the program. Global
have unique names within the program. Global
variables are not considered good programming
variables are not considered good programming
practice. Why?
practice. Why?
• Used to refer to a variable throughout the
Used to refer to a variable throughout the
function
function
 Value
Value
• Can be set in many different ways
Can be set in many different ways
Declarations vs. Definitions
Declarations vs. Definitions
 Both functions and variables MUST be
Both functions and variables MUST be
declared before they can be used
declared before they can be used
 Declaration includes just:
Declaration includes just:
 Type
Type
 Name
Name
 Arguments (for functions)
Arguments (for functions)
 Definition can come later!
Definition can come later!
• For variables: value can be assigned later (as
For variables: value can be assigned later (as
long as it is before its first use or garbage will
long as it is before its first use or garbage will
be used)
be used)
• For functions: body of function can be added
For functions: body of function can be added
later
later
Complex Example
Complex Example

See the functions1.cpp, function2.cpp and
See the functions1.cpp, function2.cpp and
function3.cpp example code
function3.cpp example code

Variable declaration:
Variable declaration:
• int x; char input[1000];
int x; char input[1000];

Function declaration (prototype):
Function declaration (prototype):
• void printHello();
void printHello();

Function definition
Function definition
• void printHello()
void printHello()
{
{
cout << “Hello”<< endl;
cout << “Hello”<< endl;
}
}
Important Rules
Important Rules

All variables and functions must be
All variables and functions must be
declared in the function/file where
declared in the function/file where
they are going to be used BEFORE
they are going to be used BEFORE
they are used.
they are used.

All variables must be initialized to
All variables must be initialized to
some starting value before being
some starting value before being
used in calculations or being printed
used in calculations or being printed
out, otherwise we get rubbish
out, otherwise we get rubbish
Statements
Statements

A statement is a single line of code
A statement is a single line of code

Can be:
Can be:
• Variable or function declarations
Variable or function declarations
• Arithmetic operations
Arithmetic operations

x = 5+3;
x = 5+3;
• Function calls
Function calls

Calcsum(x,y);
Calcsum(x,y);
• Control flow commands
Control flow commands
• More to be seen…
More to be seen…
Types
Types

“
“Type” in C++ refers to the kind of
Type” in C++ refers to the kind of
data or information
data or information

Functions have return types
Functions have return types

Arguments to functions each have
Arguments to functions each have
their own type
their own type

Variables have types
Variables have types
Why Type?
Why Type?
 Why do we have to specify types of
Why do we have to specify types of
variables, functions, arguments?
variables, functions, arguments?
 Has to do with computer memory
Has to do with computer memory
 Different kinds of data require different
Different kinds of data require different
amounts of memory to store
amounts of memory to store
• A single character can have only one of 128
A single character can have only one of 128
values (a-z,A-Z,0-9,punctuation, some others)
values (a-z,A-Z,0-9,punctuation, some others)
• An integer in mathematics can have an infinite
An integer in mathematics can have an infinite
number of values, limited to ~65,000 values on
number of values, limited to ~65,000 values on
a computer
a computer
• Therefore, more memory needed to store an
Therefore, more memory needed to store an
integer than a character
integer than a character
Computer Memory
Computer Memory
 Memory in computers made up of
Memory in computers made up of
transistors
transistors
 Transistor: just a switch that can be either
Transistor: just a switch that can be either
on or off
on or off
 “
“on” state corresponds to the value 1,
on” state corresponds to the value 1,
“off” state corresponds to the value 0
“off” state corresponds to the value 0
 Everything in memory has to be made up
Everything in memory has to be made up
of 0s and 1s – i.e., has to be stored as a
of 0s and 1s – i.e., has to be stored as a
number in base 2 (binary)
number in base 2 (binary)
 Important to understand different bases
Important to understand different bases
Numeric Types
Numeric Types
 16 bits = 2 bytes can have any value from
16 bits = 2 bytes can have any value from
0000 0000 0000 0000–1111 1111 1111 1111
0000 0000 0000 0000–1111 1111 1111 1111
or 0 – 65,535. (Shortcut: 65,535 = 2
or 0 – 65,535. (Shortcut: 65,535 = 216
16
-1)
-1)
• Was used for a long time for integer values
Was used for a long time for integer values
• If used to store negative integers, could only store
If used to store negative integers, could only store
up to +/- 32,768 (approx)
up to +/- 32,768 (approx)
 32-bit integers now more common
32-bit integers now more common
• Ever heard of 32-bit operating system? Means that
Ever heard of 32-bit operating system? Means that
main data types used are 32-bit
main data types used are 32-bit
 Amount of memory given to each type
Amount of memory given to each type
dependent on the machine and operating
dependent on the machine and operating
system
system
Next Time
Next Time
 More on types
More on types
 Operators
Operators
• Arithmetic: + - * /
Arithmetic: + - * /
• Assignment: =
Assignment: =
• Increment/Decrement: ++ --
Increment/Decrement: ++ --
 Expressions/Statements
Expressions/Statements
• Declarations
Declarations
• Assignments
Assignments
• Other one-line operations
Other one-line operations
 More program examples
More program examples
Casting
Casting

int i = 16;
int i = 16;

double d;
double d;

d = i; // will give, d = 16.0
d = i; // will give, d = 16.0

d = 10.3;
d = 10.3;

i = d; // will give i = 10
i = d; // will give i = 10

cout << 2 * 3.4 + 7 / 2; // 6.8 + 3 =
cout << 2 * 3.4 + 7 / 2; // 6.8 + 3 =
9.8 (a //double), note 7/2 is evaluated as
9.8 (a //double), note 7/2 is evaluated as
an integer
an integer

//ignoring the remainder.
//ignoring the remainder.

//see casting.cpp
//see casting.cpp
Conditional Statements
Conditional Statements

Conditions take the form:
Conditions take the form:

if (condition)
if (condition)

{statements executed if the
{statements executed if the
condition is true }
condition is true }

else
else

{statements executed if the
{statements executed if the
condition is false }
condition is false }
Conditions
Conditions

Execution resumes here with the “if
Execution resumes here with the “if
statement” having been executed.
statement” having been executed.

Note that the first line does not end with a
Note that the first line does not end with a
semicolon.
semicolon.

The curly brackets are necessary only if
The curly brackets are necessary only if
there are several statements.
there are several statements.

If you are only executing one statement
If you are only executing one statement
as a result of the condition, you can place
as a result of the condition, you can place
it on the same line or the next.
it on the same line or the next.

For example:
For example:
Conditions
Conditions

See tennis.cpp
See tennis.cpp
Relational operators.
Relational operators.

Relational operators allow you to compare
Relational operators allow you to compare
two or more items of data in an
two or more items of data in an
expression.
expression.

= = is equal to (comparison operator)
= = is equal to (comparison operator)

!= is not equal to
!= is not equal to

> is greater than
> is greater than

< is less than
< is less than

>= is greater than or equal to
>= is greater than or equal to

<= is less than or equal to
<= is less than or equal to
Relations
Relations

The mathematical operators < and >
The mathematical operators < and >
can be used with strings to
can be used with strings to
determine alphabetical order.
determine alphabetical order.
For example:
For example:

("abc" < "def")
("abc" < "def")

this is also true
this is also true

("d">"b")
("d">"b")
Relations
Relations

When dealing with non-alphanumeric characters
When dealing with non-alphanumeric characters
(i.e. numbers and letters), you need to know
(i.e. numbers and letters), you need to know
which character set, or code page, you are using
which character set, or code page, you are using
before you can determine the alphabetical order
before you can determine the alphabetical order
of a set of strings.
of a set of strings.

The most common code page is the
The most common code page is the ASCII
ASCII
(American Standard Code for Information
(American Standard Code for Information
Exchange). The EBDIC (Extended Binary Decimal
Exchange). The EBDIC (Extended Binary Decimal
Interchange Code) is used in large IBM
Interchange Code) is used in large IBM
mainframes.
mainframes.

The first 33 characters of the ASCII character set
The first 33 characters of the ASCII character set
are non-printable control codes (CTRL, carriage
are non-printable control codes (CTRL, carriage
return etc).
return etc).
Common pitfall with Boolean
Common pitfall with Boolean
expressions.
expressions.
It is easy to write:
It is easy to write:

if (x or y > 0)
if (x or y > 0)

rather than
rather than

if (x > 0 or y > 0) // using Borland
if (x > 0 or y > 0) // using Borland
//C++
//C++

if ((x>0)||(y>0))
if ((x>0)||(y>0))
Explanation
Explanation

which are both correct code but
which are both correct code but
logically different.
logically different.

The first expression literally means
The first expression literally means
"if x is true or y is greater than
"if x is true or y is greater than
zero", and x is always true for non-
zero", and x is always true for non-
zero values of x.
zero values of x.
Lazy evaluation.
Lazy evaluation.

C++ compilers implement so-called lazy
C++ compilers implement so-called lazy
evaluation, in which Boolean expressions
evaluation, in which Boolean expressions
are evaluated only until their result is
are evaluated only until their result is
clear.
clear.

For example, false
For example, false and
and anything is always
anything is always
false, true
false, true or
or anything is always true.
anything is always true.

This is a useful technique when you want
This is a useful technique when you want
to avoid making calculations that might
to avoid making calculations that might
cause a crash. For example:
cause a crash. For example:
Lazy evaluation
Lazy evaluation

if (second > 0 && first/second >
if (second > 0 && first/second >
1.2) // eliminate the possibility of
1.2) // eliminate the possibility of
dividing by //zero
dividing by //zero

{...
{...

}
}
Lazy evaluation
Lazy evaluation

In this case if second is indeed zero,
In this case if second is indeed zero,
then the potentially fatal calculation
then the potentially fatal calculation
of first / second is never executed.
of first / second is never executed.
Boolean variables.
Boolean variables.

Some conditions are used several times in
Some conditions are used several times in
the course of a calculation, for example,
the course of a calculation, for example,
whether an individual is entitled to a
whether an individual is entitled to a
discount.
discount.

Rather than re-evaluating the condition
Rather than re-evaluating the condition
you can store it in the form of a Boolean
you can store it in the form of a Boolean
variable. Hence:
variable. Hence:

bool half_price = day = = "Monday" !!
bool half_price = day = = "Monday" !!
age < 15 !! row >= "w";
age < 15 !! row >= "w";
Conditional operator, ? (the
Conditional operator, ? (the
operator is the ?)
operator is the ?)

It is possible to abbreviate some
It is possible to abbreviate some
condition statements using the ?
condition statements using the ?
operator as follows:
operator as follows:

conditional_expression ?
conditional_expression ?
expression_1 : expression_2
expression_1 : expression_2
Conditional operator
Conditional operator
 in which, if conditional_expression is
in which, if conditional_expression is
true, expression_1 is performed,
true, expression_1 is performed,
otherwise expression_2 is carried
otherwise expression_2 is carried
out.
out.
 Note that the expressions must be of
Note that the expressions must be of
the same type.
the same type.
 You can use the conditional operator
You can use the conditional operator
in a straightforward assignment, or
in a straightforward assignment, or
within a more complex statement:
within a more complex statement:
Conditional operator
Conditional operator

max = x > y ? x : y;
max = x > y ? x : y;

//Assigns to max the larger of x and
//Assigns to max the larger of x and
y
y

cout << (s.length() < t.length() ? s :
cout << (s.length() < t.length() ? s :
t); // prints the shorter of s and t
t); // prints the shorter of s and t
The switch statement. (case
The switch statement. (case
statement of Pascal)
statement of Pascal)

This switch statement allows you to
This switch statement allows you to
control the flow of your program by
control the flow of your program by
specifying a number of different
specifying a number of different
cases or conditions, rather than
cases or conditions, rather than
simply true or false.
simply true or false.

See switch1.cpp
See switch1.cpp
Switch
Switch

The switch keyword works by entering program flow at the
The switch keyword works by entering program flow at the
statement whose case matches the expression. All subsequent
statement whose case matches the expression. All subsequent
statements are executed as well, so that if expression were 3 in
statements are executed as well, so that if expression were 3 in
this example, the output would be 363invalid value. This has been
this example, the output would be 363invalid value. This has been
obtained by entering the code at the line
obtained by entering the code at the line

case 3: cout << x * 3; // then multiplying 12 (i.e. x) by 3 giving
case 3: cout << x * 3; // then multiplying 12 (i.e. x) by 3 giving
the 36,
the 36,

then proceeding to the line
then proceeding to the line

case 4: cout << x / 4; // then dividing 12 by 4 giving the 3,
case 4: cout << x / 4; // then dividing 12 by 4 giving the 3,

then proceeding to the final line and outputting the string Invalid
then proceeding to the final line and outputting the string Invalid
Output
Output

You can avoid this state of affairs by placing a
You can avoid this state of affairs by placing a break
break keyword at
keyword at
the end of each case statement, to go to the statement after the
the end of each case statement, to go to the statement after the
curly brackets. switch statements are of limited use: expression
curly brackets. switch statements are of limited use: expression
must always evaluate to a literal and you can have only one value
must always evaluate to a literal and you can have only one value
per case.
per case.

More Related Content

PPTX
Algorithms - Introduction to computer programming
PDF
PROGRAMMING FUNDAMENTALS BASICS LECTURE 1
PDF
L1. Basic Programming Concepts.pdf
PPTX
introduction to problem solving and programming
PDF
Pengenalan algoritma dasar dalam pemrograman
PPT
2.2 Demonstrate the understanding of Programming Life Cycle
PPTX
CPP03 - Repetition
PPT
Computer and programming language
Algorithms - Introduction to computer programming
PROGRAMMING FUNDAMENTALS BASICS LECTURE 1
L1. Basic Programming Concepts.pdf
introduction to problem solving and programming
Pengenalan algoritma dasar dalam pemrograman
2.2 Demonstrate the understanding of Programming Life Cycle
CPP03 - Repetition
Computer and programming language

Similar to Learn Software Programming logic and concepts (20)

PPTX
Introduction_to_Programming.pptx
PPT
Unit1 Part2 1.ppt
PPT
Unit1 Part2 1.ppt
PPT
C programming for Computing Techniques
PDF
Python overview
PPTX
c++ approach of using object oriented programming
PPT
Unit-1 Part2.pptawegawegawergawewrrgawewgd
PDF
notes on Programming fundamentals
PPTX
Lecture1.Introduction to Computer programming.pptx
PPTX
Fundamentals Topic 1 Programming basics.pptx
PPT
Programming
PDF
Software engineering going beyond the black belt
PPT
Programming Fundamentals - Lecture 1.ppt
PDF
Introduction to programming language (basic)
PDF
CS-321 Compiler Design computer engineering PPT.pdf
PPTX
Begin with c++ Fekra Course #1
PPT
SEng522Seminar hardware/software codesign.ppt
PPT
programming.ppt
PPTX
Power Point Introduction To Programming 1
PPSX
Ic lecture8
Introduction_to_Programming.pptx
Unit1 Part2 1.ppt
Unit1 Part2 1.ppt
C programming for Computing Techniques
Python overview
c++ approach of using object oriented programming
Unit-1 Part2.pptawegawegawergawewrrgawewgd
notes on Programming fundamentals
Lecture1.Introduction to Computer programming.pptx
Fundamentals Topic 1 Programming basics.pptx
Programming
Software engineering going beyond the black belt
Programming Fundamentals - Lecture 1.ppt
Introduction to programming language (basic)
CS-321 Compiler Design computer engineering PPT.pdf
Begin with c++ Fekra Course #1
SEng522Seminar hardware/software codesign.ppt
programming.ppt
Power Point Introduction To Programming 1
Ic lecture8
Ad

Recently uploaded (20)

PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
System and Network Administration Chapter 2
PPTX
Introduction to Artificial Intelligence
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Transform Your Business with a Software ERP System
PPTX
ai tools demonstartion for schools and inter college
PDF
Nekopoi APK 2025 free lastest update
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Upgrade and Innovation Strategies for SAP ERP Customers
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Odoo Companies in India – Driving Business Transformation.pdf
System and Network Administration Chapter 2
Introduction to Artificial Intelligence
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Transform Your Business with a Software ERP System
ai tools demonstartion for schools and inter college
Nekopoi APK 2025 free lastest update
Understanding Forklifts - TECH EHS Solution
Internet Downloader Manager (IDM) Crack 6.42 Build 41
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
How to Choose the Right IT Partner for Your Business in Malaysia
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PTS Company Brochure 2025 (1).pdf.......
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Design an Analysis of Algorithms I-SECS-1021-03
2025 Textile ERP Trends: SAP, Odoo & Oracle
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Ad

Learn Software Programming logic and concepts

  • 1. Topics Topics this week this week  Computer Programming Computer Programming  Programming Life-Cycle Phases Programming Life-Cycle Phases  Creating an Algorithm Creating an Algorithm  Machine Language vs. High Level Machine Language vs. High Level Languages Languages  Compilation and Execution Processes Compilation and Execution Processes  Problem-Solving Techniques Problem-Solving Techniques
  • 2. What is Computer Programming? What is Computer Programming?  It is the process of planning It is the process of planning and and implementing implementing a sequence of steps (called a sequence of steps (called instructions) for a computer to follow in instructions) for a computer to follow in order to solve a problem. order to solve a problem. STEP 1 STEP 2 STEP 3 . . .
  • 3. 99.99% of Programs 99.99% of Programs  Getting some information into the Getting some information into the program program  Doing something with the Doing something with the information information  Displaying results Displaying results Nearly all of programs you write will involve: Nearly all of programs you write will involve:
  • 4. Previously we spoke about: Previously we spoke about: Programming Life Cycle Programming Life Cycle 1 Problem-Solving Phase Problem-Solving Phase • Analysis and Specification Analysis and Specification • General Solution (Algorithm) General Solution (Algorithm) • Test/Verify (Desk check) Test/Verify (Desk check) 2 Implementation Phase Implementation Phase • Concrete Solution (Program) Concrete Solution (Program) • Test/Verify Test/Verify 3 Maintenance Phase Maintenance Phase • Use Use • Maintain (update, maintain) Maintain (update, maintain)
  • 5. A Tempting Shortcut? A Tempting Shortcut? GOAL THINKING Problem solving CODE Implementation REVISE REVISE REVISE DEBUG DEBUG DEBUG TEST CODE Shortcut? No thinking
  • 6. Problem-Solving Phase Problem-Solving Phase  ANALYZE ANALYZE the problem and the problem and SPECIFY SPECIFY what what the solution must do. the solution must do.  Develop Develop and write down on a piece and write down on a piece of paper of paper GENERAL SOLUTION GENERAL SOLUTION (ALGORITHM) to solve the problem (ALGORITHM) to solve the problem  VERIFY VERIFY that your solution really that your solution really solves the problem solves the problem. .  How will you know whether your How will you know whether your solution is correct? solution is correct?
  • 7. Example Example A programmer needs an algorithm to A programmer needs an algorithm to determine an employee’s weekly wages. determine an employee’s weekly wages. First think: First think:  How would the calculations be done by How would the calculations be done by hand? hand?  Is there anything that is fixed or constant? Is there anything that is fixed or constant?  Is there anything that changes/varies Is there anything that changes/varies every time I do the sum? every time I do the sum?
  • 8. Analysis: One Employee’s Wages Analysis: One Employee’s Wages Assumptions/Known: Assumptions/Known: 40 hours is a normal week 40 hours is a normal week Normal Hourly Rate of pay Normal Hourly Rate of pay £4.00/hour £4.00/hour Overtime rate of pay £6.00/hour Overtime rate of pay £6.00/hour Variables/Things that change Variables/Things that change Actual hours worked in one week: Actual hours worked in one week:
  • 9. If HoursWorked are more than 40.0 then If HoursWorked are more than 40.0 then wages = (40.0 * NormalRate) + (HoursWorked - 40.0) wages = (40.0 * NormalRate) + (HoursWorked - 40.0) * OvertimeRate * OvertimeRate otherwise, otherwise, wages = HoursWorked * NormalRate wages = HoursWorked * NormalRate Processes/Algorithm: Calculate Weekly Wages Processes/Algorithm: Calculate Weekly Wages
  • 10. Desk Check Calculations (use for testing algorithm) Desk Check Calculations (use for testing algorithm) Use 2 examples of 30 hours and 50 hours Use 2 examples of 30 hours and 50 hours Why? Why? Case 1: 30 hours worked 30 x £ 4.00 = £120.00 ___________ £ 120.00 Case 2: 50 hours worked 40 x £ 4.00 = £160.00 10 x £6.00 = £60.00 ___________ £ 220.00 What are the employee’s wages in each case?
  • 11. IPO Chart IPO Chart Inputs-Process-Outputs Inputs-Process-Outputs Inputs Information the computer needs Processes Things computer needs to do with Inputs Outputs Results computer must display NormalHours HoursWorked NormalRate OvertimeRate If HoursWorked are more than 40.0 then wages = (40.0 * NormalRate) + (HoursWorked - 40.0) * OvertimeRate otherwise, wages = HoursWorked * NormalRate Wages
  • 12. General Algorithm to Determine an General Algorithm to Determine an Employee’s Weekly Wages Employee’s Weekly Wages 1. 1. Initialise Initialise employee’s NormalRate and employee’s NormalRate and OvertimeRate. OvertimeRate. 2. 2. Get the HoursWorked this week from Get the HoursWorked this week from user user 3. 3. Calculate the wages Calculate the wages 4. 4. Display the answer Display the answer It is written in English! We call this pseudocode:
  • 13. Implementation Implementation  We cannot simply write this pseudocode We cannot simply write this pseudocode algorithm as a program. algorithm as a program.  It is merely a program DESIGN It is merely a program DESIGN  YOU have to convert the DESIGN to your YOU have to convert the DESIGN to your chosen chosen programming language programming language (ours at (ours at present is C++) present is C++)  A good design is one that can be easily A good design is one that can be easily converted into code not just C++. converted into code not just C++.  A poor design is difficult to convert A poor design is difficult to convert  A design should be “language” independent A design should be “language” independent • i.e. We can write the code in Java, VB etc i.e. We can write the code in Java, VB etc
  • 14. So what is a Programming Language? So what is a Programming Language?  It is a language with strict It is a language with strict grammatical rules, symbols, and grammatical rules, symbols, and special words used to construct a special words used to construct a computer program. computer program. • Syntax = grammar Syntax = grammar • Semantics = meaning Semantics = meaning
  • 15. Why a programming language? What is Why a programming language? What is wrong with English? wrong with English?  Computers do not understand English! Computers do not understand English!  English is a English is a natural language natural language and and requires each of us to understand requires each of us to understand meaning by context. meaning by context.  For Example For Example • Lung Cancer in Women explodes Lung Cancer in Women explodes • Red Tape Holds Up New Bridges Red Tape Holds Up New Bridges • Hospitals are sued by 7 Foot Doctors Hospitals are sued by 7 Foot Doctors • Star's Broken Leg Hits Box Office Star's Broken Leg Hits Box Office • Villagers Grill Gas Men Villagers Grill Gas Men
  • 16. Computers are really stupid! Computers are really stupid!  Computers do not understand anything! Computers do not understand anything! • well not quite they understand what a 1 well not quite they understand what a 1 and a 0 is. and a 0 is.  Computers follow instructions Computers follow instructions • Instructions have to be written in 1s Instructions have to be written in 1s and 0s and 0s • Such instructions are called machine Such instructions are called machine code. code. • We do not write in machine code We do not write in machine code
  • 17. Machine language Machine language  Machine languages Machine languages 11000000 000000000001 11000000 000000000001 000000000010 000000000010 Add contents of memory location 1 to Add contents of memory location 1 to contents of memory location 2 contents of memory location 2  Not easy to write programs in! Not easy to write programs in! Assembly Assembly  ADD 1 ADD 1 2 2  Needs an assembler to translate to machine Needs an assembler to translate to machine language (an assembler is software that language (an assembler is software that converts the program into machine code) converts the program into machine code) Opcode
  • 18. Levels of Levels of Programming Languages Programming Languages Levels of Computer Languages: Levels of Computer Languages:  Low (a long way from English) Low (a long way from English) • machine language, assembly language machine language, assembly language • not portable not portable  High (Closer to English) High (Closer to English) • COBOL, Pascal, FORTRAN, Logo, Basic COBOL, Pascal, FORTRAN, Logo, Basic, , Visual Basic, Prolog, Visual Basic, Prolog, C, C++ and Java C, C++ and Java
  • 19. High level languages High level languages  Deliberately terse (concise). Deliberately terse (concise).  Must be unambiguous. Must be unambiguous.  Must be flexible enough to easily Must be flexible enough to easily implement algorithms. implement algorithms.  Fairly portable Fairly portable
  • 20. Creating Creating machine ( machine (executable executable) code from ) code from C+ C+ + + source code : source code : Compilation and linking Compilation and linking source code source code compiler object code object code linked to libraries .exe file .exe file
  • 21. Implementation Phase: Test Implementation Phase: Test  TESTING your program means running TESTING your program means running (executing) your program on the computer, (executing) your program on the computer, to see if it produces correct results. to see if it produces correct results. (Verification) (Verification)  if it does not, then you must find out what is if it does not, then you must find out what is wrong with your program or algorithm and wrong with your program or algorithm and fix it--this is called debugging fix it--this is called debugging . .  Compilers do not fix logic errors. Compilers do not fix logic errors.
  • 22. Maintenance Phase Maintenance Phase  USE and MODIFY the program to meet USE and MODIFY the program to meet changing requirements or correct errors changing requirements or correct errors that show up when using it that show up when using it  maintenance begins when your program maintenance begins when your program is put into use and accounts for the is put into use and accounts for the majority of effort on most programs majority of effort on most programs  You will not be concerned very much with You will not be concerned very much with this phase while you learn. this phase while you learn.  But when you are in industry this is a But when you are in industry this is a massive part of your job! massive part of your job!
  • 23. The Basic Control Structures The Basic Control Structures in programming in programming  a a sequence sequence is a series of is a series of statements that execute one after statements that execute one after another another  selection selection (branch) is used to (branch) is used to execute different statements execute different statements depending on certain conditions depending on certain conditions (Boolean conditions) (Boolean conditions)  Iteration Iteration (repetition) is used to (repetition) is used to repeat statements while certain repeat statements while certain conditions are met. Often requires conditions are met. Often requires the use of loops. the use of loops.
  • 24. Organising Structures Organising Structures (functions in C++) (functions in C++)  Stepwise refinement Stepwise refinement • Breaking big problems into smaller bits Breaking big problems into smaller bits  “ “Natural” problem solving strategy Natural” problem solving strategy  Most common approach in programming Most common approach in programming  Different people can work on different “bits” Different people can work on different “bits”  Nearly all high level languages support this Nearly all high level languages support this
  • 25. Stepwise refinement Stepwise refinement  the breaking down of problems into a the breaking down of problems into a series of single-function tasks and series of single-function tasks and single-function subtasks. single-function subtasks.  We previously discussed functions. We previously discussed functions.
  • 26. SEQUENCES SEQUENCES Statement Statement Statement . . . 1. Get the user to input a number 2. Calculate the result e.g. number * 10 3. Display the result Note the logical order!
  • 27. SELECTION (branch) SELECTION (branch) IF Condition THEN Statement1 ELSE Statement2 Statement1 Statement Statement2 Condition . . . True False 1. Get the user to input a number 2. IF the number is greater than 0 then 1. Calculate the result = number * 10 3. ELSE 1. Calculate the result = number * (-10) 4. Display the result
  • 28. LOOP (repetition) LOOP (repetition) Statement1 Condition . . . False True WHILE Condition DO Statement1 So Statement1 is executed as long as the condition is true.
  • 29. Loop (repetition) Example Loop (repetition) Example 1. Repeat While there are more numbers to process 1. Get the user to input a number 2. IF the number is greater than 0 then 1. Calculate the result = number * 10 3. ELSE (otherwise) 1. Calculate the result = number (- 10) 4. Display the result 2. End repeat
  • 30. function function FUNCTION1 . . . FUNCTION1 a meaningful collection of SEQUENCE, SELECTION, LOOP STATEMENTS &/OR FUNCTIONS
  • 31. Subprogram CalculateResult Subprogram CalculateResult Precondition: Needs a number to work with Postcondition: returns a result depending on the number 1. if the number is greater than 0 then 1. Calculate the result = number * 10 2. else 1. Calculate the result = number (-10) 3. return the result
  • 32. Use of subprogram Use of subprogram 1. Get the user to input a number 2. Repeat While there are more numbers to process 1. result =CalculateResult(number) 2. Display the result 3. Get the user to enter next number 3. End repeat 1. Get the user to input a number 2. Repeat While there are more numbers to process 1. IF the number is greater than 0 then 1. Calculate the result = number * 10 2. ELSE (otherwise) 1. Calculate the result = number * -10 3. Display the result 4. Get the user to enter next number 3. End repeat
  • 33. #include <iostream> using namespace std; double CalculateResult(double number); int main() { float n; float answer; cout << "Please enter a number: "; //1) get the user to enter a number cin >> n; while (n != 0) { //2) loop use the value 0 to stop loop answer = CalculateResult(n); //2.1) call function cout << "The answer is " << answer << endl; //2.2) display answer cout << "Please enter a number: "; //2.3) ask for next number cin >> n; } // 3) end loop return 0; } double CalculateResult(double number) { // subprogram/function definition float result; if (number > 0) result = number * 10.0; else result = number * -10.0; return result; }//see calculate1.cpp
  • 34. Problem Solving Techniques Problem Solving Techniques  OVERCOME MENTAL BLOCK -- by rewriting the OVERCOME MENTAL BLOCK -- by rewriting the problem in your own words problem in your own words  DRAW A FIGURE/DIAGRAM DRAW A FIGURE/DIAGRAM  ASK QUESTIONS – ASK QUESTIONS – • What is the data, What sort of data is it? what would What is the data, What sort of data is it? what would be good identifiers (names) for the data. be good identifiers (names) for the data. • How much data is there, where does it come from? Is How much data is there, where does it come from? Is it given? Do you get it from the user? do you calculate it given? Do you get it from the user? do you calculate it? do you get it from a file? it? do you get it from a file? • Can you identify what is input and what is to be Can you identify what is input and what is to be output? output? • What are What are the processes the processes? ?  Do you need to repeat steps Do you need to repeat steps • What are the conditions? What are the conditions?  Do you need to do different things in different situations? Do you need to do different things in different situations? • What are the conditions What are the conditions
  • 35. Problem Solving Techniques Problem Solving Techniques  LOOK FOR FAMILIAR THINGS -- certain LOOK FOR FAMILIAR THINGS -- certain situations arise situations arise again and again. E.g. creating again and again. E.g. creating tables, adding up lists of numbers, reading from tables, adding up lists of numbers, reading from files. files.  Do you know any equations? Do you know any equations? • Find the area of a room, find the stopping distance of a Find the area of a room, find the stopping distance of a car. car.  SOLVE BY ANALOGY -- it may give you a place to SOLVE BY ANALOGY -- it may give you a place to start. start. In a broader sense than looking for In a broader sense than looking for familiar things. familiar things. • E.g. Finding the student with the highest and lowest E.g. Finding the student with the highest and lowest score is analogous to finding the highest and lowest score is analogous to finding the highest and lowest temperature. temperature.
  • 36. Problem Solving Problem Solving  USE MEANS-ENDS ANALYSIS USE MEANS-ENDS ANALYSIS • Where you often know start conditions and know Where you often know start conditions and know what the end goal is. what the end goal is. • Identify intermediate goals then think how you Identify intermediate goals then think how you get from start to the intermediary goals get from start to the intermediary goals • E.g. How do you find your way to the canteen/bar E.g. How do you find your way to the canteen/bar from here? from here?  Setup intermediary goals: get to reception, past Setup intermediary goals: get to reception, past bookshop, security and lifts then canteen. bookshop, security and lifts then canteen.  Get to stairs, get to reception, go down the stairs Get to stairs, get to reception, go down the stairs
  • 37. More Problem Solving Techniques More Problem Solving Techniques  Stepwise refinement -- break up large Stepwise refinement -- break up large problems into manageable units. problems into manageable units.  SIMPLIFY SIMPLIFY • Can you solve a simpler but related Can you solve a simpler but related problem? problem? • E.g. Bobs DIY:- Do not attempt to solve the general E.g. Bobs DIY:- Do not attempt to solve the general problem but solve the simpler cases problem but solve the simpler cases  BUILDING-BLOCK APPPROACH -- can you BUILDING-BLOCK APPPROACH -- can you solve small pieces of the problem? And then solve small pieces of the problem? And then join them up join them up • E.g. a large application like a word processor has E.g. a large application like a word processor has many functions. (Text manipulation, Tables, many functions. (Text manipulation, Tables, drawing) drawing) • Do not try to solve all at once. Do not try to solve all at once.
  • 38. Result of Problem solving Result of Problem solving 1. 1. One or more pages of rough work that sketches One or more pages of rough work that sketches your ideas of problem requirements, of user your ideas of problem requirements, of user inputs, of outputs, of constants, of conditions inputs, of outputs, of constants, of conditions for repetition and selection, of assumptions. for repetition and selection, of assumptions. 2. 2. A formal written design that includes: A formal written design that includes: 1. 1. inputs, Processes, Outputs, assumptions. inputs, Processes, Outputs, assumptions. Create an IPO chart Create an IPO chart 2. 2. Write steps to process input unambiguously Write steps to process input unambiguously using a semi formal notation (PDL, Flowchart using a semi formal notation (PDL, Flowchart or structure diagram?) Can you translate or structure diagram?) Can you translate each step of the plan into C++ easily? each step of the plan into C++ easily? 3. 3. Verification/testing procedures documented Verification/testing procedures documented (A test table). (A test table).
  • 39. What we are aiming for is a What we are aiming for is a Structured Structured Systematic Systematic Approach to Approach to Programming Programming Advantages: Advantages:  Not one giant step, but breaks in to smaller Not one giant step, but breaks in to smaller and smaller chunks. and smaller chunks.  Programmer concentrates on details Programmer concentrates on details  Easy to do in teams Easy to do in teams  Easy to keep track of development Easy to keep track of development  Creates more reliable and robust programs. Creates more reliable and robust programs.  Makes more possible reuse and extensibility. Makes more possible reuse and extensibility.
  • 40. Structured Programming Structured Programming  Errors isolated Errors isolated  Design written in code Design written in code  Improves reliability Improves reliability  Minimizes risk of Failure Minimizes risk of Failure  Faster development Faster development  Full documentation Full documentation • Maintainability Maintainability
  • 41.  So find a solution, write it down in So find a solution, write it down in English. English.  Write it down more formally in Pseudo- Write it down more formally in Pseudo- code (PDL), or as a structure diagram or code (PDL), or as a structure diagram or a flow chart. a flow chart.  Start your programming environment and Start your programming environment and convert your pseudo-code to C++ convert your pseudo-code to C++  Tell the computer to convert the C++ to Tell the computer to convert the C++ to machine language (compile) machine language (compile)  Tell the computer to load the machine Tell the computer to load the machine language into memory and execute language into memory and execute (Run). (Run). Summary Summary
  • 42. Note Note  Learning C++ syntax by heart is Learning C++ syntax by heart is useless! useless!  Experience essential Experience essential  You will need to build up a virtual You will need to build up a virtual scrapbook of techniques to be scrapbook of techniques to be successfu successful l
  • 43. “ “Get some information in, Get some information in, Do something with it, Do something with it, Display the result.” Display the result.”
  • 44. “ “Get some information in, Get some information in, Do something with it, Do something with it, Display the result.” Display the result.”
  • 45. Topics Topics  Structure of a simple C++ Program Structure of a simple C++ Program  TYPES of information TYPES of information • Simple and Complex Simple and Complex  Variables, Constants and Literals Variables, Constants and Literals  Identifiers: to Name memory Identifiers: to Name memory  Declarations Declarations  Getting information into your program Getting information into your program  Operator basics Operator basics
  • 46. Shortest C++ Program Shortest C++ Program. . A Skeleton program A Skeleton program int main ( ) { return 0; } //already run and discussed type of returned value name of function
  • 47. What happens? What happens?  The operating system (Windows ) The operating system (Windows )  “ “Loads” the program Loads” the program  Think of it as WINDOWS calling the “main” function. Think of it as WINDOWS calling the “main” function.  Instructions “in main” are carried out one at a time. Instructions “in main” are carried out one at a time.  Notice the “int” in front of “main” this line is like a Notice the “int” in front of “main” this line is like a contract to the operating system contract to the operating system • “ “I will send you a piece of information in the form of an I will send you a piece of information in the form of an integer.” integer.” • Hence the NEED for a return instruction. return 0 sends a Hence the NEED for a return instruction. return 0 sends a zero to windows XP zero to windows XP
  • 48. Discussion of structure Discussion of structure  Your program must have a function called Your program must have a function called “main” “main”  Note that Main, MAIN, mAiN will cause an Note that Main, MAIN, mAiN will cause an error error  The round brackets ‘(‘ and ‘)’after main The round brackets ‘(‘ and ‘)’after main tells the computer that main is a tells the computer that main is a function function rather than a variable rather than a variable  The curly brackets (parentheses) ‘{‘ and The curly brackets (parentheses) ‘{‘ and ‘}’ mark the beginning and end of ‘}’ mark the beginning and end of instructions that form the instructions that form the body body of main. of main. • i.e. They are i.e. They are blocks blocks  The semi-colon ‘;’ after return 0 is an The semi-colon ‘;’ after return 0 is an instruction terminator or separator. instruction terminator or separator.
  • 49. #include <iostream> using namespace std; int main ( ) { cout << “Hello World” << endl; return 0; } //already run The “Hello World” Program The “Hello World” Program uses complex information i.e. the display (cout) uses complex information i.e. the display (cout) needs more effort needs more effort Instructions to tell computer that I want to use standard complex OBJECTS for input and output
  • 50. Discussion of Hello World Program Discussion of Hello World Program  There are now two instructions in main There are now two instructions in main • we added a display information instruction using a we added a display information instruction using a complex OBJECT cout complex OBJECT cout • cout represents the display screen. That is why it is cout represents the display screen. That is why it is complex. It hides all the complicated business of complex. It hides all the complicated business of displaying things from you. All you need to know is displaying things from you. All you need to know is how to send information to cout. how to send information to cout. • cout receives information using the “<<“ send to cout receives information using the “<<“ send to operator. operator. • So we literally send the string “Hello World” to the So we literally send the string “Hello World” to the display! display! • endl is also sent to the display, this is interpreted by endl is also sent to the display, this is interpreted by cout as a new-line command. cout as a new-line command.
  • 51. Discussion of Hello World Discussion of Hello World  So cout OBJECT represents our screen. So cout OBJECT represents our screen.  Screens are hardware. Screens are hardware.  Sending information to screens varies Sending information to screens varies greatly from machine to machine. greatly from machine to machine.  So cout became “standard”. So cout became “standard”.  Customised cout’s were created for all the Customised cout’s were created for all the major types of computer in the world. major types of computer in the world.  So that you can write one piece of code So that you can write one piece of code that should compile on all the main types that should compile on all the main types of computer in the world. of computer in the world.
  • 52. Discussion of Hello World Discussion of Hello World  Because cout is NOT “BUILT IN” we need to tell Because cout is NOT “BUILT IN” we need to tell the computer that we want to make use of the the computer that we want to make use of the “standard” facilities for input and output “standard” facilities for input and output  HENCE the lines HENCE the lines #include <iostream> #include <iostream> using namespace std; using namespace std; This is one of the original reasons for C++’s popularity i.e., its relative ease of porting from one type of computer to another
  • 53. Some Definitions Some Definitions  Statements Statements • A statement is what programmers often call an A statement is what programmers often call an instruction. instruction. • Your code consists of many instructions Your code consists of many instructions • Your code consist of many statements Your code consist of many statements • Statements must end with a semi-colon Statements must end with a semi-colon  blocks blocks • Any section of code which is surrounded by Any section of code which is surrounded by curly brackets is a curly brackets is a block { } block { }
  • 54. Example Example A Block of A Block of 4 4 statements statements { { cout <<"A fraction: "<<5.0/8.0 <<endl; cout <<"A fraction: "<<5.0/8.0 <<endl; cout <<"Big # : "<< cout <<"Big # : "<< 7000.0*7000.0<<endl; 7000.0*7000.0<<endl; cout <<8 + 5 <<" is the sum of 8 & 5n"; cout <<8 + 5 <<" is the sum of 8 & 5n"; cout << “Hello world”; cout << “Hello world”; } } Block denoted by Curly braces
  • 55. TYPES of information computers use TYPES of information computers use  Simple (needs little or no effort to use) Simple (needs little or no effort to use) • To hold whole numbers (integers) To hold whole numbers (integers) • To hold numbers with fractions (float and To hold numbers with fractions (float and double) double) • To hold individual characters (char) To hold individual characters (char)  Complex (needs a little more work to use) Complex (needs a little more work to use) • Strings Strings • Records Records • cin and cout cin and cout
  • 56. Simple Information Simple Information  integer (whole numbers) integer (whole numbers) • For counting things For counting things • To represent values which only have To represent values which only have whole numbers whole numbers  Pounds, Pence? Pounds, Pence?  Grades, Scores (Chelsea 10 : United 0) Grades, Scores (Chelsea 10 : United 0)  Categories Categories int
  • 57. Simple Information Simple Information  Floating points numbers Floating points numbers • For representing numbers that may For representing numbers that may contain fractions contain fractions • Averages, measurements. Averages, measurements. • pi, e, phi pi, e, phi float double
  • 58. Simple information Simple information  Single characters Single characters  Can represents your initials Can represents your initials  Can represent single key responses Can represent single key responses to questions to questions • ‘ ‘y’ for yes and ‘n’ for no y’ for yes and ‘n’ for no  Not much else Not much else
  • 59. What about Strings What about Strings  In some languages this is a simple piece In some languages this is a simple piece of information of information  In C++ it is not. A string is complex in In C++ it is not. A string is complex in that it is made up of lots of chars. that it is made up of lots of chars.  In C++ we use the “standard” string In C++ we use the “standard” string facilities facilities #include <string> string
  • 60. Recap! Recap!  Your programs will initially entail Your programs will initially entail • Getting information into the computer Getting information into the computer  This information will either be whole numbers, This information will either be whole numbers, floating point numbers, single characters or floating point numbers, single characters or strings. strings.  More complex information we will cover at a later More complex information we will cover at a later date. date. • Doing something (operate on) with the Doing something (operate on) with the information (int, float, double, char or string) information (int, float, double, char or string) • Displaying results Displaying results
  • 61. Constants, Variables and Constants, Variables and Literals Literals Remember at school Remember at school Area of a circle is Area of a circle is π πr r2 2 Circumference of a circle is 2 Circumference of a circle is 2π πr r π π is a is a constant constant representing the number representing the number 3.1415925 3.1415925… ….. .. r is a r is a variable variable representing the radius of a representing the radius of a circle circle 2 literally represents itself, it is a 2 literally represents itself, it is a literal literal Fundamental building blocks of programs
  • 62. Key programming concept Key programming concept  Programs use, variables, constants Programs use, variables, constants and literals to store information and literals to store information needed to solve problems needed to solve problems  Remember the bank problem or Remember the bank problem or Bobs DIY (looked at) we used Bobs DIY (looked at) we used variables to hold values for wall variables to hold values for wall height and widths etc. height and widths etc.
  • 63. Fundamental task is Fundamental task is Getting information in to the computer Getting information in to the computer  Key ideas Key ideas • We enter values of We enter values of literals literals directly into directly into code. code. • We enter values of We enter values of constants constants directly into directly into code code • We have a choice on how we enter values of We have a choice on how we enter values of variables variables. .  We can enter values directly We can enter values directly  Values can be set interactively with a user. Values can be set interactively with a user.  Values can be set interactively with a file on disk. Values can be set interactively with a file on disk.
  • 64. Using literals Using literals  char, string, integer, float and char, string, integer, float and double values are referred to by double values are referred to by value not by a name. value not by a name.  We type these directly into code We type these directly into code #include <iostream> using namespace std; int main() { cout <<“The sum of one plus three is “ << 1 + 3 << endl; return 0 } string literal 2 integer literals
  • 65. Char literals Char literals #include <iostream> using namespace std; int main() { cout <<“First letter of the alphabet is “ << ‘A’ << endl; return 0; } //see char1.cpp char literals in SINGLE QUOTES
  • 66. floating point literals floating point literals  floating point number can contain floating point number can contain fractions. fractions.  floating point literals are doubles floating point literals are doubles #include <iostream> using namespace std; int main() { cout <<“one point one plus three point two is “ << 1.1 + 3.2 << endl; return 0; }//this is Float1.cpp 2 double literals
  • 67. Discussion Discussion  You can enter information directly into code using You can enter information directly into code using literals literals  This is obviously very limiting if a program wanted This is obviously very limiting if a program wanted to reuse a value we need to keep typing in its to reuse a value we need to keep typing in its value every time. value every time.  Also if a program makes use of a value many Also if a program makes use of a value many times it is hard work to change all the CORRECT times it is hard work to change all the CORRECT references in a long program, especially if the references in a long program, especially if the number, say 10 refers to a count in one part of number, say 10 refers to a count in one part of the program and the number 10 means a grade in the program and the number 10 means a grade in another. another.  How can we differentiate between them? How can we differentiate between them?  It can also be very confusing for another person to It can also be very confusing for another person to understand what the numbers mean understand what the numbers mean. .
  • 68. Solution Solution Variables and Constants Variables and Constants  These are NAMED areas of memory. These are NAMED areas of memory.  The programmer instructs the The programmer instructs the computer to reserve space for the computer to reserve space for the kind of information he/she wants and kind of information he/she wants and at the same time tell the computer at the same time tell the computer the name that will be used to refer to the name that will be used to refer to that bit of information. that bit of information.  This kind of instruction is called a This kind of instruction is called a DECLARATION DECLARATION
  • 69. DECLARATION DECLARATION  We can declare We can declare • integers integers • floating point numbers (doubles) floating point numbers (doubles) • chars chars • strings strings
  • 70. Constants and Variable Constants and Variable Declarations Declarations  When a When a variable variable is declared the is declared the computer marks the bit of memory computer marks the bit of memory reserved so that it allows its contents reserved so that it allows its contents to change (vary) at any time. In to change (vary) at any time. In particular at run time particular at run time  When a When a constant constant is declared the is declared the computer effectively locks the computer effectively locks the memory reserved and prevents the memory reserved and prevents the contents being updated. contents being updated.
  • 71. Creating Constants and Creating Constants and Variables Variables #include <iostream> using namespace std; int main() { const double Pi = 3.142; double radius; double Area, Circumference; Area = Pi*radius*radius; Circumference = 2*Pi*radius; return 0; } //see constants.cpp //also calculates phi Declarations are instructions to reserve memory space big enough to store our information. It also creates an identifier (a name) for us to refer to this memory space
  • 72. Rules for Creating Constants Rules for Creating Constants const type identifier = value; <type> choose one of int char float double string <identifier> You create a name. It must obey the rules for identifiers (see rules in a minute) <value> You provide the constant value e.g. for Pi value was 3.141592
  • 73. Examples Examples const int maxnumber = 10; const double Pi = 3.142; const char AGrade = ‘A’; const string MyName = “Vas”;
  • 74. Rules for Creating Variables Rules for Creating Variables type identifier; or Type identifier = value; or type identifier, identifier, …;
  • 75. Examples Examples int number; double Result; char response; string UserName; int n1, n2, n3, n4; Declare a double variable and set its initial value double x = 5.6;
  • 76. Rules for Creating Identifiers Rules for Creating Identifiers  A An identifier must start with a letter or underscore, n identifier must start with a letter or underscore, and be followed by zero or more letters and be followed by zero or more letters (A-Z, a-z), digits (0-9), or underscores (A-Z, a-z), digits (0-9), or underscores  VALID VALID age_of_dog age_of_dog taxRateY2K taxRateY2K PrintHeading PrintHeading ageOfHorse ageOfHorse  NOT VALID (Why?) NOT VALID (Why?) age# 2000TaxRate age# 2000TaxRate Age-Of-Cat Age-Of-Cat Age of Cat Age of Cat
  • 77. Meaningful Identifiers Meaningful Identifiers Age-Of-Cat Age-Of-Cat Age of Cat Age of Cat ILLEGAL!! Use underscore to link words or run words together and capitalise the start of each word Age_Of_Cat Age_Of_Cat AgeOfCat AgeOfCat LEGAL!!
  • 78. More About Identifiers More About Identifiers  C++ is case sensitive so C++ is case sensitive so NUMBER NUMBER Number number Number number are all legitimate but DIFFERENT identifiers are all legitimate but DIFFERENT identifiers BE CONSISTENT in your code! BE CONSISTENT in your code!  It is NOT good practice to have long identifiers It is NOT good practice to have long identifiers  Why? Why?
  • 79. Long Identifier Names Long Identifier Names  Some C++ compilers recognize only the Some C++ compilers recognize only the first 32 first 32 characters characters of an identifier as significant of an identifier as significant  then these identifiers are considered the same: then these identifiers are considered the same: age_Of_This_Old_Rhinoceros_At_My_Zoo age_Of_This_Old_Rhinoceros_At_My_Zoo age_Of_This_Old_Rhinoceros_At_My_Safari age_Of_This_Old_Rhinoceros_At_My_Safari  Also it is very annoying to keep typing in! Also it is very annoying to keep typing in!
  • 80. Meaningful Identifiers Meaningful Identifiers  It is common sense to try to create It is common sense to try to create identifiers that are: identifiers that are:  Meaningful:- they describe the Meaningful:- they describe the information they refer to information they refer to • E.g. Height, Count, BloodPressure, E.g. Height, Count, BloodPressure, CarSpeed CarSpeed  Terse:- They are only as long as Terse:- They are only as long as necessary to convey meaning. necessary to convey meaning.
  • 81. Reserved Words Reserved Words • Identifiers CANNOT be a reserved word. Identifiers CANNOT be a reserved word. • Reserved words are built in words Reserved words are built in words that have that have special meanings in the language. special meanings in the language. • They must be used only for their specified They must be used only for their specified purpose. Using them for any other purpose will purpose. Using them for any other purpose will result in a error. result in a error. • e.g. do e.g. doif if switch switch while while else else return return *
  • 82. Reserved Words Reserved Words  C++ is case sensitive. ALL reserved C++ is case sensitive. ALL reserved words are lower case words are lower case WHILE While while Are all different identifiers only the last is a reserved word
  • 83. Operators Operators  All the data types we have seen (int, float, All the data types we have seen (int, float, double, char and string) have a set of double, char and string) have a set of operators that can be applied to them operators that can be applied to them  E.g. Numerical data uses the familiar + - / E.g. Numerical data uses the familiar + - / for add subtract and divide. for add subtract and divide.  The asterisk * is used for multiplication The asterisk * is used for multiplication  These work in the usual manner These work in the usual manner
  • 84. string operators string operators  arithmetic is not meaningful when applied to arithmetic is not meaningful when applied to strings strings  You do not multiply first names! You do not multiply first names!  strings operators do other things strings operators do other things  E.g. The + operator applied to strings joins E.g. The + operator applied to strings joins them (concatenates) together them (concatenates) together  We will see other operations we want to do with We will see other operations we want to do with strings; like searching a string for a substring strings; like searching a string for a substring or comparing strings. or comparing strings.
  • 85. Expressions Expressions A VALID arrangement of variables, A VALID arrangement of variables, constants, literals and operators constants, literals and operators Expressions are evaluated and Expressions are evaluated and compute a VALUE of a given type compute a VALUE of a given type E.g. Expression 9 + 4 E.g. Expression 9 + 4 computes to 13 computes to 13
  • 86. A special OPERATOR A special OPERATOR The assignment operator = Causes much confusion! IT DOES NOT WORK LIKE EQUALS IN MATHS
  • 87. variable = expression variable = expression number = 4; number = 4; result = 10 * number; result = 10 * number; number = number + 1; number = number + 1; expression simply consists of the literal int 4. number “takes the value of” 4 Interpretation of = “Takes the value of” KEY POINT: expression is evaluated BEFORE it is applied expression evaluates to 40. result “takes the value of” 40 expression evaluates to 5 number “takes the value of” 5
  • 88. Using assignments to get Using assignments to get information into the computer information into the computer int myage; int myage; string myname; string myname; double mysalary; double mysalary; myage = 21; myage = 21; myname = “Vas”; myname = “Vas”; mysalary = 1000.00; mysalary = 1000.00;
  • 89. Interactive input formally covered Interactive input formally covered later later  using cin and cout using cin and cout  using data files using data files
  • 90. Programming in C++ Programming in C++ Lecture 2b Lecture 2b Types, Operators, Expressions Types, Operators, Expressions
  • 91. Overview Overview  Types Types • Binary arithmetic Binary arithmetic  Operators Operators • Arithmetic, logical, assignment Arithmetic, logical, assignment  Expressions/Statements Expressions/Statements • Declarations Declarations • Assignments Assignments • Other one-line operations Other one-line operations  More program examples More program examples
  • 92. Types Types  “ “Type” in C++ refers to the kind of data or Type” in C++ refers to the kind of data or information that is to be stored in the information that is to be stored in the variable variable  A variable is a quantity that can be A variable is a quantity that can be changed during a program changed during a program  Functions have return types, i.e. can return Functions have return types, i.e. can return expressions to the calling function expressions to the calling function  Arguments to functions each have their Arguments to functions each have their own type (these are passed to the function) own type (these are passed to the function)  Variables have types Variables have types
  • 93. Why Type? Why Type?  Why do we have to specify types of variables, Why do we have to specify types of variables, functions, arguments? functions, arguments?  Has to do with computer memory Has to do with computer memory  Different kinds of data require different amounts of Different kinds of data require different amounts of memory to store memory to store • A single character can have only one of 128 values A single character can have only one of 128 values (a-z,A-Z,0-9,punctuation, some others) (a-z,A-Z,0-9,punctuation, some others) • An integer (in the mathematical sense) can have an An integer (in the mathematical sense) can have an infinite number of values, on a computer however infinite number of values, on a computer however this is limited to ~65,000 values, depends on how this is limited to ~65,000 values, depends on how many bits are used many bits are used • Therefore, more memory is needed to store an Therefore, more memory is needed to store an integer than a character integer than a character
  • 94. Computer Memory Computer Memory  Memory in computers is made up of Memory in computers is made up of transistors transistors  Transistor: just a switch that can be either Transistor: just a switch that can be either on or off, easier to have just two electrical on or off, easier to have just two electrical states rather that 10 (i.e. to represent 0-9) states rather that 10 (i.e. to represent 0-9)  “ “on” state corresponds to the value 1, “off” on” state corresponds to the value 1, “off” state corresponds to the value 0 state corresponds to the value 0  Everything in memory has to be made up of Everything in memory has to be made up of 0s and 1s – i.e., has to be stored as a 0s and 1s – i.e., has to be stored as a number in base 2 (binary) number in base 2 (binary)  Important to understand different bases Important to understand different bases
  • 95. Reminder:Converting Between Reminder:Converting Between Bases Bases  To convert numbers in some other base To convert numbers in some other base into base 10 (decimal) values: into base 10 (decimal) values: • For each position, starting with position 0, the For each position, starting with position 0, the least significant digit (rightmost), take the digit least significant digit (rightmost), take the digit in that position and multiply it by the base in that position and multiply it by the base raised to the power of that position; add the raised to the power of that position; add the values together values together • 10 in base 2 = 1x2 10 in base 2 = 1x21 1 + 0x2 + 0x20 0 = 2+0 = 2 = 2+0 = 2 • 100101 in base 2 = 1x2 100101 in base 2 = 1x25 5 + 1x2 + 1x22 2 + 1x2 + 1x20 0 = 32 + = 32 + 4 + 1 = 37 4 + 1 = 37
  • 96. Converting Between Bases Converting Between Bases  Hexadecimal (base 16) uses the digits 0-9 + Hexadecimal (base 16) uses the digits 0-9 + A-E (A=10, B=11,…E=15) and prefix 0x to A-E (A=10, B=11,…E=15) and prefix 0x to differentiate from decimal //a zero 0 not an o differentiate from decimal //a zero 0 not an o  To convert binary to hexadecimal, group To convert binary to hexadecimal, group binary digits in groups of 4, convert each binary digits in groups of 4, convert each group of 4 into decimal, and use the group of 4 into decimal, and use the appropriate hex digit for that group of 4 appropriate hex digit for that group of 4  100101 in base 2 = 0010 0101 100101 in base 2 = 0010 0101 first hex digit = 0010 or 2 first hex digit = 0010 or 2 second hex digit = 0101 or 5 second hex digit = 0101 or 5 0x25 = 2x16 0x25 = 2x161 1 + 5x16 + 5x160 0 = 32 + 5 = 37 = 32 + 5 = 37  See See OctalandHex.cpp OctalandHex.cpp
  • 97. Converting Between Bases Converting Between Bases  Octal (base 8) numbers prefixed with 0 Octal (base 8) numbers prefixed with 0 (zero) (zero)  052 in base 8 = 5x8 052 in base 8 = 5x81 1 + 2x8 + 2x80 0 = 40+ 2 = 42 = 40+ 2 = 42  Octal conversion to binary: same as hex, but Octal conversion to binary: same as hex, but group digits into groups of 3 group digits into groups of 3  100101 in base 2 = 100 101 100101 in base 2 = 100 101 first octal digit = 100 or 4 first octal digit = 100 or 4 second octal digit = 101 or 5 second octal digit = 101 or 5 045 = 4x8 045 = 4x81 1 + 5x8 + 5x80 0 = 32 + 5 = 37 = 32 + 5 = 37  See OctalandHex.cpp See OctalandHex.cpp
  • 98. Common Bases Common Bases  Binary, octal (base 8), hexadecimal Binary, octal (base 8), hexadecimal (base 16) all common bases in (base 16) all common bases in programming programming  Useful because powers of 2 and easy Useful because powers of 2 and easy to convert between to convert between  Computer memory almost always in Computer memory almost always in powers of 2 powers of 2
  • 99. Back to Types Back to Types  Types typically defined in pieces of memory that are Types typically defined in pieces of memory that are powers of 2 powers of 2  Smallest piece of memory: 1 bit (Binary DigIT) Smallest piece of memory: 1 bit (Binary DigIT) • Can hold 0 or 1 (equivalent to 1 transistor) Can hold 0 or 1 (equivalent to 1 transistor)  8 bits = 1 byte, 4 bits is a nibble 8 bits = 1 byte, 4 bits is a nibble • 1 byte can have any value between 0000 0000 and 1 byte can have any value between 0000 0000 and 1111 1111 – i.e., between 0 – 255. 1111 1111 – i.e., between 0 – 255. • 1111 1111 binary 1111 1111 binary hex digit: 1111 = 8+4+2+1 = 15 = E hex digit: 1111 = 8+4+2+1 = 15 = E 0xEE = 15x16 0xEE = 15x161 1 + 15x16 + 15x160 0 = 240 + 15 = 255 = 240 + 15 = 255 • More than number of values needed for characters – More than number of values needed for characters – 1 byte typically used for character type 1 byte typically used for character type
  • 100. Numeric Types Numeric Types  16 bits = 2 bytes can have any value from 16 bits = 2 bytes can have any value from 0000 0000 0000 0000– 1111 1111 1111 1111 0000 0000 0000 0000– 1111 1111 1111 1111 or 0 – 65,535. (Shortcut: 65,535 = 2 or 0 – 65,535. (Shortcut: 65,535 = 216 16 -1) -1) • Was used for a long time for integer values Was used for a long time for integer values • If used to store negative integers, could only store If used to store negative integers, could only store up to +/- 32,768 (approx) why? up to +/- 32,768 (approx) why?  32-bit integers now more common 32-bit integers now more common • Ever heard of 32-bit operating system? Means that Ever heard of 32-bit operating system? Means that main data types used are 32-bit main data types used are 32-bit  Amount of memory given to each type Amount of memory given to each type dependent on the machine and operating dependent on the machine and operating system system
  • 101. Type Sizes Type Sizes  Many different types in C++ (more to Many different types in C++ (more to come) come) • char: a single character char: a single character  Often 1 byte, 128 values Often 1 byte, 128 values • int: an integer value int: an integer value  Often 32 bits/4 bytes, 4 billion values Often 32 bits/4 bytes, 4 billion values • float: a floating-point number float: a floating-point number  Often 4 bytes Often 4 bytes • double: a double-precision floating-point double: a double-precision floating-point number number  Double the size of a float, often 64 bits or 8 bytes Double the size of a float, often 64 bits or 8 bytes
  • 102. Operators Operators  Arithmetic: + - * / % -(unary e.g. - Arithmetic: + - * / % -(unary e.g. - (x+y)) (x+y))  Increment/decrement: ++ -- Increment/decrement: ++ --  Relational: > >= < <= Relational: > >= < <=  Equality: == != Equality: == !=  Assignment: = += -= *= Assignment: = += -= *=  Logical: || && Logical: || &&  Reference/Dereference: & * -- for later Reference/Dereference: & * -- for later
  • 103. Expressions Expressions  Built up out of constant values (e.g., Built up out of constant values (e.g., 5 or 10.7), variables (x, y, etc) and 5 or 10.7), variables (x, y, etc) and operators operators  Number and type of variables has to Number and type of variables has to match what the operator expects – match what the operator expects – like a function like a function  Some exceptions when working with Some exceptions when working with numerical variables! numerical variables!
  • 104. Type conversions (coercion) Type conversions (coercion)  Some types can automatically be Some types can automatically be converted to others converted to others  int, float, double can often be treated the int, float, double can often be treated the same for calculation purposes same for calculation purposes • int values will be converted up into floats for int values will be converted up into floats for calculations. calculations.  But major differences between integer and But major differences between integer and floating-point arithmetic! floating-point arithmetic! • Fractions just dropped in integer arithmetic Fractions just dropped in integer arithmetic • Use modulus (%) operator to get remainders Use modulus (%) operator to get remainders • Integer much faster to perform Integer much faster to perform
  • 105. Expression Examples Expression Examples  See/code examplesin.cpp See/code examplesin.cpp  Many examples follow Many examples follow  x, y, z are integer variables x, y, z are integer variables  f and d are float variables f and d are float variables
  • 106. Arithmetic Arithmetic y = 5; y = 5; // y is now 5 // y is now 5 x = y + 3; // x is now 8 x = y + 3; // x is now 8 f = 2 * 4; // f is now 8.0 f = 2 * 4; // f is now 8.0 g = f / 3.0; // g is now 2.6…67 g = f / 3.0; // g is now 2.6…67 y = x / 3; // y is now 2 y = x / 3; // y is now 2 z = x % 3; // z is now 2 z = x % 3; // z is now 2 See ExamplesinCpp.cpp See ExamplesinCpp.cpp
  • 107. Increment/Decrement Increment/Decrement x = 5; x = 5; f = 2.5; f = 2.5; x++; x++; // x is now 6 // x is now 6 f--; f--; // f is now 1.5 // f is now 1.5 ++f; ++f; // f is now 2.5 // f is now 2.5 --x; --x; // x is now 5 // x is now 5 y = ++x – 2; // x = 6, y = 2 y = ++x – 2; // x = 6, y = 2 g = f-- + 2; // f = 1.5, g = 4.5! g = f-- + 2; // f = 1.5, g = 4.5! //see //see ExamplesinCpp2.cpp ExamplesinCpp2.cpp
  • 108. Relational Relational x = 5; x = 5; f = 6.0; f = 6.0; y = (x > f); // y = 0 (false) y = (x > f); // y = 0 (false) g = (x <= f); // g = 1 (true) g = (x <= f); // g = 1 (true) // usually used in conditionals // usually used in conditionals if (x > f) { if (x > f) { // do something // do something } } See conditional1.cpp See conditional1.cpp
  • 109. Relational conditions:Common Relational conditions:Common errors errors if (x = 5); if (x = 5); if ((x=5)&&(y=7)) if ((x=5)&&(y=7)) if ((x>0)&&(x<=)) if ((x>0)&&(x<=)) Must use if (x==4) Must use if (x==4) Or if (y!=10) Or if (y!=10)
  • 110. Equality & Assignment Equality & Assignment x = 5; // sets value of x to 5 x = 5; // sets value of x to 5 if (x == 5) // returns true/false if (x == 5) // returns true/false x += 3; x += 3; // x is now 8 // x is now 8 if (x != 5) { if (x != 5) { cout << “x is not 5n”; cout << “x is not 5n”; } } x *= 2; // x is now 16 x *= 2; // x is now 16 See conditional2.cpp See conditional2.cpp
  • 111. Logical Logical x = 5; x = 5; y = 2; y = 2; if ( (x >= 5) && (y < 2) ) { if ( (x >= 5) && (y < 2) ) { cout << “Both true.n”; cout << “Both true.n”; } else if ( (x >= 5) || (y < 2) ) { } else if ( (x >= 5) || (y < 2) ) { cout << “One is true.n”; cout << “One is true.n”; } else { } else { cout << “Both false!n”; cout << “Both false!n”; } }
  • 112. Programming in C++ Programming in C++ Lecture 2c Lecture 2c Elements of a Program Elements of a Program
  • 113. Overview of Lecture Overview of Lecture  Overview of Computers & Programming Overview of Computers & Programming • Assembly language vs. C/C++ Assembly language vs. C/C++ • Compiled vs. interpreted languages Compiled vs. interpreted languages • Procedural programming vs. Object-oriented Procedural programming vs. Object-oriented programming programming  Elements of a Program Elements of a Program • Statements Statements • Functions Functions • Variables Variables  Types Types • Computer memory & binary arithmetic Computer memory & binary arithmetic • C++ types C++ types
  • 114. What Is A Computer? What Is A Computer?  CPU/processor just does a few basic CPU/processor just does a few basic things: things: • Arithmetic unit (adds, subtracts, multiplies, Arithmetic unit (adds, subtracts, multiplies, divides), sometimes called the ALU the divides), sometimes called the ALU the Arithmetic Arithmetic and and Logic Unit Logic Unit • Memory control (loads and stores integer and Memory control (loads and stores integer and floating-point values from memory) floating-point values from memory) • Think of address and data buses etc Think of address and data buses etc  Everything a computer does is Everything a computer does is accomplished with these simple operations accomplished with these simple operations
  • 115. Assembly Language Assembly Language  Computer processors each have their own Computer processors each have their own built-in assembly language, this is code that built-in assembly language, this is code that the CPU understands the CPU understands • E.g., Intel CPUs have their own language that differs E.g., Intel CPUs have their own language that differs from the language of Motorola Power PC CPUs from the language of Motorola Power PC CPUs  These have a limited range of commands, These have a limited range of commands, LOAD, ADD, SUB, MOV etc LOAD, ADD, SUB, MOV etc  Each command typically does very little Each command typically does very little • Arithmetic commands, load/store from memory Arithmetic commands, load/store from memory  Code not totally unreadable, but close, Code not totally unreadable, but close, fortunately we do not generally write in fortunately we do not generally write in assembly language any more, but it is good to assembly language any more, but it is good to know about it. know about it.
  • 116. C++ versus Assembly C++ versus Assembly  Here is some simple C++ code: Here is some simple C++ code:  assume x, y and z have been defined assume x, y and z have been defined as integers as integers  || means the logical or operator || means the logical or operator x = y + 2; x = y + 2; if ( (x > 0) || ( (y-x) <= z) ) if ( (x > 0) || ( (y-x) <= z) ) x = y + z; x = y + z;  We will also see three similar lines of code in We will also see three similar lines of code in Intel x86 assembly language in a moment... Intel x86 assembly language in a moment...
  • 117. Truth table for Logical or Truth table for Logical or A A B B A || B A || B False False False False False False True True False False True True False False True True True True True True True True True True
  • 118. Truth table for Logical or Truth table for Logical or continued continued The The predicate A predicate A is: It is is: It is Tuesday Tuesday The The predicate B predicate B is: It is is: It is raining raining A || B A || B False False False False False False True True False False True True False False True True True True True True True True True True
  • 119. Truth table for And (&&) Truth table for And (&&) A A B B A && B A && B False False False False False False True True False False False False False False True True False False True True True True true true
  • 120. MOV AX, y // put y into AX MOV BX, x // put x into BX MOV CX, z // put z into CX ADD AX, x // add to the contents of AX the value // x and store in AX CMP AX, 0 // check whether the contents of AX=0 MOV DX, BX //move contents of BX into DX SUB DX, AX //subtract the value of contents of //AX and place in DX CMP DX, CX //compare contents of CX and DX With more code here . . . Note it is difficult to understand and quite tedious
  • 121. The C++ Programming Language The C++ Programming Language  C++ is a higher-level language C++ is a higher-level language compared to assembly compared to assembly • Much more human-readable Much more human-readable • Fewer lines of code for same task Fewer lines of code for same task  C is a lower-level language compared to C is a lower-level language compared to others (like C++ and Java which are others (like C++ and Java which are Object Oriented Programming Object Oriented Programming languages) languages) • Direct control over memory allocation and Direct control over memory allocation and cleanup (as we will see) cleanup (as we will see)
  • 122. Compiled vs. Interpreted Compiled vs. Interpreted  For a program to run, the source code For a program to run, the source code must be translated into the assembly must be translated into the assembly language of the machine the program will language of the machine the program will run on. run on. • Compiled language: the source code is Compiled language: the source code is translated once and the executable form is run. translated once and the executable form is run. (C++ and Pascal) (C++ and Pascal) • Interpreted language: an interpreter runs each Interpreted language: an interpreter runs each time the program is started, and it does the time the program is started, and it does the translation on-the-fly (Visual Basic, Perl, other translation on-the-fly (Visual Basic, Perl, other scripting languages and Java). scripting languages and Java). • Java is compiled and interpreted requires a JVM Java is compiled and interpreted requires a JVM  JVM: Java Virtual Machine JVM: Java Virtual Machine
  • 123. Procedural vs. Object-Oriented Procedural vs. Object-Oriented  Procedural Programming Procedural Programming • A program viewed as a series of instructions to A program viewed as a series of instructions to the computer the computer • Instructions are organized into functions and Instructions are organized into functions and libraries of functions libraries of functions  Object-Oriented Programming Object-Oriented Programming • A program viewed as a set of objects that A program viewed as a set of objects that interact with each other interact with each other • An object encapsulates (hides and binds) An object encapsulates (hides and binds) functions with the data that the object’s functions with the data that the object’s functions operate on functions operate on
  • 124. Procedural vs. Object-Oriented Procedural vs. Object-Oriented  OOP good for complex systems – nice to OOP good for complex systems – nice to break down into small independent objects break down into small independent objects  Procedural perhaps a bit more intuitive, Procedural perhaps a bit more intuitive, especially for beginners (where we will especially for beginners (where we will commence) commence)  C is a procedural language, no OO C is a procedural language, no OO capabilities capabilities  Java and C++ are Object-Oriented Java and C++ are Object-Oriented Languages, Java is pure Object Oriented Languages, Java is pure Object Oriented i.e. everything is an object in Java. i.e. everything is an object in Java.
  • 125. Explanation of OOP and Explanation of OOP and Procedural Programming Procedural Programming  Perhaps one of the best definitions of the Perhaps one of the best definitions of the difference between these two paradigms is difference between these two paradigms is as follows: as follows:  Consider a chair: a Consider a chair: a procedural procedural programmer programmer is interested in in the wood, is interested in in the wood, hammer, screws, screw driver etc i.e., hammer, screws, screw driver etc i.e., everything that went into making the everything that went into making the chair, however the chair, however the Object Oriented Object Oriented Programmer Programmer would be interested only in would be interested only in the chair i.e. the finished article the chair i.e. the finished article
  • 126. Procedural Programming Procedural Programming  Program is a set of Program is a set of sequential sequential steps to be steps to be executed by the computer, one after executed by the computer, one after another, this is the another, this is the Sequential Paradigm Sequential Paradigm  However we do However we do Not Not necessarily run the necessarily run the same steps every time the program runs, same steps every time the program runs, can have can have selection selection/decisions /decisions • May want to skip steps under certain conditions May want to skip steps under certain conditions (selection) (selection) • May want to repeat steps under certain May want to repeat steps under certain conditions ( conditions (iteration iteration) ) • May need to save some information to use later May need to save some information to use later in the program (when computing a sum) in the program (when computing a sum)
  • 127. Programming Paradigms Programming Paradigms  There are three essential programming There are three essential programming paradigms (the word paradigm is from the Greek paradigms (the word paradigm is from the Greek word meaning example) word meaning example)  Sequential: Sequential: code is executed one after the after code is executed one after the after top-down: top-down:Sequential Paradigm Sequential Paradigm  Selection Selection/decisions. Achieved in C/C++ using /decisions. Achieved in C/C++ using the the if, if-else if, if-else or or switch-case switch-case statements to be met statements to be met in later lectures. in later lectures.  Iteration Iteration:To be achieved in the C++/Java :To be achieved in the C++/Java languages using the languages using the for for loop loop, while , while loop loop or or the the do-while do-while loop, more in later lectures loop, more in later lectures
  • 128. Elements of a Program Elements of a Program  Individual steps/commands to the computer Individual steps/commands to the computer • These are called Statements, a semicolon delimits a These are called Statements, a semicolon delimits a valid C++ statement. valid C++ statement.  Technique to organize code so it is easy to debug, fix, and Technique to organize code so it is easy to debug, fix, and maintain. maintain. Code and fix Code and fix is the most common way that one is the most common way that one programs, but perhaps the worst, SSADM is a better way. programs, but perhaps the worst, SSADM is a better way. SSADM: Structured, System Analysis and Design SSADM: Structured, System Analysis and Design Methodology Methodology • Functions Functions  Way to save information that may change each time the Way to save information that may change each time the program runs program runs • Variables vary in a program Variables vary in a program  If we want to change what steps get executed: If we want to change what steps get executed: • Control flow – topic coming soon Control flow – topic coming soon
  • 129. Code and Fix Code and Fix  Write some code Write some code  Fix problems just created Fix problems just created • Problems Problems • Software complete after n fixes Software complete after n fixes • Subsequent fixes are very expensive (time and Subsequent fixes are very expensive (time and resources) resources) • Previous fixes fail to work Previous fixes fail to work • Poor fit to users’ needs (reflects programmers Poor fit to users’ needs (reflects programmers view rather that that of the clients) view rather that that of the clients)
  • 131. The Waterfall Model The Waterfall Model  Criticisms Criticisms • Requirements must be fixed before system is designed Requirements must be fixed before system is designed • Design and code produce inconsistencies that are Design and code produce inconsistencies that are difficult to fix difficult to fix • Problems are not discovered until the Testing stage Problems are not discovered until the Testing stage • System performance can not be tested until near System performance can not be tested until near completion completion • System underperformance is difficult to fix at this stage System underperformance is difficult to fix at this stage  Problems Problems • Ageing technique Ageing technique • Less effective for new software paradigms of OOD (UML) Less effective for new software paradigms of OOD (UML) • Costs can spiral out of control Costs can spiral out of control • Projects can and usually do overrun (inefficient) Projects can and usually do overrun (inefficient)
  • 133. Functions Functions  Already have seen the main() Already have seen the main() function function  Functions are used to group Functions are used to group individual statements that together individual statements that together accomplish a single larger task accomplish a single larger task  E.g., the main() function contains E.g., the main() function contains many statements that together many statements that together accomplish the task of printing a accomplish the task of printing a message to the screen or file message to the screen or file
  • 134. Simple Example Simple Example #include <iostream> #include <iostream> using namespace std; using namespace std; void printHello() {cout<< “Hellon”}; void printHello() {cout<< “Hellon”}; void printBye() {cout<<“Byen”}; void printBye() {cout<<“Byen”}; int main() int main() { { printHello(); // this is a call to the printHello(); // this is a call to the // function printHello() // function printHello() printBye(); // this is a call to the printBye(); // this is a call to the // function prinBye // function prinBye return 0; return 0; } } See program fuctions1.cpp See program fuctions1.cpp See program fuctions1b.cpp (//does not compile) See program fuctions1b.cpp (//does not compile) as //there are no function prototypes as //there are no function prototypes
  • 135. Function Elements Function Elements  Return-type Return-type • Specifies what kind of information the function will return Specifies what kind of information the function will return • void void means nothing is returned (called a procedure in other means nothing is returned (called a procedure in other languages) languages)  Name Name • Must be unique within the program Must be unique within the program • It is used to call (invoke) the function – i.e., to cause the functio It is used to call (invoke) the function – i.e., to cause the function statements to be executed statements to be executed  Arguments Arguments • Optional information that is used by the function Optional information that is used by the function  Body Body • The actual statements within the function groups The actual statements within the function groups
  • 136. Variables Variables  Used to store information within the Used to store information within the program program  Values can change as the program Values can change as the program runs (i.e., are variable) runs (i.e., are variable) • Obtained through calculations Obtained through calculations • From input From input • From function results From function results
  • 137. Simple Examples Simple Examples #include <iostream> #include <iostream> using namespace std; using namespace std; int main() int main() { { int x = 5;//obsolete here as not used int x = 5;//obsolete here as not used char letter = ‘g’; char letter = ‘g’; cout <<“Please enter a character”; cout <<“Please enter a character”; cin >> letter; cin >> letter; cout << “the character input was “ << letter << endl; cout << “the character input was “ << letter << endl; return 0; return 0; } } //see letter.cpp //see letter.cpp
  • 138. Variable Elements Variable Elements  Type Type • Indicates what kind of information can be Indicates what kind of information can be stored in the variable stored in the variable  Name Name • Must be unique within a given function Must be unique within a given function  Except for special Except for special global variables global variables, which must , which must have unique names within the program. Global have unique names within the program. Global variables are not considered good programming variables are not considered good programming practice. Why? practice. Why? • Used to refer to a variable throughout the Used to refer to a variable throughout the function function  Value Value • Can be set in many different ways Can be set in many different ways
  • 139. Declarations vs. Definitions Declarations vs. Definitions  Both functions and variables MUST be Both functions and variables MUST be declared before they can be used declared before they can be used  Declaration includes just: Declaration includes just:  Type Type  Name Name  Arguments (for functions) Arguments (for functions)  Definition can come later! Definition can come later! • For variables: value can be assigned later (as For variables: value can be assigned later (as long as it is before its first use or garbage will long as it is before its first use or garbage will be used) be used) • For functions: body of function can be added For functions: body of function can be added later later
  • 140. Complex Example Complex Example  See the functions1.cpp, function2.cpp and See the functions1.cpp, function2.cpp and function3.cpp example code function3.cpp example code  Variable declaration: Variable declaration: • int x; char input[1000]; int x; char input[1000];  Function declaration (prototype): Function declaration (prototype): • void printHello(); void printHello();  Function definition Function definition • void printHello() void printHello() { { cout << “Hello”<< endl; cout << “Hello”<< endl; } }
  • 141. Important Rules Important Rules  All variables and functions must be All variables and functions must be declared in the function/file where declared in the function/file where they are going to be used BEFORE they are going to be used BEFORE they are used. they are used.  All variables must be initialized to All variables must be initialized to some starting value before being some starting value before being used in calculations or being printed used in calculations or being printed out, otherwise we get rubbish out, otherwise we get rubbish
  • 142. Statements Statements  A statement is a single line of code A statement is a single line of code  Can be: Can be: • Variable or function declarations Variable or function declarations • Arithmetic operations Arithmetic operations  x = 5+3; x = 5+3; • Function calls Function calls  Calcsum(x,y); Calcsum(x,y); • Control flow commands Control flow commands • More to be seen… More to be seen…
  • 143. Types Types  “ “Type” in C++ refers to the kind of Type” in C++ refers to the kind of data or information data or information  Functions have return types Functions have return types  Arguments to functions each have Arguments to functions each have their own type their own type  Variables have types Variables have types
  • 144. Why Type? Why Type?  Why do we have to specify types of Why do we have to specify types of variables, functions, arguments? variables, functions, arguments?  Has to do with computer memory Has to do with computer memory  Different kinds of data require different Different kinds of data require different amounts of memory to store amounts of memory to store • A single character can have only one of 128 A single character can have only one of 128 values (a-z,A-Z,0-9,punctuation, some others) values (a-z,A-Z,0-9,punctuation, some others) • An integer in mathematics can have an infinite An integer in mathematics can have an infinite number of values, limited to ~65,000 values on number of values, limited to ~65,000 values on a computer a computer • Therefore, more memory needed to store an Therefore, more memory needed to store an integer than a character integer than a character
  • 145. Computer Memory Computer Memory  Memory in computers made up of Memory in computers made up of transistors transistors  Transistor: just a switch that can be either Transistor: just a switch that can be either on or off on or off  “ “on” state corresponds to the value 1, on” state corresponds to the value 1, “off” state corresponds to the value 0 “off” state corresponds to the value 0  Everything in memory has to be made up Everything in memory has to be made up of 0s and 1s – i.e., has to be stored as a of 0s and 1s – i.e., has to be stored as a number in base 2 (binary) number in base 2 (binary)  Important to understand different bases Important to understand different bases
  • 146. Numeric Types Numeric Types  16 bits = 2 bytes can have any value from 16 bits = 2 bytes can have any value from 0000 0000 0000 0000–1111 1111 1111 1111 0000 0000 0000 0000–1111 1111 1111 1111 or 0 – 65,535. (Shortcut: 65,535 = 2 or 0 – 65,535. (Shortcut: 65,535 = 216 16 -1) -1) • Was used for a long time for integer values Was used for a long time for integer values • If used to store negative integers, could only store If used to store negative integers, could only store up to +/- 32,768 (approx) up to +/- 32,768 (approx)  32-bit integers now more common 32-bit integers now more common • Ever heard of 32-bit operating system? Means that Ever heard of 32-bit operating system? Means that main data types used are 32-bit main data types used are 32-bit  Amount of memory given to each type Amount of memory given to each type dependent on the machine and operating dependent on the machine and operating system system
  • 147. Next Time Next Time  More on types More on types  Operators Operators • Arithmetic: + - * / Arithmetic: + - * / • Assignment: = Assignment: = • Increment/Decrement: ++ -- Increment/Decrement: ++ --  Expressions/Statements Expressions/Statements • Declarations Declarations • Assignments Assignments • Other one-line operations Other one-line operations  More program examples More program examples
  • 148. Casting Casting  int i = 16; int i = 16;  double d; double d;  d = i; // will give, d = 16.0 d = i; // will give, d = 16.0  d = 10.3; d = 10.3;  i = d; // will give i = 10 i = d; // will give i = 10  cout << 2 * 3.4 + 7 / 2; // 6.8 + 3 = cout << 2 * 3.4 + 7 / 2; // 6.8 + 3 = 9.8 (a //double), note 7/2 is evaluated as 9.8 (a //double), note 7/2 is evaluated as an integer an integer  //ignoring the remainder. //ignoring the remainder.  //see casting.cpp //see casting.cpp
  • 149. Conditional Statements Conditional Statements  Conditions take the form: Conditions take the form:  if (condition) if (condition)  {statements executed if the {statements executed if the condition is true } condition is true }  else else  {statements executed if the {statements executed if the condition is false } condition is false }
  • 150. Conditions Conditions  Execution resumes here with the “if Execution resumes here with the “if statement” having been executed. statement” having been executed.  Note that the first line does not end with a Note that the first line does not end with a semicolon. semicolon.  The curly brackets are necessary only if The curly brackets are necessary only if there are several statements. there are several statements.  If you are only executing one statement If you are only executing one statement as a result of the condition, you can place as a result of the condition, you can place it on the same line or the next. it on the same line or the next.  For example: For example:
  • 152. Relational operators. Relational operators.  Relational operators allow you to compare Relational operators allow you to compare two or more items of data in an two or more items of data in an expression. expression.  = = is equal to (comparison operator) = = is equal to (comparison operator)  != is not equal to != is not equal to  > is greater than > is greater than  < is less than < is less than  >= is greater than or equal to >= is greater than or equal to  <= is less than or equal to <= is less than or equal to
  • 153. Relations Relations  The mathematical operators < and > The mathematical operators < and > can be used with strings to can be used with strings to determine alphabetical order. determine alphabetical order. For example: For example:  ("abc" < "def") ("abc" < "def")  this is also true this is also true  ("d">"b") ("d">"b")
  • 154. Relations Relations  When dealing with non-alphanumeric characters When dealing with non-alphanumeric characters (i.e. numbers and letters), you need to know (i.e. numbers and letters), you need to know which character set, or code page, you are using which character set, or code page, you are using before you can determine the alphabetical order before you can determine the alphabetical order of a set of strings. of a set of strings.  The most common code page is the The most common code page is the ASCII ASCII (American Standard Code for Information (American Standard Code for Information Exchange). The EBDIC (Extended Binary Decimal Exchange). The EBDIC (Extended Binary Decimal Interchange Code) is used in large IBM Interchange Code) is used in large IBM mainframes. mainframes.  The first 33 characters of the ASCII character set The first 33 characters of the ASCII character set are non-printable control codes (CTRL, carriage are non-printable control codes (CTRL, carriage return etc). return etc).
  • 155. Common pitfall with Boolean Common pitfall with Boolean expressions. expressions. It is easy to write: It is easy to write:  if (x or y > 0) if (x or y > 0)  rather than rather than  if (x > 0 or y > 0) // using Borland if (x > 0 or y > 0) // using Borland //C++ //C++  if ((x>0)||(y>0)) if ((x>0)||(y>0))
  • 156. Explanation Explanation  which are both correct code but which are both correct code but logically different. logically different.  The first expression literally means The first expression literally means "if x is true or y is greater than "if x is true or y is greater than zero", and x is always true for non- zero", and x is always true for non- zero values of x. zero values of x.
  • 157. Lazy evaluation. Lazy evaluation.  C++ compilers implement so-called lazy C++ compilers implement so-called lazy evaluation, in which Boolean expressions evaluation, in which Boolean expressions are evaluated only until their result is are evaluated only until their result is clear. clear.  For example, false For example, false and and anything is always anything is always false, true false, true or or anything is always true. anything is always true.  This is a useful technique when you want This is a useful technique when you want to avoid making calculations that might to avoid making calculations that might cause a crash. For example: cause a crash. For example:
  • 158. Lazy evaluation Lazy evaluation  if (second > 0 && first/second > if (second > 0 && first/second > 1.2) // eliminate the possibility of 1.2) // eliminate the possibility of dividing by //zero dividing by //zero  {... {...  } }
  • 159. Lazy evaluation Lazy evaluation  In this case if second is indeed zero, In this case if second is indeed zero, then the potentially fatal calculation then the potentially fatal calculation of first / second is never executed. of first / second is never executed.
  • 160. Boolean variables. Boolean variables.  Some conditions are used several times in Some conditions are used several times in the course of a calculation, for example, the course of a calculation, for example, whether an individual is entitled to a whether an individual is entitled to a discount. discount.  Rather than re-evaluating the condition Rather than re-evaluating the condition you can store it in the form of a Boolean you can store it in the form of a Boolean variable. Hence: variable. Hence:  bool half_price = day = = "Monday" !! bool half_price = day = = "Monday" !! age < 15 !! row >= "w"; age < 15 !! row >= "w";
  • 161. Conditional operator, ? (the Conditional operator, ? (the operator is the ?) operator is the ?)  It is possible to abbreviate some It is possible to abbreviate some condition statements using the ? condition statements using the ? operator as follows: operator as follows:  conditional_expression ? conditional_expression ? expression_1 : expression_2 expression_1 : expression_2
  • 162. Conditional operator Conditional operator  in which, if conditional_expression is in which, if conditional_expression is true, expression_1 is performed, true, expression_1 is performed, otherwise expression_2 is carried otherwise expression_2 is carried out. out.  Note that the expressions must be of Note that the expressions must be of the same type. the same type.  You can use the conditional operator You can use the conditional operator in a straightforward assignment, or in a straightforward assignment, or within a more complex statement: within a more complex statement:
  • 163. Conditional operator Conditional operator  max = x > y ? x : y; max = x > y ? x : y;  //Assigns to max the larger of x and //Assigns to max the larger of x and y y  cout << (s.length() < t.length() ? s : cout << (s.length() < t.length() ? s : t); // prints the shorter of s and t t); // prints the shorter of s and t
  • 164. The switch statement. (case The switch statement. (case statement of Pascal) statement of Pascal)  This switch statement allows you to This switch statement allows you to control the flow of your program by control the flow of your program by specifying a number of different specifying a number of different cases or conditions, rather than cases or conditions, rather than simply true or false. simply true or false.  See switch1.cpp See switch1.cpp
  • 165. Switch Switch  The switch keyword works by entering program flow at the The switch keyword works by entering program flow at the statement whose case matches the expression. All subsequent statement whose case matches the expression. All subsequent statements are executed as well, so that if expression were 3 in statements are executed as well, so that if expression were 3 in this example, the output would be 363invalid value. This has been this example, the output would be 363invalid value. This has been obtained by entering the code at the line obtained by entering the code at the line  case 3: cout << x * 3; // then multiplying 12 (i.e. x) by 3 giving case 3: cout << x * 3; // then multiplying 12 (i.e. x) by 3 giving the 36, the 36,  then proceeding to the line then proceeding to the line  case 4: cout << x / 4; // then dividing 12 by 4 giving the 3, case 4: cout << x / 4; // then dividing 12 by 4 giving the 3,  then proceeding to the final line and outputting the string Invalid then proceeding to the final line and outputting the string Invalid Output Output  You can avoid this state of affairs by placing a You can avoid this state of affairs by placing a break break keyword at keyword at the end of each case statement, to go to the statement after the the end of each case statement, to go to the statement after the curly brackets. switch statements are of limited use: expression curly brackets. switch statements are of limited use: expression must always evaluate to a literal and you can have only one value must always evaluate to a literal and you can have only one value per case. per case.