Vous êtes sur la page 1sur 163

MODULE I

C0mputer
Pr0gramming and
Numerical meth0ds

1
Basics of Procedure and
Object Oriented Pr0

2
Procedure Oriented Programming
 In POP the main program is divided into a
number of functions.

 A technique of hierarchical decomposition


has been used to specify the tasks to be
completed for solving a problem.

 It specifies a program as a sequence of


steps

3
Procedure Oriented Programming
• Pop consists of a list of instructions and
organizing them in to groups known as functions

• Functions are called repeatedly in a program to


execute the tasks.

4
Procedure Oriented Programming
• For eg., program may involve

 collecting data from user (reading),

 performing some kind of calculations on the


collected data(calculation)

 displaying the result to the user when


requested(printing).

• All the tasks of reading, calculating and printing


can be written in a program with the help of 3
different functions which performs these 3 tasks.

5
Structure of POP

Main Program

Function - 1 Function - 2 Function - 3

Function - 4 Function - 5

Function - 6 Function - 7 Function - 8

6
Procedure Oriented Programming
 In a multi-function program many
important data items are placed as
global.

 Each function may have its own local


data.

 Global data are vulnerable to an


inadvertent change by a function.

7
Relationship of data and functions in
POP

Global Data Global Data

Function - 1 Function - 2 Function - 3

Local Data Local Data Local Data

8
Procedure Oriented Programming
Another drawback of POP is that it
does not model real world entities well.

POP employs top-down approach.

Examples of POP are C,FORTRAN,


COBOLetc.

9
Procedure Oriented Programming
• In large programs, it is difficult to identify
what data is used by which function

• In case ,we need to revise an external data


structure, we also need to revise all
functions that access the data.

• This provides an opportunity for bugs to


creep in

10
Characteristics of Procedure Oriented
Programming
• Emphasis is on doing things.

• Large programs are divided into smaller


programs known as functions

• Most of the functions share global data

11
Characteristics of Procedure Oriented
Programming
• Data move openly around the system
from function to function

• Functions transform data from one


form to another

• Employs top-down approach

12
Object-Oriented Programming

 OOP decomposes a problem into a number of


entities called objects and then build data and
functions around these objects.

 Functions that operate on data of an object are


tied together in that object.

13
Object-Oriented Programming
Data is hidden and cannot be
accessed by external functions.

Objects may communicate with each


other through functions.

14
OOP continue…
 New data and functions can be added
whenever necessary.

 Follows bottom-up approach in


program design.

15
Organization of data and functions in
OOP
Object A Object B
Data
Data

Functions Communication Functions

Functions

Data
Object C 16
Basic Concepts of OOP

Objects

Classes

Data Abstraction

Encapsulation
17
Basic Concepts of OOP

Inheritance

Polymorphism

Message passing

Dynamic binding

18
1.Objects

Objects are the basic run-time entities in


object-oriented design.

E.g.:- a person, a place, a bank account

During execution the objects interact by


sending messages.

19
Objects continue…
An object is an instantiation of a class.

In terms of variables, a class would be


the type, and an object would be the
variable.

20
Representation of an object

Object: STUDENT
DATA
Student
Name Total
Date-of-birth
Marks
Average

FUNCTIONS
Total
Average Display
Display

21
2. Classes
 A class is a collection of data and its
associated functions referenced under one
name.

 It is actually a collection of objects of the


same type.

 E.g.:- fruit is a class


apple, orange etc are objects of the
class fruit
22
Representation of a class

23
3. Encapsulation
 The wrapping up of data and its associated
functions into a single unit (class) is called
encapsulation.

 The data is not accessible to the outside


world.

 This insulation of data from direct access by


the program is called data hiding or
information hiding.
24
25
4. Abstraction

 Abstraction refers to the act of representing


the essential features without including the
background details or explanations.

 Classes use the concept of abstraction and


are defined as a list of abstract attributes
such as wait, size ,cost ….

 Functions operate on these attributes

26
Abstraction continue…
 The attributes are sometimes called data
members because they hold information.

 The functions that operate on these data


are sometimes called methods or
member functions.

 Since the classes use the concept of data


abstraction, they are known as abstract
data type (ADT)

27
5. Inheritance
Inheritance is the process by which
objects of one class acquire the
properties of objects of another class.

It supports the concept of hierarchical


classification.

