0% found this document useful (0 votes)
1 views26 pages

Unit - I

The document provides an overview of programming paradigms, focusing on the distinction between hardware and software, types of programming languages, and the evolution of programming styles. It discusses object-oriented programming (OOP) concepts such as classes, objects, inheritance, and polymorphism, as well as the advantages of OOP in software development. Additionally, it introduces C++ as an object-oriented programming language, detailing its applications, character set, tokens, data types, and variable management.

Uploaded by

shanthkalai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views26 pages

Unit - I

The document provides an overview of programming paradigms, focusing on the distinction between hardware and software, types of programming languages, and the evolution of programming styles. It discusses object-oriented programming (OOP) concepts such as classes, objects, inheritance, and polymorphism, as well as the advantages of OOP in software development. Additionally, it introduces C++ as an object-oriented programming language, detailing its applications, character set, tokens, data types, and variable management.

Uploaded by

shanthkalai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 26

CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

UNIT I

PROGRAMMING PARADIGM

What is a program?
A sequence of instructions s communicated to the computer to solve a problem,
this sequence of instructions is called program

Why programming languages?


To communicate these instructions with the systems, programming languages are
developed.

What is hardware and software?


Two phases of manufacturing a computer:-
i) First Phase : All the physical devices are manufactured.
Input/output devices, memory devices, Keyboard, CPU are
manufactured and assembled. When the first phase is over –
the machine is physically ready. The physical structures
manufactured at this stage are called the Hardware of the
computer
ii) Second Phase : The hardware part which is physically
available knows nothing about the job. It must be trained.
This type of work is done in during the second phase of
manufacturing. In the second phase some permanent
programs are stored, these programs activate the hardware of
the computer called Software.

Hardware – “Physical Structure of the computer”


Software – “Programs needed for the computer to do jobs”

Types of Software:
iii) Application Software – Set of programs necessary to solve
the problems, written by the user of a computer. (eg – adding
two numbers)
iv) System Software – Written by the computer manufactures
related to that computer mechanisms.(eg – compiler,
interpreter, loader). Set of programs which communicate the
application software to the computer.

Three types of programming Languages:

i) Low Level language:


As a computer does everything in binary form, the programs t be given to
a computer must be given only in a binary form ( 0&1 alone must be
used). This program said to be in machine language.

1 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

ii) High Level language:

Writing low level program is difficult –to overcome this high level
languages were developed. (eg) BASIC, FORTRAN, PASCAL, COBOL,
C.
iii) Assembly Level Language:
Assembly Level Languages uses mnemonic codes
Eg : ADD A,B
Above Statement represents the addition of Value of Accumulator and
value of B register. The resultant contents are stored in Accumulator
itself.

What is problem domain and solution domain?


Solving a problem involves conversion of problem domain or problem
space to solution space.

Converted to
Problem domain Solution domain

The problem is a sector or sectors to which the problem belongs. It is an


area of interest having clearly defined boundaries. It forms an autonomous body
describing its high level features.
The solution domain is defined as the subject matter that is of concern to
the computer system and implementer of the system. It describes the features in a
manner which can be understood by the computer.

Considering the solution, there are two types of people involved as shown below:

Produces Uses
Programmer Solution User

1. Supplier or Implementer or Programmer or Developer


2. User or Client or Customer or End-User.

While solving a problem using a computer, its solution is in the form of a


program. A program is developed using a programming languages are evolved.
Programming languages have also passed through a number of generations as
computers have. Each generation of programming language follows a distinct
style of programming

Styles of Programming:

Each programming language enforces a particular style of programming. The way


of organizing information is influenced by its style of programming and it is
known as programming paradigm.

2 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

First Generation Programming Languages:

 From 1954 – 1958


 It is also called monolithic programming
 It is developed for simple application purpose
 You will have expressions, expressions have operands and operators
 No support for subprograms
 Data is globally available
 Example are : FORTRAN –I , ALGOL 58,Flowmatic

