CS1003: Programming in C

Download Report

Transcript CS1003: Programming in C

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