Transcript Basics2

C++ Basics 2
More on basic data types
Declarations
Simple mathematical Operators
Basic programming techniques
Data Types
Atomic data types

Integral, Floating Point, Character
More advanced data types
Address
 Structured

Variables
A place to store information
contents of a location in memory
has an address in RAM
uses a certain number of bytes
size depends upon the data type
Identifiers (names of things)
Examples:
x
num1
num2
name
row
c237
index
tax_rate
Not valid:
1num
newPos
bye[a] tax-rate
newpos
tax rate
(beware of this!)
Declaration Statement
A declaration statement associates an
identifier with a data object, a function, or a
data type so that the programmer can refer
to that item by name.
Declaration Statement
Syntax: data-type variable name;
Examples:
int my_age;
int count;
float deposit;
float amount;
float totalpay;
double balance;
char answer2;
Multiple Declarations
Syntax:
data-type var1, var2, var3;
Examples:
int my_age;
int count;
Note ,
float deposit, amount, totalpay;
double balance;
char answer2 ;
Constants
Literal
typed directly into the program as needed
ex. y = 23.4
pi = 3.1416
can change
Symbolic (Named)
similar to a variable, but cannot be
changed after it is initialized
ex. const int class_size = 87;
const double PI = 3.1416;
can NOT
change
Constants
Syntax
 const
type VAR = value;
 const int Imax = 1000;
 const char BLANK = ‘ ‘;
Sample Program
#include<iostream>
using namespace std;
declarations
void main(void) {
float t;
float length;
const float g = 9.8;
constants const float PI = 3.1416;
t = 1.0;
length = g*(t/(2*PI))*(t/(2*PI));
cout << “length of pendulum = “<< length;
}
Special Data Types Address Data
Recall all data stored in RAM at a specific
address.
We can refer to this address using a name e.g.
length rather than by referring to the actual
address.
We can however access addresses in memory
using special variables.


Pointers(used later in the course for dynamic memory
allocation)
References (used later in the semester for modular
programming with functions)
Special data types – structured data
We can create special data types to represent things in the
world.
For example we may want to represent a student record,
comprising of

Name, ID, grade
We want to be able to refer to an individual student and
know that they have associated attributes or fields.
We can do this using Structured data types
array
struct
union
class
Operators
An operator is a symbol that causes the
compiler to take an action.
Operators operate on data
Different data types allow different operations

E.g. multiplication division addition and
subtraction are legal on numerical data; they are
not legitimate operations for characters
*
Arithmetic Operators
addition
subtraction
multiplication
division
modulus
+
¾
*
/
%
Arithmetic Operators
Syntax
operand operator operand
Example
7
34
92
345
86
+
—
*
/
%
15
189
31
6.02
3
*
What is the Modulus operator
The modulus operator yields the remainder
of integer division.
4
3 12
12
0
12/3
14/3
12%3
14%3
4
3 14
12
2
**
Modulus
Examples.
18
17
24
4
% 4
% 3
% 6
% 18
is 2
is 2
is 0
is 4
12 % 2.5 error
13
35
24
0
%
%
%
%
4
47
4
7
is
is
is
is
1
35
0
0
6.0 % 6 error
***
A Glimpse of Operator
Overloading
Operator overload
Using the same symbol for more than one
operation.
type int / type int
9/5
operator performs
int division
type double / type double
9.0 / 5.0
operator performs
double division
*
Mixed-Mode Expressions
Operator overload. Same operator will behave
differently depending upon the operands.
Operands of the same type give results of that
type. E.g. int / int -> integer division
In mixed-mode, floating point takes precedence.
e.g. 6 / 10.0 is int / float therefore whole thing
treated as float. The 6 is converted into a float.
Problems with Integer Division
int a, b;
a = 8;
b = 3;
cout << “The result is “ << a / b << endl;
8 / 3 is 2 and not 2.6667
The result must be an integer. The
result is truncated to 2.
Problems with Integer Division
int a, b;
a = 8;
b = 3;
cout << “The result is “ << b / a << endl;
3 / 8 is 0 and not 0.375
The result must be an integer. The
result is truncated to 0.
Basic rules on order of operations
P then M DM then A S from left to right
8 + 3 * 4 is ?
Show associativity with round brackets
to clarify.
( 8 + 3 ) * 4 is 44
8 + ( 3 * 4 ) is 20
Order of Operations
Expression
Value
10 % 3 - 4 / 2
15
-1
5.0 * 2.0 / 4.0 * 2.0
5.0
5.0 * 2.0 / (4.0 * 2.0)
1.25
5.25
10 / 2 * 3
5.0 + 2.0 / (4.0 * 2.0)
Evaluation Trees
10 % 3 - 4 / 2
10 / 2 * 3
1
1
2
2
3
5.0 * 2.0 / 4.0 * 2.0
5 * 2 / (4.0 * 2.0)
2
1
1
2
3
3
**
Beware!
C++ requires the asterisk to indicate
multiplication.
valid
5*(8+3)
(x-y)*(x+y)
invalid
5(8+3)
(x-y)(x+y)
Assignment Operator =
Subtle difference to the meaning in mathematics.
In mathematics the meaning is like balances with.