Sequence of statements Global Data


(Program)

Second Generation Programming Languages :

 From 1959 – 1961


 Allows subprograms (functions, procedure, subprograms)
 Partial hiding information(through subprogram)
 Sharing the data by many subprograms breaks the data hiding principle
 Example are : FORTRAN II, ALGOL 60, COBOL

Global Data

SubProgram SubProgram SubProgram

Third Generation Programming Languages:

 From 1962 -1970


 It is also called Structured Programming
 Uses sequential code
 Introduction of scope of variables
 Allows Subprograms

Module 1 Module 2 Module 3

3 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Sub Sub
Program Global Data Program

Nested Subprograms
Sub Sub
Program Program

Local Variables may exist in


the subprograms

Different between Structured Programming and Object Oriented Programming :

S.No Structured Programming Object Oriented Programming


1. Top-down approach Bottom-up approach
2. Focus is on algorithm & Focus is on object model
control flow
3. Program is divided into a no.of Program is organized by having a no.of
sub modules or functions or classes and objects
procedures
4. Functions are independent of Each class is related in a hierarchical
each other manner
5. No designated receiver in the There is a designated receiver for each
function message passing
6. Views data and functions as Views data and functions as a single
two separate entities entity
7. Maintenance is costly Maintenance is relatively cheaper
8. Software reuse is not possible Helps in software reuse
9. Function call is used Message passing is used
10. Function abstraction is used Data abstraction is used
11. Algorithm is given importance Data is given importance
12. Solution is solution-domain Solution is problem-domain specific
specific
13. No encapsulation . Data and Encapsulation packages a\code data
function are separate altogether. Data & functionalities are
put together a single entity
14. Relational between Relational between programmer user is
programmer & program is emphasized
emphasized
15. Data driven technique is used Is driven by delegation of
responsibilities.

BASICS CONCEPTS OF OOP

4 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

OOP is a method of implementation in which programs are organized as co-


operative collections of objects, each of which represents an instance of some class &
whose classes are all members of a hierarchy of classes united through the property called
inheritance.

Concepts of OOP:
1. Objects
2. Classes
3. Data abstraction
4. Data Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message Passing

Classes and objects :

Object is anything having crisply defined conceptual boundaries.


Eg: Book, pen, train, employee etc...
Not an example : Beauty, river, sky etc…

Model is the description of a specifier view of a real world problem domain showing
those ascpets, which are considered to be imported to the observer (user) of the problem
domain.

Object Model is defined by the means of classes and objects. The development of
programs using object model is known as object- oriented development. The software
structure that supports data abstraction is known as class. A class is a datatype capturing
the essence of an abstraction. It is characterized by a no:of features. The class is a
prototype or blueprint or model that defines different features. A feature may be a data or
an operation. Data are represented by instance variables or data variables in a class. The
operations are also known as behaviours or methods or functions. Class is a datatype and
hence it cannot be directly manipulated. It describes a set of objects.

Class Object
1. Class is a datatype 1. Object is an instance of class datatype
2. It generates object 2. It gives life to a class
3. It is the prototype or model 3. It is a container for storing its features
4. It doesn’t occupy memory location 4. It occupies memory location
5. IT can’t be manipulated because it is 5. It can be manipulated
not available in the memory

Instantiation of an object is defined as the process of creating an object of a


particular class
An object has
- States or properties

5 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

- Operations
- Identity
Properties :- Properties maintain the internal state of object
Operations:- Operations provide the appropriate functionality to the object
Identity:- Identity differentiates one object fromt eh other.

The properties of an object are important because the outcome of the functions depends
on these properties. The functions control the properties of an object. They act and react
to messages. The message may cause a change in the property of an object. Thus the
behavior of an object depends on the properties.

Eg: Property - > mark


Operation -> Result
Mark value affects result.

Mapping real world entity to object oriented programming:

Real World Abstraction OOP Class

Properties Data
Entity

Operations Functions