Each derived class shares common


characteristics with the class from
which it is derived.

28
Property inheritance
Birds
Attributes
Feathers
Lay eggs

Nonflying
Flying bird
bird
Attributes Attributes
................. ………………..
……………… ……………….

Parrot Peacock Penguin Kiwi


Attributes Attributes Attributes Attributes
……………… ……………… ……………… ……………….
………………. ……………… ……………… ……………….

29
Inheritance continue…
 Inheritance provides the idea of reusability.

 We can add additional features to an existing


class without modifying it.

 This is possible by deriving a new class from


the existing one.

 The new class will have the combined feature


of both the classes.

30
Inheritance continue…

31
Inheritance continue…

32
Inheritance continue…

33
6. Polymorphism
 Polymorphism means ability to take more than
one form.

 An operator exhibits different behavior in


different instances depending on the types of
its operands – operator overloading

 The behavior of operator depends upon the


types of data used in the program.
 E.g. :- operator +
case 1 :- 3 + 4 = 7
case 2 :- “abc” + “xyz” = “abcxyz”
34
Polymorphism continue…
 Using a single function name to perform
different types of tasks – function overloading
Shape

Draw( )

Circle object Box object Square object

Draw( circle) Draw( box) Draw (square)

35
7. Message passing
• Objects can communicate each other by
passing messages.

• Message passing is nothing but sending and


receiving of information by the objects,
same as people exchange information.

• This helps in building systems that simulate


real life.

36
Message passing continue…
• Following are the basic steps in message
passing

Creating classes that define objects and its


behavior.
Creating objects from class definitions.
Establishing communication among objects

• In OOP, message passing involves specifying


the name of the function, and the information to
be sent
37
8. Dynamic binding
• In OOP, dynamic binding refers to linking a
procedure call to the code that will be
executed only at run time.

• The code associated with the procedure is


not known until the program is executed,
which is also known as late binding.

38
Benefits/Advantages of OOP
 Eliminates redundant codes - inheritance

 Saves development time

 Builds secure programs – data hiding

 Software complexity can be reduced

 Easily upgraded from small to large systems


39
Benefits/Advantages of OOP
• OOP provides a clear modular structure for
programs.

• It is good for defining abstract data types

• Implementation details are hidden from other


modules

• It is easy to maintain and modify the existing


code as new objects are created with small
differences to existing ones

• It implements real life scenario.


40
Applications of OOP

• Real-time system design

• Simulation and modeling systems

• Object oriented database

• Object oriented distributed database

• Client-server systems

41
Applications of OOP

• Hypertext, Hypermedia

• Neural networking and parallel programming

• Decision support and office automation systems

• CIM/CAD/CAM systems

• AI and Expert systems

42
Introduction to C++
 C++ is an OOP language.
 It was developed by Bjarne Stroustrup
 C++ is an extension of C
 The important facilities that C++ adds to
C are
classes
inheritance
operator overloading
function overloading
43
C++ character set
• Alphabets – A-Z (uppercase letters)
a-z (lowercase letters)
• Numerals -0,1,2….9
• Special symbols - “ , }
,|,*,&,^,@,$,#,>,<,>=,<=,==,=,+,-,/ ,(, ),%,:, ;,{,}
&&,|| etc.
• White spaces
-back space (\b),horizontal tab (\t),
newline (\n)etc

44
Tokens
• Smallest individual units in a program.

• Tokens are:
keywords
identifiers
constants / literals
punctuators
operators

45
keywords
• Certain identifiers reserved for specific
usage in C++ are called keywords

• Words that convey special meaning to the


compiler

• Keywords cannot be used for naming the


variables in a program

• ANSI C++( American national standards


institute ) supports 32 keywords
46
47
Keywords can't be used for
• Declaring a variable

• Declaring a class

• Declaring a function

• Declaring an object

48
Identifiers
 A name used to identify a variable, a
function, a class or an object

 It is defined by the user.

 Consisting of a sequence of letters and


digits, with a letter as a first character.

 Lowercase letters are preferred.

49
Rules for naming identifiers
1 .Identifier is an arbitrary long sequence of letters and
digits.

2. The first character must be a letter.

3. The underscore (_) is count as a letter

4.Uppercase and lowercase are distinct .

5. Keywords cannot be used as identifier

6. White space are not allowed.

