You are on page 1of 81

Object Oriented Programming

Unit – I

Overview of C++
C++ BASICS
 C++ Character Sets
 Tokens
1. Keywords
2. Identifiers
3. Literals
i. Integer constant
ii. Floating constant
iii. Character constant
iv. String literal
4. Punctuators
5. Operators

2
C++ Data types
1. Fundamental data types
a) int Data type
b) char Data type
c) float Data type
d) double Data type
e) void Data type
2. Derived data types
a) Arrays
b) Function
c) Pointer
d) Reference
e) Constant
3. User-Defined Derived data types
a) Class
b) Structure
c) Union
4. Data Type Modifiers
1. Signed
2. Unsigned
3. Long
4. Short 3
Operators and Expression

1. I/O Operators
2. Arithmetic Operators
3. Increment / Decrement Operators
4. Relational Operators
5. Logical Operators
6. Conditional Operators
7. Some other Operators
1. Sizeof()
2. Comma Operator

4
Flow of Control
1. Compound Statement
2. Selection statements
1. The if statement
2. The switch statement
3. Iteration Statements
1. The for loop
2. The while loop
3. The do..while loop
4. Nested Loops
4. Jump Statements
1. The goto statement
2. The break statement
3. The continue statement
5
Console I/O Operations

I. Unformatted Console I/O functions


