Unit - I
Unit - I
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
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.
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.
Converted to
Problem domain Solution domain
Considering the solution, there are two types of people involved as shown below:
Produces Uses
Programmer Solution User
Styles of Programming:
Global Data
Sub Sub
Program Global Data Program
Nested Subprograms
Sub Sub
Program Program
Concepts of OOP:
1. Objects
2. Classes
3. Data abstraction
4. Data Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message Passing
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
- 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.
Properties Data
Entity
Operations Functions
Encapulation :
Is a mechanism that associates the data and code that manipulates the data
and keep them safe from external interference and misuse.
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.
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.
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 :
Applications C++ :
Character set :
Identifiers :
• Every word in C++ program can be either Identifier or Keyword
• Identifier is a name given to Variables, Functions, Constants,
Symbolic constants
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];
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 :
Assignment Operators :
•Assignment Opeartor
•Compound Assignment Operators
Assignment Operator :
= : Assign value to a variable
Syntax :
variable = expression;
Example :
a = 100;
b = z + 10 *a;
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
^
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 :
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
or
data-type(expression);
data-type(variable-name);
Example:
int a,b;
float c;
c=a/b;
c=(float) a/b;
CONSTANTS:
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
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
•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
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
: 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;
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];
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
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.
Reference variable :
alias (alternative name) for a previously declared variable.
After that the 2 names can Provides an be used to access that variable.
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
• 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
{ 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
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