50
Identifiers continue…
• Examples: num, add, rem , _avg,
addr2, FIELetc.

• Examples of non-identifiers:2num , int ,


float , tot sale etc.

51
Constants/literals
 Are tokens that represent data items that
never change their value during a program
run.

 C++ has four types of constants:


Integer constants
Character constants
Floating constants
String constants

52
Integer constants
•Integer constants are the whole numbers.

•It Must have at least one digit and must not


contain any decimal point(period symbol).

•It may contain either + or – sign as the first


character.

53
Integer constants
• C++ allows three types of integer literals:
a) Decimal constant (Base 10)– a
sequence of digits with no zeros in the
beginning. eg . 123 , +56,-67….
b) Octal constants(Base 8)-Sequence of
digits starting with zero. Eg.
010,01237….
c) Hexadecimal constants(Base 16)-
sequence of digits preceded by OX or
Ox
ex . OX79 , 0xAB
54
Character constants

 A valid character enclosed in single quotes


is a character constant.

 eg . „a „ , „y‟ , „L‟

 C++ supports certain non-graphic characters


that can be represented by using escape
sequences which consists of a backslash(\)
followed by one or more characters.

55
Character constants
\b – backspace
\n – newline
\t-horizontal tab
\v – vertical tab
\a- alert
\f-form feed
\r- carriage return

56
Floating constants
 Real numbers(numbers with fractional part)

 They can be written in two forms:

1 .Fractional form
2. Exponential form

57
Floating constants
1 .Fractional form
• A floating constant in fractional form must
have at least 1 digit before the decimal point
and 1 digit after the decimal point.

•It can have a + or - sign preceding it.


Eg . 4.5 , 123.0 – valid
21, 3. , +.01-invalid

58
Floating constants
2. Exponential form

-Floating constants in exponential form has two


parts

– Mantissa :– must be an integer or a real


constant
– Exponent :– must be an integer

-The mantissa is followed by e or E and the exponent

• Ex . 12e -5
12.7E10
59
String literals
• Sequence of characters enclosed in double
quotes

• The string literals are terminated by a null


character (\ 0 ) called string terminator

• The size of a string is the number of


characters plus the null character
• Eg. “ abc “ – 4 bytes

60
Punctuators
• Punctuators are the symbols used in the
program as separators.

• Brackets [ ] ->indicate single and multi


dimensional arrays

• Braces { } ->indicate the start and end of a


compound statement.

• Parentheses ( ) ->indicate function calls,


function parameters, group expressions.

61
Punctuators
• Comma , ->used as a separator in a
function argument list.

• Asterisk * -> used for pointer declaration

• Semicolon ; ->used as a statement


terminator

• Colon : ->indicates a labeled statement

62
Punctuators
• Equal to sign = -> used for variable
initialization, assignment operator in
expressions.

• Pound sign # ->preprocessor directives.

• Ellipsis … ->used in formal argument lists


of function prototypes to indicate a
variable number of arguments

63
Variables

• A variable is an identifier that is used to


represent some specific type of information
in a program

• A variable represents a single data item that


is a numeric quantity or a character
constant.

• The name of a variable can be composed of


letters, digits, and the underscore character.
64
Variables
• The data item must be assigned to the
variable at some point in the program.

• The data item can then be accessed later in


the program simply by referring to the
variable name.

• A given variable can be assigned different


data items at various places within the
program.

65
Variables
• Thus, the information represented by the variable
can change during the execution of the program

• The data type associated with the variable cannot


change.

• General form of variable declaration is


data type variable1, variable2…….variablen;

• Eg.
– int a,b,c; //a,b,c are integer variables
– char d;//d is a character type variable

66
Local Variables
• A local variable is a variable which is either a
variable declared within a function or is an
argument passed to a function.

• If we declare variables in a function, then we


can use only them within that function.

67
Local Variables
• Eg. int main()
{
#include<iostream.h> int a,b;
void swap(int x, int y) cin>>a>>b;
cout<<“a=“<<a<<endl;
{ cout<<“b=“<<b<<endl;
int temp=x; swap(a,b);
x=y; cout<<“a=“<<a<<endl;
cout<<“b=“<<b<<endl;
y=temp; return 0;
} }

68
Global variables
• A global variable is a variable which is
accessible in multiple scopes.

• The global variables are only accessible


after they have been declared .

• For instance, if we consider the example