1. Single Character functions(getchar(), putchar()
2. String functions (gets(), puts())
II. Unformatted Stream I/O functions
III. Character functions(get(), put())
IV. String functions (getline(), write())

6
When? Where? Who?

C++ is a language developed at


AT & T Bell laboratories by Bjarne
Stroustrup in the 1980s.

7
C++ CHARACTER SET

It is a set of valid characters


that a language can recognize.

It represents any letter, digit or


any other sign.

8
The C++ has the following
CHARACTER SET

1. - A-Z, a-
LETTERS
2. DIGITS z
- 0-9
3. SPECIAL SYMBOLS
4. WHITE SPACES
5. OTHER CHARACTERS

9
TOKEN
S
C++ provides following tokens (smallest
individual unit in a program )
KEYWORDS
IDENTIFIERS
LITERALS
PUNCTUATORS
OPERATORS

10
KEYWORDS

These are the words that convey a special


meaning to the language compiler.

These are reserved for special purpose


and must not be used as normal identifier
names.

11
Some of the KEYWORDs are…

auto, break, case, char, class,


const, continue, default, delete, do,
double, else, enum, extern, float,
for, friend, goto, if, inline, integer,
long, new,…..

12
IDENTIFIERS

These are FUNDAMENTAL BUILDING


BLOCKS OF A PROGRAM.

C++ is case sensitive as it treats upper


and lower-case characters differently.

13
Some of the valid
IDENTIFIERS are…

MYFILE
Myfile

Stud1
stud23

Emp_no
14
Some of the invalid
IDENTIFIERS
are…

MY.FILE
29Myfile
break
Emp-no
Reg No

15
LITERALS

These are data items that never change


their value during a program run.

It is also referred to as constants

16
Different types of
LITERALS are…

1. Integer-constant
2. Character-constant
3. Floating-constant
4. String-constant

17
INTEGER CONSTANT

These are WHOLE NUMBERS WITHOUT


ANY FRACTIONAL PART.

C++ allows three types of integer


constant
Decimal – Eg. 123, +97
Octal - Eg. 0123, 010
Hexa-Decimal – Eg. 0x14, 0XC
18
CHARACTER CONSTANT

It is one character enclosed in single quotes.

Eg. „a‟, „1‟

Escape sequence represents a single


character (Eg. „\n‟, „\t‟, „\\‟, etc.)

19
FLOATING CONSTANT

It is also called real constants


These are numbers having fractional parts
These may be written in one of the two forms called
Fractional form
Exponent form

Eg. 2.0, 17.23, - 45.23


Eg. 172E05, 1.72E07

20
STRING CONSTANT

It is a sequence of characters surrounded by


double quotes.

Eg. “a”, “123”, “hello welcome”

Each string literal is by default (automatically)


added with a special character „\0‟ which makes
the end of a string
21
PUNCTUATOR
S
The following characters are used as punctuators
(also known as separators).

[] () {} , ; : * = #

22
Basic Datatypes.

Operators.

Control Structures.

Arrays and Functions


23
What is Data type ?

Data types are the means to


identify the typeof data and
associated operations of
handling it.
24
C++ data types are of two types

1. Fundamental (atomic or
dynamic or primitive) Datatype

1. Derived (Non-primitive)
Datatype
25
1. Fundamental Data type
The data items that cannot be
decomposed of.
There are five such data
types :
int for integers
float for real numbers
char for characters
double
precision for real numbers
with higher
26
integer Data type
Approx. size
Type Minimal range
( in bytes)

Short 2 -32768 to 32767


Unsigned short 2 0 to 65535
Signed short 2 Same as short
int 2 -32768 to 32767
Unsigned int 2 0 to 65535
Signed int 2 Same as int
long 4 -2147483648 to
2147483648
Unsigned short 4 0 to 4294967295
Signed short 4 Same as long
27
float Data type

Approx. size
Type Minimal range
( in bytes)

Float 4 3.4 X 10 -38 to 3.4 X 10 38 - 1


Double 8 1.7 X 10 -308 to 1.7 X 10 308 - 1
-4932 to 3.4 X 10 4932 –
Long double 10 3.4 X 10 1
char Data type

Approx. size
Type Minimal range
( in bytes)

char 1 -128 to 127


Unsigned char 1 0 to 255
Signed char 1 Same as char
2. Derived data types
The data items that are composed of
the fundamental data types
They are of two types :
1. Predefined derived data types like array,
pointer, reference, constant etc.
1. User defined derived data types
like structure, class, union, etc.
Uses of Data types
As the type specifier for the data and
functions in the program

To declare variables and functions

For the explicit type conversion of


data
Data Type Modifiers
The keywords used along with the basic data types to
extend the range of data handled by the basic data
types.
This is achieved by excluding the negative numbers in
the range
Also by allocating more number of bytes for the data.
Type modifiers of C++ are signed, unsigned, long
and short.
1.
Arrays
It refers to a named set of finite number of
same type of data,
Each of which can be referenced by
mentioning its position (called subscript) in the
list.
There are one-dimensional and multi-
dimensional arrays.
2. Function
It is the named unit of a set of instructions to
perform a particular task.
A function is invoked from other parts of the
program.
A function should be declared before it is
defined if the function calling statement
appears before its definition.
3. Pointer
A variable that can hold the address of a
memory location.
The declaration of the pointer consists of a data
type, an *(asterisk) and the variable name.
The data type of the pointer depends upon the
type of the data that is pointed to by it.
4. Reference
It is an alternative name of an object.
A reference variable provides an alias
name to a previously defined variable.
Its declaration consists of the data type, an
&(ampersand) and the variable.
The data type of reference variable will be
same as that of its original variable name.
5. Constant
It makes a variable symbolic constant.

The keyword const is used to make an


object constant.
The syntax is:
const DataType VarName = Value;
6. Enumeration
A small group of related objects may be
put in a set and given a name.
A user can define a set of integer type
identifiers in the form of new data types
called enumerated data types.
It is an alternative method for naming
integer constants.
The keyword used is enum.
Syntax:
enum variable {enumerator’s list};
Example:
enum week
{sun,mon,tue,wed,thur,fri,sat};
VARIABLES
Variable are identifiers of memory locations
That is, Variables are the names given to
storage locations by which the contents of those
locations can be referenced.
There are two values associated with a variable:
 lvalue which is the address of the memory
location
 rvalue which is the content of the location
This is to be declared in the program prior to its
use in it.
Varible declaration
DataType VarName;
m Variable Name
Example :
100 RValue
 int num;
 float p,q,root; 100 101 LValu
e
 int m=100;
 const float pi=3.14;
OPERATOR
S Operators

UNARY BINARY TERNARY

1. I/O
2. Arithmetic
1. Increment
3. Relational
2. Decrement
4. Logical Conditional Operator
3. Unary minus
5. Bitwise
4. Sizeof() operator
6. Shift
Increment / Decrement

Two special operators of C++


The increment operator(++) adds 1 to its
operand
The decrement operator(--) subtracts 1
from its operand
The result will be stored in the same
operand.
Consider the code snippet:

int a=5, b=3;


a++; b--;
After
execution a
= 6 and b =
2
i.e., a++; is
equivalent to
sizeof() Operator

It is a unary compile-time operator

It returns the number of bytes occupied


by the variable or data type specified
within the parantheses

For example : sizeof(float) returns 4


I / O Operators

The operators for input and output


operations are :
 >> called extraction or get
from
 << called insertion or put to
Eg: cin >> a; cin >> b >>
d; cout << “Hello”;
cout << a;
RELATIONAL OPERATORS
•It compare two quantities, i.e., it
determine the relation between the
two data.
The result of the operation will be
either TRUE (1) or FALSE(0).
They are : <, <=, >, >=, ==, !=
Arithmetic operators

The symbols that trigger computations in the


program are called arithmetic operators.
 + for Addition,
 - for subtraction,
 * for multiplication,
 / for division,
 % for remainder of division ( it works
only on integer operands.)
Logical Operators

It is used to combine existing relational


expressions.
The logical AND(&&), logical OR(||) and
logical NOT(!) are the operators.
Arithmetic Vs Relational Vs logical

 Arithemetic  Relational  Logical


 Combines relational
 Performs  Performs expressions
computational comparision
operation operation
 Operands are  Numeric and  The operands are
numeric and character operands boolean
character data only are allowed values(TRUE/FALSE
)
 Result will be  Result will be
 Result will be a
numeric either true or false boolean
 Both unary and  All the operators  values
Both binary and unary
binary operators are are binary operators are available
available
Conditional Operator(? :)

It is a ternary operator, which requires


three operands to operate upon.
This operator returns depending on
condition.
a
The syntax : expression1?
expression2:expression3
Precedence of Operators

Precedence Operator Meaning

() Function call or bracket


1.
[] Array subscript
! Logical negation(NOT)
+ Unary plus
2. - Unary minus
++ Pre increment or post increment
-- Pre decrement or post decrement
Sizeof Returns size of operand, in bytes
* Multiply
3. / Divide
% Remainder(Modulus)
+ Binary plus
4.
- Binary minus
Precedence of Operators

Precedence Operator Meaning

< Less than


<= Less than or equal to
5.
> Greater than
>= Greater than or equal to
== Equal to
6.
!= Not equal to
7. && Logical AND
8. || Logical OR
9. ?: Conditional Operator
10. = Simple assignment
Expression
s
Operators and operands are
combined to form expressions.
An expression represents an
operation and normally it returns a
value as the result of the operation.
Since there are different types of
operators, expressions are also of
different types.
Type conversion
When constants and variables of different
types are mixed in an expression proper
type conversion methods are applied to get
the correct results.
It is the process of converting one
predefined type into another in a particular
expression.
Type conversions are of two types:
1. Implicit type conversion
It also known as type promotion
Conversion is done by the compiler
without programmer’s intervention.
In this case the compiler converts all
operands up to the type of the largest
operand.
2. Explicit type conversion
It also known as type casting
Conversion is done by the programmer.
Example,
Ans = (float)a/b;
FLOW OF
CONTROL
Normally, the instructions contained in a
program are executed in a sequential fashion
and one instruction will be executed only once.
 In some situations,
some of the statements need to be skipped
without executing them,
 While in some other situations,
Some of the statements need to be executed more
than once.
 C++ provides two facilities :
1. Selection 2. Iteration
STATEMEN
It is the
TS
instructions given to the
computer to perform any kind of action.
It is terminated with a semicolon(;).
A sequence of statements enclosed by a
pair of braces({ }) is called Compound
statement.
{ statement-1; block
statement-
} 2;
Selection
Statements
It is also called conditional or decision statements

C++ provides two types of Selection stmts

1. if statements – Single Selection

2. switch statement – Multiple Selection


The if statements
The if statement has four forms:
1. Simple if
2. If…else
3. If…else if ladder
4. Nested if
Syntax of simple
if
if (boolean expression)
{
statement(s)
}
If expression evaluates to true, the
statement will be executed;
otherwise it will be skipped.
Syntax of if…
else If the expression
if (bool. expression) evaluates to true, the
{ statement1 will be
statement1(s) executed and
} statement2 will be
skipped.
else
If the expression
{ evaluates to false, the
statement2(s) statement1 will be
} skipped and statement2
will be executed.
Syntax of nested if
if (boolean expression)
{ An if statement can
if(boolean expression) contain another if
{ statement, which is
statement1(s)
}
called nesting of if.
} The nesting will be
else complex when there are
{ more and more ifs
if(boolean expression)
{
within the else of each if.
statement2(s) This can be simplified by
} the if..else if ladder
}
Syntax of if…else ladder
if (boolean expression1)
statement1
else if(boolean expression2)
statement2
else if(boolean expression3)

else
statement
Exercis
eGiven the following set of identifiers:
char ch;
short sh;
int intval;
long
longval;
float fl;
Identify
the
Exercis
e What output will the following code
fragment produce?
int val, res, n=1000;
cin >>val;
res = n + val >1750 ? 400 : 200;
cout << res;
(i) if the input is 2000
(ii) if the input is 1000
(iii) if the input is 500
Exercis
e Suppose x1 and x2 are two type
double variables that you want to add
as integers and assign to an integer
variable. Construct a C++ statement
for doing so.
Exercis
e
 Write the output of the following
code segment when I is an integer
variable with value 10.
int x, I=10;
(a)I+= I + I; cout << I;
(b)x = I++ + ++I; cout << x;
Problem

Write a program to display the


grade corresponding to the mark
given as input(using if…else ladder)
The conditional operator(? :)
alternative to if
C++ has a conditional operator that
can be used as an alternative to if
statement.
This operator can be used to replace
if…else statements of the following
general form:
if (expression) Exampl
statement1 e if (a>b)
else big=a;
statement2 else
big=
Alternative method b;
Expression ? Statement1 :
statement2 big = (a>b) ? a : b;
The switch statement
It is a multiple-branch selection
statement
This selection statement successively
tests the value of an expression against
a list of integer or character constants.
When match is found, the statements
associated with that constant are
executed.
Syntax
switch(integer or character expression)
:{
case constant1: statements; break;
case constant2: statements; break;
case constant3: statements; break;
…….
default: statement;
}
Example
: switch(dow)
{
case 1: cout << “\nSunday”; break;
case 2: cout << “\nMonday”; break;
case 3: cout << “\nTuesday”; break;
case 4: cout << “\nWednesday”;
break;
case 5: cout << “\nThursday”; break;
case 6: cout << “\nFriday”; break;
case 7: cout << “\nSaturday”; break;
default: cout << “\nWrong number of 75
LOOPS
It is a group of instructions the computer
executes repeatedly until some
terminating condition is satisfied.
Generally there are two types
Entry controlled loops
For loop
While loop
Exit controlled loops
Do while loop
for loop

Syntax:
for(initialization_expression;
conditional_expression;
update_expression)
{
body of the loop;
}
while loop

Syntax:
Initialization statatement;
while(conditional_expression)
{
body of the loop;
updating statement;
}
do while loop

Syntax:
Initialization statement
do
{
body of the loop;
updating statement;
}
while(conditional_expressi
on);
Nested Loop

A loop containing another loop is known


as nested loop.
The inner and outer loop need not be of
the same type.
Exercise

Write a C++ program to find the decimal


equivalent of a given binary number.

You might also like