So simple equations like x = 5 in maths causes you to
INFER that x is 5, or 2x = x + 3 causes you to infer that
x = 3.
The assignment operator (=) causes the operand
on the left to take on the value to the right side of
the statement.
The compiler is instructed to store the value on
the right in the address associated with the
variable on the left
*
Assignments
This operator assigns from right to left.
valid
invalid
x=5
5= x
picard = 6.02
vg_grd = 87.5
Assignment Statement
Syntax:
variable = expression;
Examples:
quiz1score = 14;
balance = balance + deposit;
Do NOT use the word equals here. Use
“assigned to” or “takes the value of”.
Assignment Statement in
declarations
Examples:
int myage = 33;
int width = 10, length;
double ex1 = 85, ex2 = 73, ex3 = 82;
char ans, key = ‘Q’, ch;
Why do this?



Remember that in order to use a variable we must
declare it first.
We must also make sure that a variable has a sensible
value stored before it is used.
Programmers often like to put in “default” sensible
values when they declare variables
Recall Storage Locations
int deposit, balance;
deposit = 234;
balance = 1000;
1. Deposit and balance are given memory
addresses.
2. 234 is put into the memory address for deposit.
3. 1000 is put into the memory address for balance.
Storage Locations
int deposit, balance;
deposit
?
?
balance
?
?
4 bytes of storage 4 bytes of storage
Rubbish
*
Storage Locations
deposit = 234;
balance = 1000;
deposit
234
balance
1000
Storage Locations
int deposit, balance;
deposit
= 234;
balance = 1000;
balance = balance + deposit;
Add the contents of the deposit address to
the contents of the balance address. Store
the result at the balance address.
Storage Locations
balance
=
deposit
234
balance + deposit;
balance
12 3 4
98765
The addition “balance + deposit” is done somewhere else,
the result of the calculations is copied into the address
associated with balance
Basic Programming Techniques 1
Accumulation
Adding up lists of numbers, doing running
totals.
 We need a variable to store the running total
e.g. sum
 We need to add to whatever has been
accumulated in sum.
 We get lines like

sum = sum + new_value;
Example
Suppose we want to accumulate numbers 96, 70,
85 and 60.
Need an accumulator variable sum say.
Need to initialise it

sum = 0;
Then
//sum now holds 0
accumulate the numbers.
sum
= sum + 96; //sum now holds 96
sum
= sum + 70; //sum now holds 166
sum
= sum + 85; //sum now holds 251
sum
= sum + 60; //sum now holds 311
Basic Programming Techniques 2
Counting
 Very
similar to accumulating.
 Need a counter variable.
 Normally initialised to 0;
 Normally add one on each time.E.g.
 count
= 0;
 count = count + 1;
 Can
count in steps of more than one, e.g.
 count
= count + 2;
Accumulating/Counting
Down
It is also common for counting and accumulating
to be done in reverse.


Start an accumulator not with 0
Keep subtracting numbers




Sum = 100;
Sum = sum – 10;
Sum = sum – 10;
// sum holds 0
// sum now holds 90
// sum now holds 80
Count downs



start = 10;
start = start – 1;
Etc.
//start = 10
//start = 9
Increment/Decrement operators
Counting by adding 1 (incrementing) so common
C++ has a special operator for adding 1;

count++; // same as count = count + 1;
Note there is a decrement operator for
subtracting 1

count--; // same as count = count – 1;
Example: enter a sequence of numbers from
the keyboard and find the average.
Defining diagram
Inputs
Processes
Outputs
newnumber
Initialise accumulator (sum)
Initialise counter (count)
Repeat
prompt for a number
enter a number
increment counter
accumulate number
End repeat
Calculate average = sum/count
Display average
Average
Test data
10 numbers 1-10 should add up to 55
therefore average should be 5.5
PDL Design
Initialise accumulator (sum)
Initialise counter (count)
do
prompt for a number
enter a number
increment counter
accumulate number
While we have more data ??


How do we do this in C++
Use sentinel or prompt for more data
Calculate average = sum/count
Display average
Program (see demo)