program, we have one global variable, w.

69
Global variables
Eg.
int main()
#include<iostream.h>
{
double w;
void z() int i;
{ w=4;
w=0; return 0;
return; }
} • Here, w is a global
void q() variable, which has scope
{ in all the three functions
in this programs: z(), q()
int index; and main().
w=2;
• index and i are local
return; variables.
} 70
Dynamic initialization of variables:
• C++ allows initialization of the variables at run
time known as dynamic initialization.
• A variable can be declared and initialized at
run time using expressions at the place of
declaration.
eg, float area=3.14*r*r;
float average=sum/I;

71
C++ operators
• The tokens or symbols that performs some kind of
operations are called operators
• An operation requires an operator and operands

1. arithmetic operators } unary , binary


2. assignment operators
3. Comparison and logical operators { relational ,
equality , logical }
4. Bitwise operators
5. Special operators { ternary , comma ,scope , new
and delete }

72
Arithmetic operators
Arithmetic operators may be :

• Unary operators : require one operand to


operate .

• Binary operators: require two operand to


operate.

73
Arithmetic operators

• Arithmetic operators are used for


performing most common operations of
mathematics like addition, subtraction etc.

• These operators are considered as basic


operators and also known as binary
operators as they require two variables to be
evaluated.

74
Arithmetic operators

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus(remainder of an
integer division)

75
Arithmetic operators

• Eg. Let a=5 and b=3 then,


a+b=8
a-b=2
a*b=15
a/b=1
a%b=2

76
Assignment operators

• An assignment operator is used to


assign the value back to a variable, a
modified value of the present value.

77
Assignment operators
Operator Meaning
= Assignment
+= Assign the sum
-= Assign the difference
*- Assign the product
%= Assign the remainder
/= Assign the quotient

78
Assignment operators

Operator Meaning
>>= Assign right shift
<<= Assign left shift
&= Assign bitwise AND
!= Assign bitwise NOT
|= Assign bitwise OR
^= Assign bitwise XOR

79
Assignment operators
• Eg.
x+=y is equivalent to x=x+y
x-=y is equivalent to x=x-y

80
Comparison and logical operators

• Relational operators

• Equality operators

• Logical operators

81
Relational operators

• Relational operators are used to compare the


values of the variables if they are less than,
greater than the other and so on.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
82
Relational operators
• Eg.
Let a=5 , b=6
a<b -True
a>b -False
a<=b -True
a>=b -False

83
Equality operator

• Equality operators are used for checking the


equality of the given expression or statement
Operator Meaning
== Equal to
!= Not equal to

84
Equality operator
Eg. Let a=6, b=8,c=9
a==b -> False
(a*b)!=c -> True

- „A‟==„B‟ -> False

85
Logical operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

86
Logical operators
• Logical AND: The expression is true only if both
the conditions are true. General form is,
expression1 && expression2

Expression Result
True && True True
True && False False
False && True False
False && False False
87
Logical operators
• Logical AND Example:
Let a=2, b=3, c=5

ie, (a<b) && (b<c)


(2<3) && (3<5)
True && True ->True

88
Logical operators
• Logical OR: The expression is true if any one of
the conditions is true. General form is,
expression1 || expression2
Expression Result
0 || 0 0
0 || 1 1
1 || 0 1
1 || 1 1

89
Logical operators
• Logical OR example,
Let a=2, b=3, c=5
(a<b) || (b>c)
(2<3) || (3>5)
True || False -> True

90
Logical operators
• Logical negation: Logical expression can be
changed from false to true or from true to
false using the negation operator(!)
• General form;
!expression
Expression Result
!(true) False
!(false) True
91
Bitwise operators
• Bitwise complement:- This operator switches all the
bits in a binary pattern, ie, all the 0‟ s becomes 1‟s
and 1‟s becomes 0‟s.

• Shift operators: The shift operations take binary


patterns as input and shift the bits to the left or
right, keeping in same number of bits by dropping
shifted bits off the end and filling in with 0‟s from the
other end.

• C++ provides two types of shift operations:


– Left shift
– Right shift

92
Bitwise operators
• Left shift: The << operator is used for left
shifting.
For eg, Let x=33, its binary pattern is
00100001(8 bits)
x<<3 00100001(initial)
0 01000010
0 10000100
1 00001000(resultant)
93
Bitwise operators
• Right shift: The >> operator is used for right
shifting.
• For eg, Let y = 41, its binary pattern is
00101001
y>>2(initial) 00101001
00010100 1
(Resultant) 00001010 0