Different styles of representing an object:

Object Name Object Name


Attribute 1 Attribute 1 Oprn1
Operation1
: : OprnN
: : Attr 1
: : :
Operation2
Attribute N Attribute N AttrN
Operation 1
:
: Operation3
Oprn2
Operation N
Oprn – operation, Attr - Attribute

Encapulation :
Is a mechanism that associates the data and code that manipulates the data
and keep them safe from external interference and misuse.

6 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Data Abstraction :
Creating new data types using encapsulated items that are suited to an
application to be programmed is called as data abstraction.
Abstract Data Types(ADT) :
The data types created by data abstraction are called as abstract data
types.
Inheritance :
Is a process of deriving a new class from the existing class without
modifying it.
Advantage :
 Adding new features to the system without modifying the existing one.
 Easy to enhance the system
 Reusability of code.

Differentiate data abstraction and encapsulation.


S.No Data abstraction Encapsulation.
1 Separates interface and Groups related items into one
implementation group
2 Provide access to a specific part Hides the data and the user cannot
of data access the same directly
3 Defined as a data type called Packages data and functionality
class which separates interface and hides the implementation
from implementation details

Polymorphism :
Ability to take more than one form. Two types :
 Compile time polymorphism(Static or Early binding) –Linking done at
compile time. Eg: Function overloading, Operator Overloading
 Runtime Polymorphism(Dynamic or Late binding) - Linking done at
run time.
Eg : Virtual Function

Message Communication :
Objects can communicate(interact) with each other through functions.
Message passing involves specifying the name of an object, name of the
function(message) and information to be sent. It is similar to function call.
Example : student.marks(rollno);
Where student – object marks – message rollno - information
Benefits or advantages or Merits of OOP:
OOP offers several benefits to both the program designer and user.
 Extend the program without modifying the existing one using the concept
of inheritance provides reusability of code.
 The standard library can be extended by users reduces the amount of code
and allow us to build reliable programs.
 Data hiding allow us to build secure programs.
 Easily partitioned a large project into small module and handled easily.

7 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

 Object oriented systems can be easily upgraded from small to large


systems.
 Software complexity can be easily managed.
 Suitable for solving complex problems.
 Easily map the real world problems.
 Software maintenance cost reduced.
 Software quality improved.

Applications of OOP :
The areas make use of OOP are real time systems, Digital Image Processing,
Neural networks, Pattern Recognition, AI and expert systems, Mobile computing,
Parallel Computing, DBMS, Data warehousing and Data Mining, Object oriented
databases.

FUNDAMENTALS OF C++
Introduction :

• Object Oriented Programming Language


• Developed by Bjarne Stroustrup at AT & T Bell Laboratories in the year
1980
• Extension of C
• C with OO concepts
• Called as C with Classes

Applications C++ :

• Able to handle very large programs


• Suitable for developing editors, compilers, databases, communication
systems and complex real world problems.
• Able to map real world problem properly.
• Programs are easily maintainable and expandable.

Character set :

• All Uppercase and Lowercase Alphabets A..Z & a..z


• All digits from 0..9
• Special characters
TOKENS :
In a C++ program the smallest individual units are known as C++ Tokens
Eg : constants, identifiers, keywords, operators, etc.,

Identifiers :
• Every word in C++ program can be either Identifier or Keyword
• Identifier is a name given to Variables, Functions, Constants,
Symbolic constants

8 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

RULES FOR IDENTIFIERS :


• Consists of only letters,digits or underscore
• First character must be an alphabet
• Any length - Only first 31 characters are significant
• Cannot use a keyword
• Must not contain white space
Example :
Sum, avg, total, mark, a, b
Keywords :
• Built in words--- Fixed Meaning ( These meanings can’t be
changed.)
• Written in lowercase letters
Example:
void, case, if, int ,float ,else, while

Data Types :
C++ supports three classes of datatypes:-
 •Primary (or fundamental ) or built-in datatypes
 •Derived datatypes
 User-defined datatypes
