COMPUTER
PROGRAMMING
Lecture 02
(Data Types and Operators)
Dr. Muniba Ashfaq
KEYWORDS
Keywords (also called reserved words)
Are used by the C++ language
Must be used as they are defined in
the programming language
Cannot be used as identifiers
Dr. Muniba Ashfaq
C++ KEY WORDS
C ++ Ke yw o rd s
Keywords common to the
C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
Dr. Muniba Ashfaq
VARIABLE & ITS DECLARATION
A variable is a memory address where data
can be stored and changed.
Declaring a variable means specifying both
its name and its data type.
Dr. Muniba Ashfaq
WHAT DOES A
VARIABLE DECLARATION DO?
A declaration tells the compiler to allocate
enough memory to hold a value of this data
type, and to associate the identifier with this
location.
int ageOfDog;
char middleInitial;
float taxRate;
Dr. Muniba Ashfaq
DECLARING VARIABLES (PART 1)
Before use, variables must be declared
Tells the compiler the type of data to store
Examples: int number_of_bars;
double one_weight, total_weight;
int is an abbreviation for integer.
could store 3, 102, 3211, -456, etc.
number_of_bars is of type integer
double
represents numbers with a fractional
component
could store 1.34, 4.0, -345.6, etc.
one_weight and total_weight are both of type double
Dr. Muniba Ashfaq
DECLARING VARIABLES (PART 2)
Two locations for variable declarations
Immediately prior to use At the beginning
int main() int main()
{ {
… int sum;
int sum; …
sum = score1 + score 2; sum = score1 + score2;
… …
return 0;
return 0;
} }
Dr. Muniba Ashfaq
DECLARING VARIABLES (PART 3)
Declaration syntax:
Type_name Variable_1 , Variable_2, . . . ;
Declaration Examples:
double average, m_score, total_score;
double moon_distance;
int age, num_students;
int cars_waiting;
Dr. Muniba Ashfaq
ASSIGNMENT STATEMENTS
An assignment statement changes the value of a
variable
total_weight = one_weight + number_of_bars;
total_weight is set to the sum one_weight + number_of_bars
Assignment statements end with a semi-colon
The single variable to be changed is always on the left
of the assignment operator ‘=‘
On the right of the assignment operator can be
Constants -- age = 21;
Variables -- my_cost = your_cost;
Expressions -- circumference = diameter * 3.14159;
Dr. Muniba Ashfaq
INITIALIZING VARIABLES
Declaring a variable does not give it a value
Giving a variable its first value is initializing the variable
Variables are initialized in assignment statements
double mpg; // declare the variable
mpg = 26.3; // initialize the variable
Declaration and initialization can be combined
using two methods
Method 1
double mpg = 26.3, area = 0.0 , volume;
Method 2
double mpg(26.3), area(0.0), volume;
Dr. Muniba Ashfaq
C++ OBJECTS TYPES
C++ has a large number of fundamental or built-in
object types
The fundamental object types fall into one of three
categories
Integer objects
Floating-point objects
Character objects
Dr. Muniba Ashfaq
INTEGER OBJECT TYPE
The basic integer object type is int
The size of an int depends on the machine and the
compiler
On PCs it is normally 16 or 32 bits
Other integers object types
short: typically uses less bits (often 2 bytes)
long: typically uses more bits (often 4 bytes)
Different types allow programmers to use resources more
efficiently
Standard arithmetic and relational operations are
available for these types
Dr. Muniba Ashfaq
INTEGER CONSTANTS
Integer constants are positive or negative whole numbers
Integer constant forms
Decimal
Digits 0, 1, 2, 3, 4, 5, 6, 7
Octal (base 8)
Digits 0, 1, 2, 3, 4, 5, 6, 7
Hexadecimal (base 16)
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a , b, c, d, e, f, A, B, C, D, E, F
Consider
31 oct and 25 dec
Decimal Constants
Examples
97
40000
50000
23a (illegal)
The type of the constant depends on its size, unless the type is
specified
Dr. Muniba Ashfaq
CHARACTER OBJECT TYPE
Char is for specifying character data
char variable may hold only a single lowercase letter, a single
upper case letter, a single digit, or a single special character
like a $, 7, *, etc.
case sensitive, i.e. a and A are not same.
ASCII is the dominant encoding scheme
Examples
' ' encoded as 32 '+' encoded as 43
'A' encoded as 65 'Z' encoded as 90
'a' encoded as 97 'z' encoded as 122
Dr. Muniba Ashfaq
CHARACTER OBJECT TYPE
Explicit (literal) characters within single quotes
'a','D','*‘
Special characters - delineated by a backslash \
Two character sequences (escape codes)
Some important special escape codes
\t denotes a tab w \n denotes a new line
\\ denotes a backslash w \' denotes a single quote
\" denotes a double quote
'\t' is the explicit tab character, '\n' is the explicit
new line character, and so on
Dr. Muniba Ashfaq
FLOATING-POINT OBJECT
Floating-point object types represent real numbers
Integer part
Fractional part
The number 108.1517 breaks down into the following parts
108 - integer part
1517 - fractional part
C++ provides three floating-point object types
Float
(often 4 bytes) Declares floating point numbers with up to 7 significant digits
Double
long double
(often 10 bytes) Declares floating point numbers with up to 19 significant digits.
Dr. Muniba Ashfaq
Data Type
C++ Variable Covered Range Size Data storage range
int 16 bits (2 byte) -32768 to 32767
short int 16 bits (2 bytes) -32768 to 32767
long int 32 bits (4 bytes) -2147483648 to
2147483647
unsigned int 16 bits (2 bytes) 0 to 65535
unsigned long int 32 bits (4 bytes)
0 to 4294967295
float 32 bits (4 bytes) 3.4x10(-38) to
3.4x10(+38)
long float 64 bits (8 bytes) 1.7x10(-308) to
1.7x10(+308)
double 64 bits (8 bytes) 1.7x10(-308) to
1.7x10(+308)
long double 80 bits (10 bytes) 3.4x10(-4932) to
TYPE COMPATIBILITIES
Warning: If you store values of one type in
variable of another type the results can be
inconsistent:
Can store integers in floating point or in char
(assumes ASCII value)
bool can be stored as int: (true = nonzero, false = 0)
Implicit promotion: integers are promoted to
doubles
double var = 2; // results in var = 2.0
On integer and doubles together:
Mixed type expressions: Both must be int to return
int, otherwise float.
Dr. Muniba Ashfaq
TYPE COMPATIBILITIES
(IMPLICIT CONVERSION)
The compiler tries to be value-preserving.
General rule: promote up to the first type that
can contain the value of the expression.
Note that representation doesn’t change but
values can be altered .
Promotes to the smallest type that can hold
both values.
If assign float to int will truncate
int_variable = 2.99; // results in 2 being stored in
int_variable
If assign int to float will promote to double:
double dvar = 2; // results in 2.0 being stored in
dvar
Dr. Muniba Ashfaq
TYPE COMPATIBILITIES
(EXPLICIT CONVERSION)
Casting - forcing conversion by putting (type) in front of
variable or expression. Used to insure that result is of
desired type.
Example: If you want to divide two integers and get a real
result you must cast one to double so that a real divide
occurs and store the result in a double.
int x=5, y=2; double z; z = static_cast <double>(x)/y; // 2.5
int x=5, y=2; double z; z = (double)x/y; // 2.5
int x=5, y=2; double z; z = static_cast <double>(x/y) ; // 2.0
converts x to double and then does mixed division, not
integer divide
static_cast<int> (z) - will truncate z
static_cast <int> (x + 0.5) - will round positive x {use () to
cast complete expression)
Cast division of integers to give real result:
int x=5, y=2; double z; z = static_cast <double>(x/y) ; // 2.0
Dr. Muniba Ashfaq
STREAM EXTRACTION AND ASSIGNMENT
OPERATOR
>> (stream extraction operator)
When used with cin, waits for the user to input a value and
stores the value in the variable to the right of the operator
The user types a value, then presses the Enter (Return) key to
send the data to the computer
Example:
int myVariable;
cin >> myVariable;
Waits for user input, then stores input in myVariable
= (assignment operator)
Assigns value to a variable
Binary operator (has two operands)
Example:
sum = variable1 + variable2;
Dr. Muniba Ashfaq
A SIMPLE PROGRAM TO ADD TWO NUMBERS
1 //example
2 // program to add two numbers
3 #include <iostream>
4
5 int main()
6 {
7 Use
int integer1, integer2, sum; stream extraction
// declaration
8 operator with standard input
9 stream to//obtain
cout << "Enter first integer\n"; user•input.
prompt Notice how cin is used to get user input.
10 cin >> integer1; Calculations can //be performed
read in output
an General
integer form statements: alternative for
is cin>>identifier;
11 cout << "Enter secondlines 13 and 14:// prompt
integer\n"; • Cin is an I stream object
12 cin >> integer2; • streams input from standard input
// read an integer
13 cout << "Sum is " <<
sum = integer1 + integer2;
• uses
// integer1 thesum
>> (input
+ integer2
assignment of << operator)
std::endl;
• Note that data entered from the keyboard
14 cout << "Sum is " << sum << endl; // print sum
must be compatible with the data type of the
15 variable
•Variables can be output using cout << variableName.
16 return• 0;
Generl//form
indicate endl flushes the buffer and prints a
that program ended successfully
is cout<<expression;
17 } newline.
• An expression is any c++ expression(stringConcatenating,
constant, identifier,
chaining or
formula or function call) cascading stream insertion
• Cout is an o stream object
• streams output to standard output operations.
• uses the << (output) operator
OUTPUT OF PROGRAM
Dr. Muniba Ashfaq
PROGRAM TO FIND THE AREA OF
RECTANGLE
Tells the compiler to use names
in iostream in a “standard” way
Dr. Muniba Ashfaq
OUTPUT
Dr. Muniba Ashfaq
PROGRAM TO FIND TOTAL NUMBER OF STUDENTS IN
ALL SECTIONS
1. //example
2. //to find the total number of students in all sections.
3. # include <iostream> //preprocessor directive
4. int main()
5. {
6. int number_of_sections, students_per_section; //declaration
7. int total_students;
8. cout<<"enter the number of sections\n"; //prompt to enter total number of sections
9. cin>>number_of_sections; //reading number of sections
10. cout<<"enter the number of students per section\n"; //prompt to enter number
11. // of students per section
12. cin>>students_per_section; //reading students per section
13.
14. total_students = number_of_sections * students_per_section; //assignment to total students
15. cout<<"total number of students in all the sections is\n"; //prompt
16. cout<<total_students; // show the number of total students
17. return 0;
18. }
Dr. Muniba Ashfaq
OUTPUT
Dr. Muniba Ashfaq
ARITHMETIC
Arithmetic is performed with operators.
Arithmetic operators are listed in following table
C ++ o p e ra tio n Arith m e tic Alg e b ra ic C ++ e xp re ssio n
o p e ra to r e xp re ssio n
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y
Modulus % r mod s r % s
Modulus operator returns the remainder of integer division
7 % 5 evaluates to 2
Integer division truncates remainder
7 / 5 evaluates to 1
Dr. Muniba Ashfaq
RESULTS OF ARITHMETIC OPERATORS
Arithmetic operators can be used with any numeric type.
An operand is a number or variable used by the operator e.g.
integer1 + integer2
+ is operator
integer1 and integer2 are operands
Result of an operator depends on the types of operands
If both operands are int, the result is int
If one or both operands are double, the result is double
Dr. Muniba Ashfaq
Dr. Muniba Ashfaq
ARITHMETIC EXPRESSIONS
Arithmetic operations can be used to express
the mathematic expression in C++:
b 2 4ac b *b 4* a *c
x( y z ) x * ( y z)
1
2 1 /( x * x x 3)
x x3
ab (a b) /( c d )
cd
Dr. Muniba Ashfaq
OPERATOR PRECEDENCE
Some arithmetic operators act before others
(e.g., multiplication before addition)
Be sure to use parenthesis when needed
Example: Find the average of three variables a, b
and c
Do not use: a + b + c / 3 (incorrect)
Use: (a + b + c ) / 3 (correct)
Dr. Muniba Ashfaq
RULES OF OPERATOR PRECEDENCE
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested,
the expression in the innermost pair is evaluated
first. If there are several pairs of parentheses “on
the same level” (i.e., not nested), they are
evaluated left to right.
*, /, or % Multiplication Division Evaluated second. If there are several, they are
Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several,
Subtraction they are evaluated left to right.
Dr. Muniba Ashfaq
OPERATOR PRECEDENCE
An example to understand operator precedence.
20 - 4 / 5 * 2 + 3 * 5 % 4
(4 / 5)
((4 / 5) * 2)
((4 / 5) * 2) (3 * 5)
((4 / 5) * 2) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) + ((3 * 5) % 4)
Dr. Muniba Ashfaq
ASSIGNMENT OPERATORS
= is the assignment operator
Used to assign a value to a variable
An assignment statement changes the value of a variable
General Form:
identifier = expression;
The single variable to be changed is always on the left
of the assignment operator ‘=‘
On the right of the assignment operator can be
Constants
For example age = 21;
Variables
For example my_cost = your_cost;
Expressions
For example circumference = diameter * 3.14159;
Dr. Muniba Ashfaq
ASSIGNMENT OPERATORS
The ‘=‘ operator in C++ is not an equal sign
The following statement cannot be necessarily true in algebra
number_of_bars = number_of_bars + 3;
In C++ it means the new value of number_of_bars
is the previous value of number_of_bars plus 3
Dr. Muniba Ashfaq
ASSIGNMENT EXPRESSION
ABBREVIATIONS
Program can be written and compiled a bit faster by the use of
abbreviated assignment operators
C++ provides several assignment operators for abbreviating assignment
expressions.
Addition assignment operator
c = c + 3; abbreviated to
c += 3;
Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
Other assignment operators
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
Dr. Muniba Ashfaq
ARITHMETIC ASSIGNMENT
OPERATORS
Assig nm e nt Sa m p le Exp la na tio n Assig ns
o p e ra to r e xp re ssio n
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
+= c += 7 c = c + 7 10 to c
-= d -= 4 d = d - 4 1 to d
*= e *= 5 e = e * 5 20 to e
/= f /= 3 f = f / 3 2 to f
%= g %= 9 g = g % 9 3 to g
Dr. Muniba Ashfaq
INCREMENT AND DECREMENT
OPERATORS
Increment and decrement operators are unary operators as they
require only one operand.
++ unary increment operator
Adds 1 to the value of a variable
x ++;
is equivalent to x = x + 1;
Pre-increment
When the operator is used before the variable (++c)
Variable is changed, then the expression it is in is evaluated
Post-increment
When the operator is used after the variable (c++)
Expression the variable is in executes, then the variable is
changed.
Dr. Muniba Ashfaq
INCREMENT AND DECREMENT
OPERATORS
-- -- unary decrement operator
Subtracts 1 from the value of a variable
x --;
is equivalent to x = x – 1;
Pre-decrement
When the operator is used before the variable (--c)
Variable is changed, then the expression it is in is evaluated.
Post-decrement
When the operator is used after the variable (c--)
Expression the variable is in executes, then the variable is
changed.
Dr. Muniba Ashfaq
INCREMENT AND DECREMENT
OPERATORS
Example
If c = 5, then
cout << ++c;
c is changed to 6, then printed out
cout << c++;
Prints out 5 (cout is executed before the increment)
c then becomes 6
When variable not in expression
Preincrementing and postincrementing have same effect
++c;
cout << c;
and
c++;
cout << c;
are the same
Dr. Muniba Ashfaq
SUMMARIZING INCREMENT AND DECREMENT OPERATORS
IN A TABLE
O p e ra to r C a lle d Sa m p le e xp re ssio n Exp la na tio n
++ preincrement ++a Increment a by 1, then use the new value
of a in the expression in which a resides.
++ postincrement a++ Use the current value of a in the expression
in which a resides, then increment a by 1.
-- predecrement --b Decrement b by 1, then use the new value
of b in the expression in which b resides.
-- postdecrement b-- Use the current value of b in the expression
in which b resides, then decrement b by 1.
The associativity of these unary operators is from right to left
Dr. Muniba Ashfaq
AN EXAMPLE TO UNDERSTAND THE
EFFECT OF PRE-INCREMENT AND POST-
INCREMENT
1 // example
2 // Pre incrementing and post incrementing.
3 #include <iostream.h>
4
5
8 // function main begins program execution
9 int main()
10 {
11 int c; // declare variable
12
13 // demonstrate pos tincrement
14 c = 5; // assign 5 to c
15 cout << c << endl; // print 5
16 cout << c++ << endl; // print 5 then post increment
17 cout << c << endl << endl; // print 6
18
19 // demonstrate pre increment
20 c = 5; // assign 5 to c
21 cout << c << endl; // print 5
22 cout << ++c << endl; // pre increment then print 6
23 cout << c << endl; // print 6
24
25 return 0; // indicate successful termination
26
27 } // end function main
Dr. Muniba Ashfaq
OUTPUT
Cout<<c prints c =5
Cout<<c++ prints c =5 then increment c by 1 to 6
Cout<<c prints c =6
Cout<<c prints c =5
Cout<<++c first increment c by one to to 6 then prints c =6
Cout<<c prints c =6
Dr. Muniba Ashfaq
LOGICAL OPERATORS
C++ defines these logical operators: <, >,
<=, >= and == (the equivalence operator)
You can compare any variable. Characters
are compared based on their ASCII values.
All answers will be true (not zero) or false
(0)
You can extend the logic with && (and), !
(not) and || (or).
MORE OPERATORS
== test equality x == y
= assignment x = y
!= not equal
>= greater than or equal
<= less than or equal
MORE OPERATORS
> greater than
< less than
no space between operators
= = is invalid == OK
& bitwise AND
| bitwise OR
~ bitwise NOT
COMPOUND STATEMENTS
&& and
|| or
! not
PRECEDENCE OF THE OPERATORS
ENCOUNTERED SO FAR
O p e ra to rs Asso c ia tivity Typ e
() left to right parentheses
++ -- static_cast<type>() left to right unary (postfix)
++ -- + - right to left unary (prefix)
* / % left to right multiplicative
+ - left to right additive
<< >> left to right insertion/extraction
< <= > >= left to right relational
== != left to right equality
?: right to left conditional
= += -= *= /= %= right to left assignment
, left to right comma
Dr. Muniba Ashfaq