94
Bitwise operators
• Bitwise AND: The bitwise AND operations are
carried out between the two bit patterns of
the two operands.
Let, x=6 0110
y=3 0011
x&y 0010

95
Bitwise operators
• Bitwise OR: The bitwise OR operations are
similar to the bitwise AND and the result is 1 if
any one of the bit value is 1.
• The symbol | represents the bitwise OR
x=6 0110
y=1 0001
x|y 0111

96
Bitwise operators
• Bitwise Exclusive OR: This operation can be
carried out by the notation ^ .
• To generate a 1 bit in the result, a bitwise
exclusive OR needs a 1 in either number, but
not in both.
• Let, x=5 0101
y=2 0010
x^y 0111
97
Special operators:Unary operators
• Unary operators precedes their single operand.
• Unary minus (-) – to change the sign of a value
x=-50
• Unary Plus(+) – to represent a positive number
y=+55
• Increment (++)and decrement operators(--)
++ adds one to its operand
eg. x++ -> x=x+1
++x ->x=x+1
-- subtract one from its operand
eg. x-- -> x=x-1
--x ->x=x-1
98
Special operators:Unary operators

• sizeof () -> gives bytes occupied by a


variable
eg, sizeof (x)
• & operator prints the address of a
variable in the memory
• * operator indicates the contents of the
storage field to which a pointer is
pointing.
• ! Operator is negation operator.
• ~ operator is bitwise complement

99
Special operators : conditional
operators
• Conditional operator(ternary operator) is
indicated by the symbol ?:
• This operator uses three expressions.
• The general form is,
expression1 ? Expression2 : expression3
• If expression 1 is true, then expression2 is
evaluated; otherwise expression3 is
evaluated.
100
Special operators : conditional
operators
• Eg, Let x=10;
y=x>9 ? 100 : 200;
• Y is assigned the value 100 if x>y .
• Otherwise ,y=200

101
Special operators :typecast
operator
• Converts a declared data type to some other
required type
• C++ provides a specific way for converting one
data type to other using typecast operator.
• Syntax:
(type-name)expression
Eg, avg=sum/(float)i;

102
Special operators :typecast
operator
• Type name behaves as if it is a function for
converting values to a designed type
– Eg, result=(int)(19.2/4);
– The cast operation(int) casts not only the 19.2 but
also the entire expression.
– The result is 4, rather than 4.8

103
Special operators :comma
operator
• C++ uses comma in two ways
• The first use of comma is as a
separator in the variable declaration.
– Eg, int a,b,c;
• used as a separator in a function
argument list

104
Special operators :scope
resolution operator
• C++ supports a mechanism to access a global
variable from a function in which a local
variable is defined with the same name as that
of the global variable.
• It is achieved using the scope resolution
operator.
• Syntax:
::variable name
The variable name is the global variable.

105
Special operators :scope
resolution operator
• The global variable to be accessed must be preceded by the
scope resolution operator.
• It directs the compiler to access a global variable, instead of
the one defined as local variable.
• Eg,
……
…….
{ Block 2
int x=10;
……..
{
int x=1; Block1
……..
}
……
}

106
Special operators :scope
resolution operator
• Block2 is contained in block1
• A declaration in an inner block hides a
declaration of the same variable in an outer
block
• Within the inner block, the variable x will refer
to the data object declared therein.
• ::x is used to access the global variable.

107
Memory management operators:
new and delete
• They are also called free store operators.

• An object can be created by using new and destroyed


by using delete, when required.

• The operators new and delete perform the task of


allocating and freeing the memory.

• A data object created inside a block with new will


remain in existence until it is destroyed by using delete.

108
Memory management operators:
new and delete
• The new operator can be used to create objects of
any type.
• Syntax:
pointer-variable = new data-type;
• Pointer variable is a pointer of type data-type
• The new operator allocates sufficient memory to
hold a data object of type data-type and returns the
address of the object.
• The data-type may be any valid data type.
• The pointer variable holds the address of the
memory space allocated.
• Eg, p=new int; Where p is a pointer of type int. 109
Memory management operators:
new and delete
• We can initialize the memory using the new operator.
pointer-variable=new data-type(value);
Eg, int *p=new int(25);