Primary (or fundamental ) or built-in datatypes :
int, float, double, char, short int, long int, signed short int, unsigned
short int etc.,
Derived datatypes
• Array
• Function
• Pointer
User-defined datatypes
• Structure
• Union
• Class
• Enumeration
VARIABLES :
 Entity whose value can be changed during program execution.
All variables must be declared before it can be used in the program.
Syntax:
datatype variable name;
Example :
int a,b,sum;
float x;
char c, s[10];

DYNAMIC INITIALIZATION OF VARIABLES:


It is also possible in C++ to declare a variable at the point of their first usage.
Example :

9 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

float avg = sum/n;


for(int i = 0 ; i < 10 ; i++)

OPERATORS
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Increment and Decrement Operators
• Conditional Operator
• Bitwise Operators
• Special Operators

Arithmetic Operators :
+ : Addition
- : Subtraction
* : Multiplication
/ : Division
% : Modulo Division
Example :
x + y, a - b, a * b, f / s, f % s
Relational Operators :
< : Less than
> : Greater than
<= : Less than or equal to
>= : Greater than or equal to
!= : Not equal to
Example :
x < y, a > b, a <= b, f >= s, f != s
Logical Operators :

&& : Logical AND


|| : Logical OR
! : Logical NOT
Example :
a > b && x == 10;
a < b || a < n
!(x >= y)

Assignment Operators :
•Assignment Opeartor
•Compound Assignment Operators
Assignment Operator :
= : Assign value to a variable
Syntax :
variable = expression;

10 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Example :
a = 100;
b = z + 10 *a;

COMPOUND ASSIGNMENT OPERATORS :


Syntax :
variable opeartor = expression/constant
x = x + 10 can be written as x + = 10;
operator : can be any arithmetic, relational, logical operator.
Compound Assignment Operators :
+=, -=, *=, /=, %=, &=, |=, <<=, >>=
Example :
A+=exp; a-=exp; a*=exp;

INCREMENT AND DECREMENT OPERATORS :


Increment Operator : ++
Pre Increment - Eg: ++a
Post Increment – Eg: a++
Example : int a=10, b=10;
a = ++b assigns b = 11, a=11
a= b++ assign a = 10, b=11
Decrement Operator : --
Pre Decrement - Eg: --a
Post Decrement – Eg: a--
CONDITIONAL OPERATOR

Ternary operator pair ?:


Syntax :
exp1 ? exp2 : exp3

True False
Example :
if (a>b)
x=a;
else
x=b;
Can be written as
x=(a>b) ? a : b
BITWISE OPERATORS

Operator Meaning

&
Bitwise AND
|
Bitwise OR

11 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

^
Bitwise exclusive OR
<<
Shift Left
>>
Shift Right
~
One’s complement

SPECIAL OPERATORS :
• Comma operator
• Size of operator
• Pointer operators
• Member selection operator

COMMA OPERATOR :
• Used to link the related expressions together
• Used in for loops and while loops
Example 1: swapping two numbers
t = x, x = y, y = t;
Example 2 :
a = (x=10,y=5,x+y);
Takes value from left to right manner:
1.Assigns 10 to the variable x
2.Assigns 5 to y
3.And finally assigns 15 to the variable a

Sizeof operator :

• Is a compile time operator


• It returns the number of bytes that the operand occupies
• Operand may be a variable, a constant or a datatype
Syntax :
sizeof(data-type);
sizeof(variable);
Example :
M=sizeof(sum) returns 2 if sum is int
N=sizeof(long int) returns 4
a =sizeof(float) returns 4
a =sizeof(double) returns 8
a =sizeof(long double) returns 10

Additional Operators in C++ :


<< - Insertion operator
>> - Extraction operator
:: - Scope resolution operator

12 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

::* - Pointer-to-member declarator