• The general form for one dimensional array is


pointer-variable=new data-type[size];
Eg, int *p=new int[10];

• Creates memory space for an array of 10 integers

• P[0] – first element


• P[1] – second element
110
Memory management operators:
new and delete
• When a data object is no longer needed, it is
destroyed to release memory space for reuse.

• The general form is


delete pointer-variable;
Eg, delete p;

111
Manipulators
• Manipulators are operators that are used to
format the data display.
• The most commonly used manipulators are
endl and setw.
• Endl:
– The endl manipulator when used in an output
statement, causes a linefeed to be inserted.
– Eg, cout<<“m”<<m<<endl;
cout<<“n”<<n<<endl;

112
Manipulators
• Setw:
– It is used to specify a common field width for all
the numbers and force them to be printed right
justified.
– Eg, cout<<setw(5)<<sum<<endl;

113
Increment and decrement operators

• Increment and decrement operators are


unary operators that add or subtract one
from their operand respectively.

• Increment operators are used to increase


the value of the variable by one and
decrement operators are used to
decrease the value of the variable by one.

114
Increment and decrement operators
• Syntax:-
Increment operator:
++variable name or variable name++
Decrement operator:
--variable name or variable name--
• Example:
Increment operator: ++i, i++
Decrement operator:--i, i--

115
Increment and decrement
operators:Example programs
• Increment operator • Decrement operator
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i=1; int i=20;
while(i<10) while(i>10)
{ {
cout<<i; cout<<i;
i++; i--;
} }
} }

116
Pre-increment and post increment

• In pre-increment, value is first incremented


and then used inside the expression.
a=++i;
• Here, suppose the value of variable i is 5,
then the value of variable a will be 6 because
the value of i gets modified before using it in
an expression.

117
Pre-increment and post increment

• In post-increment, value is first used in the


expression and then incremented.
a=i++;
• Here, suppose the value of the variable i is 5
then value of variable a will be 5 because,
the value of i gets incremented only after
assigning the value 5 to a.

118
Datatypes
C++ data types are:
• Built-in type
– Integral type– int & char
– Void
– Floating type – float & double
– Boolean
• Derived type
– Array
– Function
– pointer
– Reference
• User-defined type
– Structure
– Union
– Class
– Enumeration 119
Built-in data types
• Known as primary, fundamental or basic data
types.

• The void data type is used with functions that


do not return any value.

• And void is also used to represent the empty


argument list of function call statement.
120
Built-in data types
• With the exception of void, the basic data
types may have several modifiers preceding
them to serve the needs of various situations.

• The modifiers signed, unsigned, long and


short may be applied to character and integer
basic data types.

• The modifier long may be applied to double.


121
Built-in data types
Type Bytes Range

bool 1 True or false

char 1 -128 to 127

Unsigned char 1 0 to 255

Signed char 1 -128 to 127

int 2 -32768 to 32767

Unsigned int 2 0 to 65535

Signed int 2 -32768 to 32767


122
Built-in data types
Type Bytes Range

Short int 1 -128 to 127

Unsigned short int 1 0 to 255

Signed short int 1 -128 to 127

Long int 4 -2147483648 to 2147483647

Signed long int 4 -2147483648 to 2147483647

Unsigned long int 4 0 to 4294967295

float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

Long double 10 3.4E-4932 to 1.1E+4932123


Built-in data types
• char type: used to hold ASCII characters like
‘a’, ‘B’ or any other 8 bit quantity.

• bool type: Can hold only two values true(non-


zero) or false(zero)

• int type: can hold integer quantities that do


not contain a decimal point.
124
Built-in data types
• float type: used to store numbers with a
fractional component or when larger numbers
are involved. It is also known as real data type.

• double type: Same purpose as that of float, but


there is considerable difference in the magnitude
and precision of the numbers they can hold.

• string type: used to hold multiple characters


without the array management overhead.

125
User-defined data types
• Structures
• Classes
• Union
• Enumeration data types

126
User-defined data types
• Structure data type:
– Structures uses struct keywords to combine variables of
different data types in a single record.
– Syntax
• Struct[<struct name>]
{
<data type> <variable-name1>;
<data type> <variable-name2>;
} <sructure variable declaration>;
– Eg,
struct friend
{
char name[80];
int age, height;
}friendA;
127
User-defined data types
• class data type:
– The class keyword is used
– Syntax,
<class keyword><class-name> [<:base class list>]
{
<member variable list>
}
– Eg,
class circle
{
int radius; //data member
int area(void);//member function
} 128
User-defined data types
• union data type:
– Same as compared to struct, the only difference is that it
lets the user to declare variables that share same memory
space.
– Syntax
union [<union name>]
{
<data-type> <variable names>;
}[<union variables name>];

– Eg,
union charorint
{
char c;
int i;
}number; 129
User-defined data types
• Enumeration data type:
– enum is the keyword used.

– The programmer can declare new data type and define the
variables of these data types that can hold.

– For example, the user can define the material as a new


data type.

– Its variables may be solid, liquid or gas.

– Thus three values are restricted for this new data type

130
User-defined data types
• Syntax:
enum data-type {variable1,variable2}
• Example:
enum material{solid,liquid,gas};
enum logical{false,true};
enum logical{true=2,false=4};

• In the second example, the keyword enum is followed


by the tag name logical.
• The enumerators are the identifiers false and true.
131
Derived data type
• The derived data types are:
– Pointers
– Functions
– Arrays
– References

132
Derived data type
• Pointers:
– A pointer is a memory variable that stores a
memory address.

– Pointer can have any name that is legal for other


variables.

– It is declared in the same fashion like other


variables, but it is always denoted by a *
operator.

133
Derived data type
• Examples:
int *x;
float *f;
char *y;

• In the first statement, x is an integer pointer and tells


the compiler that it holds the address of any integer
variable.

• In the same way, f is a float pointer that stores the


address of any float variable and y is a character
pointer that stores the address of any character
variable.
134
Derived data type
• Functions:
– A function is a self-contained block or a sub-
program of one or more statements that perform
a special task when called.

– It is possible to use the same name with multiple


definitions called as function overloading.

135
Derived data type
int main() funA()
{ {
…. ….
funA(); ….
…… return;
}
……..
funb()
funB()
….
{
….
….
}
….
….
return;
}

136
Derived data type
• In figure, funA() and funB() are two user
defined functions.

• These are invoked from the body of the


main().

• After the execution of funA() and funB(), the


program control returns back to the calling
function main().
137
Derived data type
• Arrays:
– Array is a collection of elements of similar data
types in which each element is located in separate
memory location.
• Eg, int b[4];
• It declares an array b[] which can hold four
integer values.

138
Derived data type
• References:
– C++ reference types declares with & operator.
– These are nearly identical but not exactly same as
pointer types.
– They declare aliases for object variables and allow
the programmer to use variable by reference.
– Eg, int a;
x=&a;

139
Statements
• A statement in a computer program carries out some
action.
• There are three types of statements are used in C++.
• Simple expression statement:
-consists of any valid C++ expression followed by a
semicolon
-A simple expression statements are used to
evaluate a group of expressions.
x=y;
sum=x+y;

140
Statements
• Compound statement:
– A group of valid C++ expressions placed within a { and }
statement is called a compound statement.

– A compound statement may contain expression statement,


compound statement and control statements.

– The compound statement is not ended with a semicolon


– Eg, {
a=b+c;
x=x*y;
}

141
Statements
• Control statements:
– The control statement is used for the program flow
and to check the conditions of the given expression or
a variable or a constant.

– Decisions and loops can be provided in control


statements.

– The keywords of the control statements are normally


a predefined or reserved words and the programming
may not use them as ordinary variables.
– Eg, if(a>b)
{
……..
………
} 142
Structure of C++ program

143
Structure of C++ program
• It is a common practice to organize a program into
three separate files.

• The class declarations are placed in a header file and


the definitions of the member functions go into
another file.

• This approach enables the programmer to separate the


abstract specification of the interface(class definition)
from the implementation details(member function
definition)
144
Structure of C++ program
• Finally the main program that uses the class is placed
in a third file which “includes” the previous two files as
well as any other files required.

• This approach is based on the concept of client-server


model.

• The class definition including the member functions


constitute the server that provides services to the main
program known as client.

• The client uses the server through the public interface


of the class.
145
Structure of C++ program:Simple statement

#include<iostream.h> //include header file


using namespace std;
void main()
{
cout<<“C++ is better than C \n”;//C++ statement
} //end of exmple