->* - Pointer-to-member operator
.* - Pointer-to-member operator
new - Memory allocation operator
delete - Memory release operator
endl - Line feed operator
setw - Field width operator

Scope resolution operator ::

• Used to access the global variable.


Example :
#include<iostream.h>
int a = 10;
main()
{
int a= 50;
a = a+100;
cout<<a<<endl;
cout<<::a;
}
Output :
150
10

EXPRESSIONS
• Combination of operands and operators
Example :
a*b-c
(m+n)*(x+y)
a*b/c
3*x*x+2*x+1

TYPE CONVERSION :
• Implicit or AutomaticType conversion
• Explicit Type Conversion

Implicit Type conversion :

Compiler performs type conversion of data items when an expression consists of


data items of different data types.

Explicit Type Conversion :


Syntax:
(data-type) expression;
(data-type) variable-name;

13 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

or
data-type(expression);
data-type(variable-name);
Example:
int a,b;
float c;
c=a/b;
c=(float) a/b;

CONSTANTS:

• Fixed values that do not change during the execution of a program.


Types of constants:
•Numeric constants :
1) Integer Constants 2) Real Constants
•Character constants:
1) Single character 2) String constants
NUMERIC CONSTANTS :
INTEGER CONSTANTS: Sequence of digits.
Types of Integer Constants:
Decimal Integer constant: consists of a set of digits.(0 through 9 preceded by an optional
+ or - sign.
Eg : 1234 , -3215, 0, 65872, +77
• Embedded spaces, commas and non digit characters are not permitted between digits.
23,860 23 860 $555 - Not Permitted
Octal Integer Constant:
•Combination of digits (0 through 7 with a leading 0).
Eg : 088 , 0 , 0564, 0115
Hexadecimal Integer Constant:
•Sequence of digits (0 through 9, A through F with a leading 0x,0X)
Eg : 0X3, 0x3, 0XDEF, 0x8E
REAL CONSTANTS
•Numbers containing fractional parts
•These numbers are called real (or floating point) constants.
Eg : 0.0083 -0.78 475.75 +36.0
215. .95 -.71 +.5
Real number may be expressed in exponential (or scientific notation).
Syntax:
mantissa e exponent
•Mantissa- real number expressed in decimal notation (or) an integer.
CHARACTER CONSTANTS
Single character constant:
•contains a single character enclosed within a pair of single quote marks.
Eg : ‘5’ ‘X’ ‘;’ ‘ ‘
‘5’– not the same as 5

14 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

printf(“%d”,’a’);
o/p: 97(ASCII value of a =97)
STRING CONSTANTS:
• Sequence of characters enclosed in double quotes.
• Characters may be letters, numbers, special characters and blank space

Eg : “hai!” “1981” “WELLDONE” “X” “8+7”


“X” (does not have an equivalent integer value) not equal to ‘X’
(have an equivalent integer value)

Enumerated Data Types :


•User defined data type.
•Values ranges over a finite set of identifiers called as enumeration constants.
Syntax :
enum identifier {set of constants};
Example :
enum color {red, blue, green};
color a,b;
b = red; a = blue;
cout << a << b << c; displays 1 0

PREPROCESSOR :
It is a program that processes the source code before it passes through the compiler.
PREPROCESSOR DIRECTIVES:
It is placed in the source program before the main function.
3 CATEGORIES:
• Macro substitution directives
• File Inclusion directives
• Compiler Control directives

MACRO SUBSTITUTION DIRECTIVES


Identifier in the program is replaced by a predefined value(string). Also called
as symbolic constant declaration.
Syntax:
#define identifier(sym. Const. name) value
Example for Simple Macro Substitution
#define PI 3.14
#define NAME “XXX”
#define SUM 2*3-1
Argumented Macro Substitution(Macro function) :
Syntax:
#define identifier(f1, f2,…,fn) string
Example :
#define CUBE(x) (x*x*x)
In program:--
The above example is expanded as

15 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

volume=CUBE(side); --- > (side*side*side)


UNDEFINING A MACRO:
#undef identifier
FILE INCLUSION DIRECTIVES
SYNTAX:
#include <filename>
Searched only in the standard directory.
Example :
#include <iostream.h>
SYNTAX:
#include “filename”
Preprocessor inserts the entire contents of filename into the source code of the
program. Search for the file is made first in the current directory and then in the standard
directories.
Example :
#include “sum.cpp”
Operator Precedence and Associativity
:
Precedence of operator :
• Specifies which operator can be evaluated first.
• Each operator in C++ has a precedence associated with it.
Precedence of arithmetic operators :
High priority * / %
Lower priority + -
Example :
Evaluate x=a-b/3+c*2-1;
Evaluate y=a-b/(3+c)*(2-1);
Evaluate z=a-(b/(3+c)*2)-1;
ASSOCIATIVITY :

•Specifies the direction - (from left to right (or) right to left) in which the expression is
evaluated, while using the particular operator.
•It is also differs from operator to operator.

CONTROL STATEMENTS
BRANCHING STATEMENTS
• If Statement
• If-Else Statement
• Switch Statement
• Goto Statement
• Break Statement
• Continue Statement
LOOPING STATEMENTS
• For Loop
• While Loop
• Do-while Statement

16 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

IF STATEMENT
: used to control the sequence of the execution of statements.
if(test-expression)
statement;
if(test-expression)
{
statement 1;
statement 2;
}
IF-ELSE STATEMENT
: Some actions are performed even though the test expression fails.
if(test-expression) if(test-expression)
{ statement 1;
statement 1; else
statement 2; statement 2;
}
else
{
statement 3;
statement 4;
}
statement 5;
ELSE IF STATEMENTS :
used when there are multiple conditions and different actions to be taken under each
condition. (Multi-way decision)
if(test-expression 1)
statement 1;
else if(test-expression 2)
statement 2;
else if(test-expression 3)
statement 3;
else
statement 4;
FOR LOOP
: It is used to execute statement a fixed number of times.
for(initialization;condition;updation)
statement;
for(initialization;condition;updation)
{
statement 1;
statement2;
}
statement;

WHILE LOOP

17 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

: It is used when the number of iterations to be performed are not known in advance.
while(expression)
{
statement 1;
statement 2;
}
statement;
DO-WHILE LOOP :
It executes the body of a loop atleast once.
do
{
statement 1;
statement 2;
}while(condition);
statement;

BREAK STATEMENT :
It terminates the execution of loop and the control is transferred to the statement
immediately following the loop.
for(i=0;i<20;i++) while(expr)
{ {
…. …..
if(condition) if(condition)
break; break;
…. …..
} }
statement; statement;

SWITCH STATEMENT
: used to replace multiple if-else statement.
switch(test-variable)
{
case v1:
statements;
break;
case v2:
statements;
break;
…..
default :
statements;
break;
}
statement;

18 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

CONTINUE STATEMENT
:It skips the remainder of the current iteration and initiates the execution of the next
iteration.
for(j=0;j<20;j++) while(expr)
{ {
….. …..
if(expr) if(expr)
continue; continue;
…. ….
} }

ARRAYS
-Set of data items of the same datatype under a common name.
-They are popularly known as Subscripted Variable.
Array Definition(Single dimensional Array) :
Syntax: datatype array_name[array_size];
Example:
int age[5];
char name[20];
Accessing Array Elements:
•It can be accessed by using array index or subscript which ranges from 1 to n.
Syntax:
array_name[index];
Example:
int age[5];
cout<<age[1];
Note: There is no array bound validation
Array Initialization – at Definition
Syntax:
datatype array_name[size]={list of values separated by comma};
Example:
int age[5]={10,1,50,20,11};
int age[]={10,1,50,20,11};
Array Initialization – Not in Definition
-using For loop ,while or do-while loop
Example:
int age[5];
for(int i=1;i<=5;i++)
cin>>a[i];
Two Dimensional Arrays
Syntax:
array_name[row_index][column_index];
Example:
int a[3][3];
cout<<a[2][0];

19 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Initialization at Definition
Syntax
datatype array_name[row_size][col_size]={
{elements of first row},
{elements of second row},
……….,
{elements of Nth row}
};

STRINGS
It is represented as an array of characters and the end of the string is
marked by the NULL (‘\0’) character.
String constants : Are enclosed by double quotes.
Eg. cout<<“Welcome to SIT”;
STRING DECLARATION :
Syntax
char array_name[size];
Example:
char name[30];
cin>>name;
String Initialization:
Syntax:
char array_name[size]=“string”;
Example:
char month[10] = “April”;
STRING MANIPULATIONS
#include<string.h>
-strlen(string_variable);
-strcat(string_variable1,string_variable2);
-strcpy(string_variable1,string_variable2);
-strcmp(string_variable1,string_variable2);
-strlwr(string_variable);
-strupr(string_variable);
Examples:
char name[20]=“ramu”;
cout<<strlen(name);
char name[20]=“rama”;last[20]=“chandran”;
int i;
cout<<strcat(name,last);
cout<<strcpy(name,last);
i=strcmp(name,last);
cout<<strupr(name)<<strlwr(name);

MANIPULATORS

20 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Manipulators are operators used to format the output display. To include the file
#include<iomanip> to use manipulators in the program. The manipulators are“\
n” and “\t”, endl ,setw(),setbase(), setfill(), setprecision(), flush()
Endl : Used to feed one line.
Example : int a = 123, m = 21, n = 3; cout << a << endl << m << endl << n;
Output :
123
21
3
Setw(): Used to set the field width and used to display the output in right
alignment form.
Example : int a = 123, m = 21, n = 3;
cout << setw(5) << a << endl << setw(5) <<m << setw(5) << endl << n;
Output :
123
21
3
setbase() : Used to set the base.
Example : int value = 15; cout << setbase(10) << value << endl;
cout << setbase(8) << value << endl; cout << setbase(16) << value << endl;
Output :
15
17
f
setfill() : Used to fill the unused space created using setw() with specified
character.
Example : int a = 123, m = 21, n = 3; cout << setfill(‘*’);
cout << setw(5) << a << endl << setw(5) <<m << setw(5) << endl << n;
Output :
**123
***21
****3
setprecision() : Used to control the no. of digits after decimal point.

Example : float a=12.3456; cout << a << endl;


cout << setprecision(2) << a << endl; cout << a;
Output :
12.3456
12.35
12.35
flush() : Used to empty the output buffer.
Syntax : cout.flush();

Reference variable :
 alias (alternative name) for a previously declared variable.
 After that the 2 names can Provides an be used to access that variable.

21 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Syntax : data-type var.name;


data-type & ref-name = var.name;
Example :
float total = 100;
float & sum = total; à sum and total = 100
total = total + 50; à sum and total = 150
sum = 0; à sum and total = 0
Need :
 Reduces the complexity of using pointer variable.
 Do the same function but not access the address.

FUNCTIONS
Elements of Function :
1. Function Prototype
2. Function Parameters
3. Function Definition
4. Function Call
5. return statement
Function Prototypes:
•Additional feature added to C++
•It provides the following information to the complier.
1.The name of the function
2.The type of the value returned by the function
3.The no. and type of arguments passed to the function
•When the function call is encountered, the complier checks the function call with
its prototype to ensure that correct arguments are used if not then the compiler informs
the user about that.
Syntax :
ret. type fun.name(arg1, arg2,...argn);
Example :
Function Prototype :
float volume (int, float);
Function Definition :
float volume (int x, float y)
{ float a;
body of the function;
return a;
}
Function call :
void main
{ L = volume(m,n);}

Parameter Passing
• Pass by Value

22 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

• Pass by Address

Pass by Reference
Pass by Value

•Updation of an argument within the function not affect the main function
Example :
float volume (int, float); //Fn prototype
float volume (int x, float y) //Fn definition
{
float a;
a = x * y;
x= x + 10; y = y + 100;
cout<<x<<y;
return a;
}
void main
{ int m =1, n = 2;
L = volume(m,n); //Function call
cout <<m<<n; }
Pass by Address

•Passing address instead of value then the updation of an argument within the
function affect the main function also.
Example :
float volume (int *, float *); //Fn prototype
float volume (int *x, float *y) //Fn definition
{ float a;
a = *x * *y;
*x= *x + 10; *y = *y + 100;
cout<<*x<<*y;
return a;
}
void main
{ int m =1, n = 2;
L = volume(&m,&n); //Function call
cout <<m<<n; }

Pass by Reference

•updation of an argument within the function affect the main function also because
instead passing address only value can be passed but we create a reference to that
variable in the function
Example :
float volume (int & , float & ); //Fn prototype
float volume (int &x, float &y) //Fn definition

23 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

{ float a; a = x * y;
x= x + 10; y = y + 100;
cout<<x<<y;
return a; }
void main
{ int m =1, n = 2;
L = volume(m,n); //Function call
cout <<m<<n; }

Disadv of function:
•When the program executes the function call instruction the CPU stores the
address of the instruction following the function call, copies the arguments of the
function call onto the stack and finally transfers control to the specified function.
•The CPU then executes the function and stores the returned value in the predefined
memory address and returns control to the calling function.
•It is a overhead in the execution time of the program
•Sometimes the execution of program takes lesser time than the context switch
time..

INLINE FUNCTIONS

• C++ provide a alternative in the form of Inline functions.


• Inline functions are those whose function body is inserted in place of the function
call statement during the compilation process. There is no context switch
overhead.
• Similar to macro of C.
Disadv of macro : They are not functions then usual error checking does not occur
during compilation
•Inline function enjoy both the flexibility and power offered by normal functions and
macro functions.
Syntax :
inline ret.type fun.name(arguments)
{
Body of the function
};
Example :
//To multiply two numbers
#include<iostream.h>
inline float mul(float x, float y)
{
return(x*y);
}
void main()
{
float a,b;
cout<<“Enter 2 numbers”;

24 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

cin>>a>>b;
cout<<a<<“ *“<<b<<“=“<<mul(a,b)<<endl;
cout<< “100 * 15 =“<<mul(100,15)<<endl;
}

Output :
Enter 2 numbers 5 3
5*3=15
100*15=1500

DEFAULT ARGUMENTS
•C++ allow us to call the function without specifying all the arguments defined in
the function prototype.
•The compiler assigns a default value to the argument which does not have a
matching argument in the function call.
•The default values are specified in the function prototype.
Example :
float amount (float p, int n, float rate= 0.15);
Function call – amount(5000,7);
Substitute p=5000,n=7,rate=0.15
Function call - amount(4500,10,0.12);
Substitute p=4500,n =10, rate=0.12
RULES
• Only the trailing arguments can have default values.
• We must add defaults from right to left.
Example :
int mul(int i,int j=5,int k=10); //legal
int mul(int j=5,int k); //illegal
int mul(int i=0,int j,int k=10); //illegal
int mul(int i=2,int j=5,int k=10); //legal
Structure of a C++ program :

Include Files

Class Declarations

Member Function Definitions

Main Function Program


The 4 sections may be placed in separate or same file.
• Organize the program into 3 separate files
1. Class Declarations
2. Member Function Declarations
3. The main function which includes previous 2 files.
Advantage :
• Abstracts the implementation details from other users.

25 Prepared By Ms. J.Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

• Resembles client-server model

Member Function

Class Definition Server

Main Function Client

Different phases of C++ program execution.


 Creating a Program
 Compiling a Program
 Linking the program with functions that are needed from the C++ library
 Executing the program

26 Prepared By Ms. J.Rajesh Pushpa

You might also like