146
Structure of C++ program
• A program starts with preprocessor directives.

• Such statements are preceded with a # symbol to


indicate the presence of a pre-processor directive to
the compiler.

• All C++ programs begin with a #include directive, that


includes the specified header file contents into the
main program.

• (#define is another directive used to replace the


occurrence of identifier in the rest of the code by
replacement)
147
Structure of C++ program
• We have used the following #include directive in the
program.

#include<iostream.h>

• This directive causes the preprocessor to add the


contents of the iostream file to the program.

• iostream file contains the declarations for the


identifiers cin and cout and the identifiers << and >>.

148
Structure of C++ program
• The namespace defines a scope for the identifiers that are
used in a program.

• For using the identifiers defined in the namespace scope,


we must include the using directive, like
using namespace std;

• Here, std is the namespace where ANSI standard libraries


are defined.

• This will bring all the identifiers defined in the std to the
current global scope.

• Using and namespace are the new keywords of C++.


149
Structure of C++ program
• The above example contains only one function main()

• The syntax is
data-type main()

• The data-type will be either void or int mostly.

• The execution starts at main() and ends at main().

• Every C++ program must have a main().

• The data-type int before the main() returns an integer type


value to the operating system.
150
Structure of C++ program
• If the return type is int, every main() in C++ should end with a
return(0) statement, otherwise a warning or an error might occur.

• The default return type is int.

• The data-type void means the main() doesn’t return any value.

• Like C, C++ statements also terminate with semicolon.

• The only statement in the above program is an output statement.

cout<<“C++ is better than C”;

151
Structure of C++ program
• C++ introduces a new comment symbol //(double slash)

• Comments start with a double slash symbol and terminate at the


end of the line.

• A comment may start anywhere in the line, and whatever follows


till the end of the line is ignored.

• There is no closing symbol.

• Double slash comment is basically a single line comment.

• Multiline comments can be written as follows


//This is an example of
//C++ program
152
Structure of C++ program:compound
statement declaration
• Program to find the average of two numbers:
#include<iostream.h>
using namespace std;
int main()
{
float number1, number2, sum, average;
cout<<“Enter two numbers”;
cin>>number1;
cin>>number2;
sum=number1+number2;
average=sum/2;
cout<<“sum= “<<sum<<“\n”;
cout<<“Average= “<<average<<“\n”;
return 0;
}
153
Structure of C++ program:compound
statement declaration
• This program uses four variables number1, number2, sum, and
average.

• They are declared as type float by the statement


float number1,number2,sum,average;

• All variables must be declared before they are used in the program.
• The statement cin>>number1; and
cin>>number2; are input statements and causes
the program to wait for the user to type in two numbers.

• We can also combine these two inputting operations by


cin>>number1>>number2;

154
A Simple C++ program
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<“C++ is better than C \n”;
getch();
}

155
Input output streams
• Every program takes some data as input and
generates processed data as output.

• A stream is a sequence of bytes.

• The source stream that provides data to the


program is called input stream.

• The destination stream that receives output from


the program is called the output stream.

156
Input output streams
• The data in the input stream can come from the
keyboard or another storage device.

• The data in the output stream is sent to an


output device.

• The commonly used streams are.


cin – standard input ,usually keyboard
cout – standard output, usually screen

157
Output operator – cout<<

 The identifier cout is a predefined object


that represents the standard o/p stream
(screen).
 The operator << is called insertion or put to
operator.
 It sends the contents of the variable on its
right to the object on its left.
 The header file iostream should be included
at the beginning of all programs that uses i/o
statements
158
Output using insertion operator

cout “C++ is better


<<
than C”

159
Program to add two numbers
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, b, sum;
cout<<“enter 2 numbers”;
cin>>a;
cin>>b;
sum= a+b;
cout<<“the sum =“<<sum;
getch();
}

160
Input operator – cin>>
 The identifier cin is a predefined object in
C++ that corresponds to standard i/p stream
(keyboard).

 The operator >> is known as extraction or


get from operator.

 It extracts the value from the keyboard and


assigns it to the variable on its right.

161
Input using extraction operator

cin >> a

keyboard

162
Cascading of I/O operators
 The multiple use of << or >> in one
statement is called cascading of I/O
operators
 E.g. :-
cout<<“sum is “<<sum;
cin>>a>>b;

163

Vous aimerez peut-être aussi