UNIT-I
Constants:
Ø Constants in c refer to fixed values that
do not during the execution of a program.
Ø C supports several types of constants as
illustrated
constants is two types> Numeric constants
> character constants
Numeric constants is two types
> integer constants
> Real constants
character constants is two types
> Single character
> String character
Variables:
Ø
A
variable is a name that may be used to store a data value. Unlike constant,
variables are
changeable.
Ø
We can
change value of a variable during execution of a program. A programmer can
choose a
meaningful variable name.
Example:
average, height, age, total etc
Rules to define
variable name:
Ø
Variable name must be up to 8 characters.
Ø
Variable name must not start with a digit.
Ø
Variable
name can consist of alphabets, digits and special symbols like underscore _.
Ø
Blank or
spaces are not allowed in variable name.
Ø
Keywords
are not allowed as variable name.
Data
types:
Ø
Data
types specify how we enter data into our programs and what type of data we
enter.
Ø
C
language has some predefined set of data types to handle various kinds of data
that we use in
our program.
Ø
C
language supports 2 different type of data types,
Primary data types:
Ø These are fundamental data types in C
namely integer (int), floating(float), character(char)
And
void.
Derived data
types:
Ø Derived data types are like arrays,
functions, structures and pointers. These are discussed in
detail later.
Integer type:
Ø Integers are used to store whole numbers
.
Ø Size and range of Integer type on 16-bit
machine.
Type
|
Size
(bytes)
|
Range
|
Int
or signed int
|
2
|
32,768
to 32767
|
Unsigned
int
|
2
|
0
to 65535
|
Short
int or signed short int
|
1
|
-128
to 127
|
Long
int or signed long int
|
4
|
-2,147,648
to 2,147,483,647
|
Unsigned long int
|
4
|
0 to 4,294,967,295
|
Floating type:
Ø Floating types are used to store real
numbers.
Ø Size and range of Integer type on 16-bit
machine.
Type
|
Size
(bytes)
|
Range
|
Float
|
4
|
3.4E-38
to 3.4E+38
|
double
|
8
|
1.7E-3.08
to 1.7E+3.08
|
Long
double
|
10
|
3.4E-4932
to 1.1E+4932
|
Character
type:
Ø Character types are used to store
characters value.
Ø Size and range of Integer type on 16-bit
machine.
Type
|
Size
(bytes)
|
range
|
Char
or signed char
|
1
|
-128
to 127
|
Unsigned
char
|
1
|
0
to 255
|
Void type:
Ø Void type means no value. This is usually
used to specify the type of functions.
Managing input and output operations:
Ø
C
programming language provides many of the built-in functions to read given
input and write
data on screen, printer or in any file.
Scanf () and printf () functions:
#include< stdio.h>
#include< conio.h>
void main()
{
int
i;
Printf
("Enter a value");
Scanf
("%d",&i);
Printf
( "\n You entered: %d",i);
Getch
();
}
Ø When you will compile the above code, it
will ask you to enter a value. When you will enter the
value, it will display
the value you have entered.
NOTE:
printf () function returns the
number of characters printed by it, and scanf ()
returns the number of characters read by it
Int i = printf
("study tonight");
get char() & put char() functions:
Ø
The get
char () function reads a character from the terminal and returns it as an
integer.
This function reads only single character at a time.
Ø
You can
use this method in the loop in case you want to read more than one characters.
Ø
The put
char () function prints the character passed to it on the screen and returns
the same
character.
Ø This function puts only single character at
a time. In case you want to display more than one
characters, use put char ()
method in the loop.
#include < stdio.h>
#include < conio.h>
Void main ( )
{
Int
c;
Printf ("Enter a character");
c=get char ();
Put
char(c);
getch ();
}
Ø When you will compile the above code, it
will ask you to enter a value. When you will enter the
value, it will display
the value you have entered.
gets() & puts() functions:
Ø
The gets
() function reads a line from stdin into the buffer pointed to by s until
either a
terminating new line or EOF (end of file).
Ø
The puts
() function writes the string s and a trailing newline to STD out.
#include< stdio.h>
#include< conio.h>
Void main ()
{
Char
str[100];
Printf ("Enter a string");
Gets
(str );
Puts
(str );
Getch ();
}
Ø When you will compile the above code, it
will ask you to enter a string. When you will enter the
string, it will display
the value you have entered.
Operators in C Language:
Ø
C
language supports a rich set of built-in operators. An operator is a symbol
that tells the
compiler to perform certain mathematical or logical
manipulations.
Ø
Operators
are used in program to manipulate data and variables.
Ø C operators can be classified into
following types.
Arithmetic operators:
Ø
C
supports all the basic arithmetic operators. The following table shows all the
basic
arithmetic operators.
OPERATOR
|
DESCRIPTION
|
+
|
Adds
two operands
|
-
|
Substract
second operands from first
|
*
|
Multiply
two operand
|
/
|
Divide
numerator by denumerator
|
%
|
Remainder
of division
|
++
|
Increment
operator increases integer value by one
|
--
|
Decrement
operator decreases integer value by one
|
Relation operators:
Ø
The
following table shows all relation operators supported by C.
Operator
|
Description
|
==
|
Check if
two operand are equal
|
!=
|
Check if
two operand are not equal
|
>
|
Check if operand on the left is greater than
operand on the right
|
<
|
Check operand on the left is smaller than right operand
|
>=
|
Check left
operand Is greater than or equal to right operand
|
<=
|
Check if
operand on left Is similar than or equal to right operand
|
Logical operators:
Ø
C
language supports following 3 logical operators. Suppose a=1 and b=0,
operator
|
Description
|
Example
|
&&
|
Logical
and
|
(a
&& b) is false
|
||
|
Logical
or
|
(
a || b) is true
|
!
|
Logical
not
|
(!a
) is false
|
Bitwise operators:
Ø
Bitwise
operators perform manipulations of data at bit level. These operators also
perform
shifting of bits from right to left.
Ø Bitwise operators are not applied to float
or double.
Operator
|
Description
|
&
|
Bitwise
and
|
|
|
Bitwise
or
|
^
|
Bitwise
exclusive or
|
<<
|
Left
shift
|
>>
|
Right
shift
|
Conditional operator:
Ø It is also known as ternary operator and
used to evaluate conditional expression.
Ø
epr1?
expr2 : expr3.
Ø If epr1 Condition is true ? Then value
expr2 : Otherwise value expr3.
Operator
|
Description
|
Example
|
Size of
|
Returns the size of an variable
|
Size of (x) return size of
variable x
|
&
|
Return the address of an
variable
|
&x: return address of the
variable x
|
*
|
Pointer to a variable
|
*x: will be pointer to a
variable x
|
Decision making in C:
Ø
Decision
making is about deciding the order of execution of statements based on certain
conditions or repeat a group of statements until certain specified conditions
are met.
Ø C language handles decision-making by
supporting the following statements,
if statement
Switch statement
conditional operator statement
goto statement
Decision making with if statement:
Ø
The if statement may be implemented in different
forms depending on the complexity of
conditions to be tested.
Ø
The
different forms are,
Simple if statement
If....else statement
Nested if....else statement
Else
if statement
Simple if statement:
Ø
The
general form of a simple if statement is,
SY:
if(
expression )
{
statement-inside;
}
Statement-outside;
Ø
If the
expression is true, then 'statement-inside' it will be executed, otherwise
'statement-inside'
is skipped and only 'statement-outside' is executed.
Example:
#include< stdio.h>
Void main ( )
{
int
x,y;
x=15;
y=13;
if (x
> y )
{
printf("x is greater than y");
}
}
Output: x is greater than y
if...else statement:
Ø
The
general form of a simple if...else statement is,
SY:
if( expression )
{
statement-block1;
}
else
{
statement-block2;
}
Example :
#include< stdio.h>
void main( )
{
int
x,y;
x=15;
y=18;
if
(x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
Output:y is greater than x
Nested if....else statement:
Ø The general form of a nested if...else
statement is
SY:
if( expression )
{
if(
expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{
statement-block 3;
}
Ø if 'expression' is false the
'statement-block3' will be executed, otherwise it continues to perform
the test
for 'expression 1' . If the 'expression 1' is true the 'statement-block1' is
executed otherwise
'statement-block2' is executed.
Example:
#include< stdio.h>
#include< conio.h>
void main( )
{
int
a,b,c;
clrscr();
printf("enter 3 number");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(
a > c)
{
printf("a is greatest");
}
else
{
printf("c is greatest");
}
}
else
{
if(
b> c)
{
printf("b is greatest");
}
else
{
printf("c is greatest");
}
}
getch();
}
else-if ladder:
Ø The general form of else-if ladder
is,if(expression 1)
SY:
#include<stdio.h>
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;
Ø
The
expression is tested from the top(of the ladder) downwards. As soon as the true
condition is
found, the statement associated with it is executed.
Ø
Example :
#include< stdio.h>
#include< conio.h>
void main( )
{
int
a;
printf("enter a number");
scanf("%d",&a);
if(
a%5==0 && a%8==0)
{
printf("divisible by both 5 and 8");
}
else
if( a%8==0 )
{
printf("divisible by 8");
}
else
if(a%5==0)
{
printf("divisible by 5");
}
else
{
printf("divisible by none");
}
getch();
}
Switch statement:
Ø
Switch
statement is used to solve multiple option type problems for menu like program,
where
one value is associated with each option.
Ø The expression in switch case evaluates to
return an integral value, which is then compared to
the values in different
cases, where it matches that block of code is executed, if there is no match,
then default block is executed.
The general form of switch statement is,
Sy:
switch(expression)
{
case
value-1:
block-1;
break;
case
value-2:
block-2;
break;
case
value-3:
block-3;
break;
case
value-4:
block-4;
break;
default:
default-block;
break;
}
Example:
#include<stdio.h>
main()
{
int i = 1;
switch(i)
{
case
1:
printf("A"); // No break
case
2:
printf("B"); // No break
case
3:
printf("C");
break;
}
Output: A B C
Looping in c:
Ø
In any
programming language, loops are used to execute a set of statements repeatedly
until a
particular condition is satisfied.
Ø
A
sequence of statement is executed until a specified condition is true. This
sequence of
statement to be executed is kept inside the curly braces { } known
as loop body.
Ø
After
every execution of loop body condition is checked, and if it is found to be
true the loop
body is executed again.
Ø When condition check comes out to be false,
the loop body will not be executed.
How it works:
There are 3 type of loops in c language
1. while loop
2. for loop
3. do-while loop
while loop:
Ø
while
loop can be address as an entry control loop. It is completed in 3 steps.
Variable initialization.( e.g int x=0; )
condition( e.g while( x<=10) )
Variable increment or decrement ( x++ or
x-- or x=x+2 )
Syntax:
variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}
Example:
#include< stdio.h>
#include< conio.h>
void main( )
{
int
x;
x=1;
while(x<=10)
{
printf("%d\t", x);
x++;
}
getch();
}
Output : 1 2 3 4 5 6 7 8 9 10
for loop:
Ø for loop is used to execute a set of
statement repeatedly until a particular condition is satisfied.
we can say it
an open ended loop. General format is,
sy:
for(initialization; condition ;
increment/decrement)
{
statement-block;
}
Ø
In for loop
we have exactly two semicolons, one after initialization and second after
condition.
Ø In this loop we can have more than one
initialization or increment/decrement, separated using
comma operator. for loop
can have only one condition.
Example:
#include< stdio.h>
#include< conio.h>
void main( )
{
int
x;
for(x=0; x<=10; x++)
{
printf("%d\t",x);
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
do while loop:
Ø
In some
situations it is necessary to execute body of the loop before testing the
condition.
Ø Such situations can be handled with the
help of do-while loop. do statement evaluates the body of
the loop first and at
the end, the condition is checked using while statement.
General format of do-while loop is
do
{
....
.....
}
while(condition)
Example:
#include< stdio.h>
#include< conio.h>
void main()
{
int
a,i;
a=5;
i=1;
do
{
printf("%d\t",a*i);
i++;
}
while(i<=10);
getch();
}
output
5 10 15 20 25 30 35 40 45 50
Break statement:
Ø When break statement is encountered inside
a loop, the loop is immediately exited and the
program continues with the
statement immediately following the loop.
continue statement:
Ø It causes the control to go directly to the
test-condition and then continue the loop process.
On encountering continue,
cursor leave the current cycle of loop, and starts with the next cycle.
Unions in C
Language:
UNIT-II
ARRAYS:
Ø
An array is a group of related data items that
share a common name. for instance we can define an array name salary to
represent to set of salaries of a group of employs.
Ø
A
particular value is indicated by writing a number is called index number of
subscript in brackets after the array name.
For Example :
Salary [10];
Represents
the salary of the 10th employee
Ø
When the
complete set of values is referred to as an array the individual values are
called elements array can be of any variable type.
Types of Arrays:
Ø
They are
three types of arrays
o Single dimensional array
o Two dimensional array
o Multi dimensional array
Single dimensional array:
Ø
One
dimensional array at least of items can be given one variable name using only
one subscripit and such a variable is called one dimensional array (or) single
subscripted variable
For example:
Int
num [10];
Declaration of
arrays:
Ø
Like any
other variable array must be declared before they are used, they general form
array declaration is
Sy:
Type variable
name [size]
|
Inclization of array:
Ø
We can
inclize the elements of array in the same way as the ordinary variables when
they declare, they general form of inclization of array is
Sy:
Type
name [size]={ least of values};
|
Two dimensional
array:
Ø
In two
dimensional the array represented as rows and columns of a table or matrix representation form.
Ø
C allows
to us defined as table of items by using two dimensional array’s
Two dimensional
array’s as declared as follows:
Type array name [row size],[column size];
|
Inclization of two dimensional array:
Ø
Like the
one dimensional array two dimensional array may be araised by the following their declaration list of
values enclosed in brasses.
For example:
Int
table [2][3]={ (0,0)(1,1,1)};
Multi
dimensional array’s:
Ø
C allows
array’s of three or more dimensions, the general form of multi dimensional
array is
Sy:
Type array name [s1] [s2]
[s3]---------------[sn];
|
Ø
Where si
is the size of the itha dimension
For
example:
Int name [s1][s2][s3];
Example program of array’s:
#include< stdio.h>
#include< conio.h>
void main()
{
int
arr[3][4];
int
i,j,k;
printf("Enter array element");
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
printf("%d",arr[i][j]);
}
}
getch();
}
String handle
functions:
Ø
A string
is an array any group of characters defined between double quotient marks is a
constant string.
For example of string:
“WELCOME TO C.LANGUAGE”
Declaring
inclizing string variables:
Ø
A string
variable is an valued c variable name
and is always declared as an array .
The general form
of declaration of a string variable is :
Char name[size];
|
Ø
The size
the determines of number of characters in the string name.
Ø
When the
complier assumes a character string to a character array’s it automatically
supplies a (null character)(‘/o’) at the end of string.
Ø
Characters
array’s may be inclinzed when they are declared.
Ø
C permits
a character array to be inclinzed in either of the following two forms.
Char city [4]=”NEW YORK”;
Char city
[4]=[‘N’,’E’,’W’,’Y’,’O’,’R’,’K’];
READING STRINGS
FOR TERMINAL:
Ø
The input
functions scanf can be used with %s format specification to read in the string
of characters.
For
example:
#include<string.h>
Main()
{
Char
name[5];
Printf(“enter
the name”);
Scanf(“%s”,
& name);
Name=%s
name;
}
Writing strings
to screen:
Ø
We have
used the printf function with %s format to print strings to be screen. the format %s can be used to display an array of
characters that is terminated by the null character.
For example:
Printf(“name=%s/n”,name);
“City
[8]=Kurnool”
Printf(“district=%s/n
city”);
String Handling Functions:
Ø
C
language supports a large number of string handling functions that can be used
to carry out many of the string manipulations.
Ø
These
functions are packaged in string.h library. Hence, you must include string.h
header file in your program to use these functions.
Ø
The
following are the most commonly used string handling functions.
Method
|
description
|
Strcat()
|
It
is used to concatenate (combine) two string
|
Strlen()
|
It
is used to show length of the string
|
Strrev()
|
It
is used to show reverse of a string
|
Strcpy()
|
Copies
one string in to another
|
Strcmp()
|
It
is used to compare two string
|
Strcat () function:
Ø
Strcat
("hello”, “world");
Ø
Strcat ()
function will add the string "world" to "hello".
strlen() function:
Ø
strlen()
function will return the length of the string passed to it.
Ex: Int
j;
j=strlen("studytonight");
printf("%d",j);
output :
12
strcmp() function:
Ø
strcmp()
function will return the ASCII difference between first un matching character
of two strings.
Ex: int
j;
j=strcmp ("study”, “tonight");
Printf ("%d",j);
Output:
-1
FUNCTIONS:
Ø
A
function is a block of code that performs a particular task. There are times
when we need to write a particular block of code for more than once in our
program.
Ø
This may
lead to bugs and irritation for the programmer. C-language provides an approach
in which you need to declare and define a group of statements once and that can
be called and used whenever required.
Ø
This
saves both time and space. C functions can be classified into two categories,
·
Library
functions
·
User-defined
function
LIBRARY
FUNCTIONS:
Ø
Library
functions are those functions which are defined by C library, example printf(),
scanf(), strcat() etc.
Ø
You just
need to include appropriate header files to use these functions. These are
already declared and defined in C libraries.
USER DEFINED FUNCTIONS:
Ø
User-defined
functions are those functions which are defined by the user at the time of writing
program.
Ø
Functions
are made for code reusability and for saving time and space.
Benefits of
Using Functions:
Ø
It
provides modularity to the program.
Ø
Easy code Reusability. You just have to call
the function by its name to use it.
Ø
In case of large programs with thousands of
code lines, debugging and editing becomes easier if you use functions.
Form of c
–functions:
·
All
functions have the form
Sy:
Function
name (argument list)
Argument declaration;
{
Local variable declaration
Executable statement
Return
(expression);
}
return-type:
Ø
Return
type specifies the type of value (int,float,char,double) that function is
expected to return to the program calling the function.
function-name:
Ø
Function
name specifies the name of the function. The function name is any valid C
identifier and therefore must follow the same rule of formation as other
variables in C.
parameter-list:
Ø
The
parameter list declares the variables that will receive the data sent by
calling program. They often referred to as formal parameters. These parameters
are also used to send values to calling program.
Types of
Function calls in C:
Ø
Functions
are called by their names. If the function is without argument, it can be
called directly using its name. But for functions with arguments, we have two
ways to call them,
·
Call by
Value
·
Call by Reference
Call by Value:
Ø
In this
calling technique we pass the values of arguments which are stored or copied
into the formal parameters of functions.
Ø
Hence,
the original values are unchanged only the parameters inside function changes.
void calc(int x);
int main()
{
int x = 10;
calc(x);
printf("%d", x);
}
void calc(int x)
{
x = x + 10 ;
}
Output : 10
Call by
Reference:
Ø
In this
we pass the address of the variable as arguments. In this case the formal
parameter can be taken as a reference or a pointer, in both the case they will
change the values of the original variable.
void calc(int *p);
int main()
{
int x = 10;
calc(&x); // passing address of x as
argument
printf("%d", x);
}
void calc(int *p)
{
*p = *p + 10;
}
Output : 20
Category of
functions:
v
Functions
with no arguments and no return values.
v
Functions
with arguments and no return values.
v
Functions
with arguments and return values.
Recursion:
Ø
When a called
function in terms calls another function a process of chaning occurs.
Ø
Recursion
is a special case of process when a function call itself repeatedly until some
specified condition is satisfied.
Example:
Factorial (n);
Int n;
{
Int fact;
If n==1;
Return 1;
Else
Fact=n*!(n-1);
Return fact;
}
Structures and
unions:
Ø
Structure
is a user-defined data type in C which allows you to combine different data
types to store a particular type of record.
Ø
Structure
helps to construct a complex data type in more meaningful way. It is somewhat
similar to an Array.
Ø
The only
difference is that array is used to store collection of similar data types while
structure can store collection of any type of data.
Defining a
structure:
Ø
struct
keyword is used to define a structure. struct define a new data type which is a
collection of different type of data.
Syntax:
struct structure name
{
//Statements
}
Example of
Structure:
struct Book
{
char name[15];
int price;
int pages;
};
Declaring
Structure Variables:
Ø
It is
possible to declare variables of a structure, after the structure is defined.
Structure variable declaration is similar to the declaration of variables of
any other data types. Structure variables can be declared in following two
ways.
Declaring
Structure variables separately:
Struct Student
{
Char [20] name;
Int age;
Int roll no;
} ;
Declaring Structure Variables with Structure definition:
struct Student
{
Char [20] name;
int age;
int roll no;
} S1, S2 ;
Ø
Unions
are conceptually similar to structures. The syntax of union is also similar to
that of structure. The only differences are in terms of storage.
Ø
In
structure each member has its own storage location, whereas all members of
union uses a single shared memory location which is equal to the size of its
largest data member.
Ø
This
implies that although a union may contain many members of different types, it
cannot handle all the members at same time. A union is declared using union
keyword.
union item
{
int m;
float x;
char c;
} It1;
Complete Example for Union:
#include <
stdio.h>
#include <
conio.h>
union item
{
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch='z';
clrscr();
printf("%d\n",it.a);
printf("%f\n",it.b);
printf("%c\n",it.ch);
getch();
return 0;
}
Out put :
-26426
20.1999
UNIT-III
Object Oriented
Programming:
Ø
Object
Oriented programming is a programming style that is associated with the concept
of OBJECTS, having data fields and related member functions.
Features of
object oriented programming:
Ø
Emphasis
is on data rather than procedure.
Ø
Programs
are divided into what are known as objects.
Ø
Data
structures are designed such that they characterize the objects.
Ø
Functions
that operate on the data of an object are tied together in the data structure.
Ø
Data is
hidden and cannot be accessed by external functions.
Ø
Objects
may communicate with each other through functions.
Ø
New data
and functions can be easily added whenever necessary.
Principles of
object oriented programming:
Ø
Now, let
us discuss some of the main features of object oriented programming which you
will be using in C++.
v Objects
v Classes
v Abstraction
v Encapsulation
v Inheritance
v Overloading
v Exception Handling
Objects:
Ø
Objects
are the basic unit of OOP. They are instances of class, which have data members
and use various member functions to perform tasks.
Classes:
Ø
It is similar
to structures in C language. Class can also be defined as user defined data
type but it also contains functions in it.
Ø
So, class
is basically a blueprint for object. It declare & defines what data
variables the object will have and what operations can be performed on the
class's object.
Abstraction:
Ø
Abstraction
refers to showing only the essential features of the application and hiding the
details.
Ø
C++,
classes provide methods to the outside world to access & use the data
variables, but the variables are hidden from direct access.
Encapsulation:
Ø
It can
also be said data binding. Encapsulation is all about binding the data
variables and functions together in class.
Inheritance:
Ø
Inheritance
is a way to reuse once written code again and again. The class which is
inherited is called base calls & the class which inherits is called derived
class.
Ø
So when,
a derived class inherits a base class, the derived class can use all the
functions which are defined in base class, hence making code reusable.
Polymorphism:
Ø
Polymorphism
makes the code more readable. It is a features, which lets is create functions
with same name but different arguments, which will perform differently. That is
function with same name, functioning in different.
Overloading:
Ø
Overloading
is a part of polymorphism. Where a function or operator is made & defined
many times, to perform different functions they are said to be overloaded.
Exception
Handling:
Ø
Exception
handling is a feature of OOP, to handle unresolved exceptions or errors
produced at runtime.
Benefits of
object oriented programming:
Ø
Through
inheritance we can eliminate redundant code and extend the use of existing
classes.
Ø
We can
build programs from the standard working modules that communicate with one another, rather than having to start
writing the code from scratch.
Ø
The
principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other parts of the program.
Ø
It is
possible to have multiple instances of an object to co-exist without any
interference.
Ø
It is
possible to map objects in the problem domain to those in the program.
Ø
It is easy to partition the work in a project
based on objects.
Ø
The data
centered design approach enables us to capture more details of a model in implementable
form.
Ø
Software
complexity can be easily managed.
Difference
between c-language & c++ language:
Procedural/structured
programming (c-language)
Ø
A procedural program consists of instructions in
groups known as functions.
Ø
High
level languages like fortan, pascal and c are commonly known as procedural
programming languages.
Ø
Programs
are organized in the form of subroutines and the data items are freely
accessible.
Ø
Data in
procedural language is open and can be accessed by any function.
Ø
Function overloading
and operator overloading are not possible in procedural language.
Ø
In
procedural languages local variable can be declared only at the beginning of
the block.
Ø
Program
controls are through jumps and calls to subroutines.
Ø
Polymorphism,
encapsulation and inheritance are not possible in procedural languages.
Ø
For
sloving the problems each module in procedure oriented language is a sub
program.
Ø
Data
abstraction property is not supported by procedural languages.
Object oriented
programming (c ++):
Ø
Oop’s
allows to decompose a problem into a number of entites called objects and then
builds the data and functions around these objects.
Ø
Organization
of data and functions in oop.
Ø
Programs
are designed around the data being operated rather than the operations themselves.
Ø
Data in
oop is hidden and can be accessed by member functions only.
Ø
Oop
extends the meaning of normally used operations by defining them for user
defined functions through the concept of function overloading and operator
overloading.
Ø
Oop
supports polymorphism, encapsulation and inheritance concepts.
Ø
For solving the problems. The problem is
divided in to number of modules. These modules are a logical collection of
classes and objects.
Ø
Oop
supports data abstraction.
Functions in c++:
Inline functions:
Ø
Inline
functions are those whose function body is inserted in place of the function
call statement during the compilation process.
Ø
Within
the inline code, the program will no incur any context switching over head.
Ø
The concept
of inline function is similar to macro functions in c.
Ø
An inline
function definition is similar to an ordinary function except that the keyword
inline precedes the function definition.
Ø
The
significant feature of inline function is, there is no explicit function call
and body is substituted at the point of inline function call, thereby,the
run-time overhead for function linkage mechanism is reduced.
Example program
for inline function:
#include<iostream.h>
Inline
intsquare(int num)
{
Return num*num;
}
Void main()
{
Float n;
Cout<<”enter
a number:”;
Cin>>n;
Cout<<”square
is”<<square(n)<<endl;
Cout<<”square(10)=”<<square(10);
}
Function
overloading:
Ø
Function
overloading is a concept that allows multiple functions to share the same name
with different argument types.
Ø
Assigning
one or more function body to the same name is known as function overloading or
function name overloading.
Friend functions
and friend classes:
Ø
The
concept of encapsulation and data hiding that non-member function should not be
allowed to access and object private and protected members.
Ø
Using
friend function or friend class a non member function can be able to access
private data members.
Ø
A
function declaration must be prefixed by the keyword friend whereas the
function definition must not.
Special
characteristics of friend function:
Ø
The scope
of a friend function is not limited to the class in which it has been declared
as a friend.
Ø
A friend
function cannot be called using the object of that class; it is not in the
scope of the class. it can be invoked like a normal function without the use of
any object.
Ø
It can be
declared in the private part or the public part of a class without affecting
its meaning.
Example program
of friend function:
#include<iostream.h>
Class sample
{
Int a, b;
Public:
Void set data ()
Friend float mean
(sample s);
};
Float mean (sample
s)
{
Return float
(s.a+s.b)/2.0;
}
Friend class:
Ø
All the
member function of one class can be friend functions of another class.
Example program
for friend classes:
#include<iostream.h>
Class boy
{
Int income1,
income2;
Public:
Void set data
(int in1, int, in2)
{
Income1=in1;
Income2=int2;
}
Friend class
girl;
};
Static data
member:
Ø
A data
member of a class can be qualified as static. the properties of a static member
variable are similar to that of a c static variable.
Characteristics
of static data members as follows:
Ø
It is
initialized to zero when the first object of its class its created. No other
initialization is permitted.
Ø
Only one
copy of that member is created for the entire class and is shared by all the
objects of that class.
Ø
It is
visible only with in the class, but its life time is the entire program.
Example program
of static data member:
#include<iostream.h>
Class item
{
Static int count;
Int number;
Public:
Void get data
(int a);
{
Number=a;
Count++;
}
Void get
count(void)
{
Cout<<”count”;
Cout<<count<<”/n”;
}
};
Static member
functions:
Ø
A member
function that is declared static has the following properties
Ø
A static
function can have access to only other static members declared in the same
class.
Ø
A static
member function can be called using the class name as follows.
Sy:
Class-name::function name
|
Example program
for static member function :
#Include<iostream.h>
Class test
{
Int code;
Static int count;
Public:
Void set code(void)
{
Code=++count;
}
Classes and
objects:
Definition of
classes:
Ø
A class
definition is a process of naming a class and data variables, and method of the
class.
Ø
A class
is a way to bind the data and its associated functions together. it allows the
data to be hidden.
The general
syntax of a class declaration is as follows:
Class class –name
{
Private:
Variable declarations;
Function definitions;
Public:
Variable declarations;
Function definitions;
};
Ø
The
function and variables used in a class is collectively called members.
Ø
They are
grouped under two sections namely private and public by the default the members
are private.
Ø
Public
members can be accessed from out side the class also.
Ø
The
variables declared inside the class are known as data members and the functions
are known as member function.
Example of
classes:
Class student
{
Private:
Int sno;
Char sname[25];
Int m1,m2 ,m3;
Public:
Void getdata();
Void putdata();
};
Objects definition:
Ø
In c++, the class variables are known as
objects these are basic run time entities in an oop.
The syntax for
defining objects of a class :
Class
class name object1,object2,object3--------------object n;
Example of
object:
Class
student s1;
Access modes of classes and objects:
Ø
In
c++,they are three types of access modes of classes and objects.
·
Private
member of a class
·
Public
member of a class
·
Protected
member of a class
Private member
of a class:
Ø
The
private members of a class have strict access control.
Ø
Only the
member functions of the same class can access these members.
Ø
The
private member of a class are in accessible outside the class.
Ø
Information
hiding is implemented.
Public member of
a class:
Ø
The
members of a class, which are to be visible out side the class.
Ø
Public
members should be declared in public section only.
Ø
All data
members and functions declared in the public section of the class can be
accessed without any restriction from any where in the program.
Protected member
of a class:
Ø
Protected
members has more significance in inheritance.
Ø
The
protected members of a class have strict
access control.
Ø
Only the
member functions of the same class can access these members.
Ø
The
protected members of a class are inaccessible outside the class.
UNIT-IV
Constructor and
destructors:
Definition of
constructor:
Ø
A constructor is a special member function
whose main operation is to allocate the required resources such as memory and
initialize the object of its class.
Special
characteristics of constructor:
Ø
Constructor
are declared in public section only.
Ø
These are
invoked automatically when the objects are created.
Ø
Constructors
do not have return type.
Ø
Constructors
have the default arguments.
Ø
The name
of the constructor is same as the class name.
Ø
The
constructor without arguments is called as default constructor.
Ø
Constructor
can be invoked explicitly.
Syntax:
Class classname
{
Public:
};
Classname::classname()
{
}
Types of
constructors:
Ø
In c++, they are five types of constructors
v
Parameterized
constructors
v
Default
constructors
v
Multiple
constructors
v
Copy
constructors
v
Dynamic
constructors
Parameterized
constructors:
Ø
Constructors
with arguments are called parameterized constructors.
Example of
parameterized constructors:
Class num
{
Int a,b;
Public:
Num(int x,int y);
};
Num:: num(int
x,int y)
{
A=x;
B=y;
}
Default
constructor:
Ø
A default
constructor function initializes the
data members with no arguments it may be explicitly written in a program.
Syntax of the
default constructor:
Class class-name
{
Private:
--------
Public:
Class_name();
};
Class_name::class_name()
{
}
Multiple
constructors:
Ø
C++
permits to use the two kinds of constructors namely constructors with no arguments and constructors with arguments in
the same class.
Ø
How ever
a class having more than one constructor function is called an constructor over
loaded.
Copy
constructors:
Ø
The copy
constructors is used when the initialization of an object by another object of
the same class.
Ø
There are
3 important places where a copy constructor
is called
v
When an
object is created from another object of the same type.
v
When an
object is passed by value as a parameter to a function.
v
When an
object is returned from a function.
Syntax of copy
constructors:
Class_name::
class name(class_name & ptr);
|
Dynamic
constructors:
Ø
The
constructor can also used to allocate memory, while creating objects. when an
object are not of the same size.
Ø
Allocation
of memory to objects at the time of their construction is known as dynamic construction
of objects.
Destructor:
Definition of
destructor:
Ø
A destructor is a function that automatically
executes when an object is destroyed.
Characteristics of destructor function:
Ø
A
destructor function name is same as the that of class except that the first
character of the name must be ’~’ (tilde).
Ø
A
destructor have public access in the class declaration.
Ø
A
destructor function takes no arguments.
Ø
There can
be only one destructor in each class.
Syntax:
Class
name
{
Private:
Public:
~name();
};
Operator
overloading:
Ø
C++ has
the ability to provide the operators with a special meaning to an operator is
known as operator overloading.
Ø
The
overloaded operator should contain one operand of user defined data type we
cannot overload the operator for built in data types.
Ø
There is
no higher limit to the number of overloading for any operator an operator can
be overloaded for a number of times
Ø
If the
arguments are different in each overloaded operation function.
Ø
Only
existing operators can be overloaded we cannot create a new operators.
We can overload
all the c++ operators except the following:
Ø
Size
resolution operator (::)
Ø
Scope of
operator (size of)
Ø
Conditional
operator (?:)
Ø
Class
member access operator (., .*,->*)
Ø
Pointer
to member declaration (:: *)
Types of
operator overloading:
Ø
In c++
they are two types of operator overloading
v Unary operator overloading
v Binary operator overloading
Unary operator
overloading:
Ø
When
unary operators are overloaded using member functions. it requires no explicit argument and return no
value.
Ø
Where as
when it is overloaded using friend function, it requires one reference
arguments.
Binary operator
overloading:
Ø
When
binary operators are overloaded using friend function, it requires two
arguments.
Ø
Where as
when it is overloaded using member function, it requires one argument.
Example of
operator overloading:
#include<iostream.h>
Class sample
{
Int x,y,z;
Public:
Void get data(int a,int b, int
c)
{
X=a,y=b,z=c;
}
Void
display()
{
Cout<<x<<”
“;
Cout<<y<<”
“;
Cout<<z<<”
“;
}
Inheritance:
Definition of
inheritance:
Ø
The
mechanism of deriving a new class from an old one is called inheritance.
Ø
The old
class is referred to as the base class and the new one is called derived class.
Ø
Inheritance
makes the code reusable. When we inherit an existing class, all its methods and
fields become available in the new class, hence code is reused.
Purpose of
Inheritance:
v
Code
Reusability
v
Method Overriding (Hence, Runtime
Polymorphism.)
v
Use of Virtual Keyword
Basic Syntax of
Inheritance:
Class
subclass_name:access _mode superclass_name;
|
Inheritance
Visibility Mode:
Ø
Depending
on Access modifier used while inheritance, the availability of class members of
Super class in the sub class changes. It can either be private, protected or
public.
Public
Inheritance:
Ø
This is
the most used inheritance mode. In this the protected member of super class
becomes protected members of sub class and public becomes public.
Sy:
Class
subclass:public superclass
|
Private
Inheritance:
Ø
In
private mode, the protected and public members of super class become private
members of derived class.
Sy:
Class
subclass:superclass
|
Protected
Inheritance:
Ø
In
protected mode, the public and protected members of Super class becomes
protected members of Sub class.
Sy:
Class
subclass: protected superclass
|
Types of
inheritance:
Ø
In C++,
we have 5 different types of Inheritance. Namely,
v
Single
Inheritance
v
Multiple
Inheritance
v
Hierarchical Inheritance
v
Multilevel Inheritance
v
Hybrid Inheritance
Single
inheritance:
Ø
In this
type of inheritance one derived class inherits from only one base class. It is
the most simplest form of Inheritance.
Sample diagram
of inheritance:
Example of
single inheritance:
Class b
{
Int a;
Public:
Void read_sno();
Void show_sno();
};
Multiple
inheritance:
Ø
In this
type of inheritance a single derived class may inherit from two or more than
two base classes.
Ø
Sample diagram
of multiple inheritance:
Example of
multiple inheritance:
Class
b1
{
Protected:
Int
a;
};
Class
b2
{
Protected:
Int
b;
};
Hierarchical
inheritance:
Ø
In this
type of inheritance, multiple derived classes inherits from a single base class
Sample diagram
of hierarchical inheritance:
Example of
hierarchical inheritance:
Class
b
{
Protected:
Int a,b;
};
Class d1:public b
{
Int s;
Public:
Void read_data();
Void show_sum();
}
Multilevel inheritance:
Ø
In this
type of inheritance the derived class inherits from a class, which in turn
inherits from some other class. The Super class for one, is sub class for the
other.
Sample diagram
of multilevel inheritance:
Example of
multilevel inheritance:
Class
b
{
Protected:
Int a;
};
Class d2:public
d1
{
Protected:
Int s;
Public:
Void read_data();
Void show_data();
};
Hybrid
inheritance:
Ø
Hybrid
Inheritance is combination of Hierarchical and Multilevel Inheritance.
Sample diagram
of hybrid inheritance:
Example of
hybrid inheritance:
Class
b1
{
Protected:
Int a;
};
Class d1:public b
{
Protected :
Int b;
};
Class b2
{
Protected:
Int c;
};
Class d2:public
d1,b2
{
Protected:
Int s;
Public:
Void read_data();
Void show_data();
};
Pointers:
Ø
Pointers
are variables that hold address of another variable of same data type.
Ø
Pointers
are one of the most distinct and exciting features of C language. It provides
power and flexibility to the language.
Ø
Although
pointer may appear little confusing and complicated in the beginning, but trust
me it’s a powerful tool and handy to use once its mastered.
Benefit of using
pointers:
Ø
Pointers
are more efficient in handling Array and Structure.
Ø
Pointer
allows references to function and thereby helps in passing of function as
arguments to other function.
Ø
It
reduces length and the program execution time.
It
allows C to support dynamic memory management
Ø
A pointer variable is therefore nothing but a
variable that contains an address, which is a location of another variable.
Ø
Value of
pointer variable will be stored in another memory location.
Declaring a
pointer variable:
General syntax
of pointer declaration is:
data-type *pointer_name;
Initialization
of Pointer variable:
Ø
Pointer
Initialization is the process of assigning address of a variable to pointer
variable.
Ø
Pointer
variable contains address of variable of same data type. In C language address
operator & is used to determine the address of a variable.
Example of
pointer:
#include<stdio.h>
Main()
{
int a = 10 ;
int *ptr ;
ptr = &a ;
}
Advantages of
pointers:
Ø
Pointers
save the memory space.
Ø
Execution
time with pointer is faster because data is manipulated with the address direct
access to memory location.
Ø
The
memory is accessed efficiently with the pointers the pointers assigns the
memory space dynamically that leads you to reserve a specific bytes in the
memory.
Ø
Pointers
are used with data structures they are useful for representing two dimensional
and multidimensional arrays.
Virtual
functions and polymorphism:
Ø
Using virtual
functions, the member function of the base class can be overridden by the functions
of the derived class.
Ø
The
keyword virtual provides a mechanism for defining the virtual functions.
Syntax:
Class
myclass
{
Public:
Virtual return type function name(arguments)
{
}
};
Rules for the
virtual functions:
Ø
Virtual
functions are the members of some class
Ø
They
cannot be static members.
Ø
They are
accessed by using object pointer
Ø
A virtual
functions can be a friend of another class
Ø
Virtual
functions supporting runtime polymorphism they should be declared in public
section of a class.
Ø
The
prototype of the base class version and the derived class version are
identical.
Example of
virtual functions:
Class
num
{
Private:
Int
a,b;
Public:
Virtual
int sum();
};
Dynamic memory
allocation:
Ø
Dynamic memory
allocation can be obtained by using the functions calloc (),and malloc (),in c
language. these are the functions in header files stdlib.h.
Ø
The name
‘calloc’ stands for ‘contiguous allocation’, and the name malloc stands for
memory allocation.
Ø
These
functions create space for array. structures and unions dynamically.
The syntax of
the calloc () function is:
Calloc
(n,sizeof(int))
|
Ø
The
function calloc () takes two arguments one is ‘n’ it allocates contiguous space
in memory for an array of n elements.
Ø
Second
argument specifies the number of bytes for each element.
Example of
dynamic memory allocation:
#include<stdio.h>
#include<stdlib.h>
Int main(void)
{
Int *a;
Int n=10;
}
Ø
The value
of n is 10,each element occupies 2
bytes, because it is an integer type element.
Ø
So
10*2=20 bytes of memory allocated and the address is stored in the pointer a.
Ø
The
programmer uses the malloc () function in the same manner. this function takes
a single argument.
The syntax of
malloc () function is:
a=malloc
(n*size of(int));
|
Ø If the required space is available the
malloc () function allocates the memory and assign the
address of memory
location to pointer variable a, otherwise the function returns ‘null’.
UNIT-V
Managing console
I/O Operations:
Ø
C++
contains several predefined streams that are opened automatically when the
execution of a program starts.
Ø
The four
standard streams cin, cout, cerr, and clog are automatically opened before the
function main () is executed.
Ø
They are
closed after main() has completed these predefined stream objects are declared
in iostream.h have the following meaning.
Object
|
Description
|
Cin
|
Standard
input (usually keyboard) corresponding
to stdin in c.
|
Cout
|
Standard
output (usually screen) corresponding to stdout in c.
|
Cerr
|
Standard
error output(usually screen) corresponding to stderr in c.
|
Clog
|
A
fully buffered version of cerr (no c equivalent)
|
Unformatted i/o
operations:
Ø
The most
commonly used objects through out all c++ programs are cin and cout.
Ø
They are
predefined in the header file.iostream.h which supports the input and output of
the data of various types.
Ø
This is
achieved by overloading the operaters<< and >> to recognize all the
basic data types.
Put () and get
() functions:
à
The
stream classes of c++ support two member functions, get () and put (). The
function get () is used to read a single character from the input device.
à
Where as
the put () function is used to write a
single character to the output device.
Example program:
#include<iostream.h>
Void main()
{
Char c;
Cout<<”enter
a character:”;
Cin.get(c);
Cout<<”given
character is:”;
Cout.put
(c);
}
Getline () and
write () functions:
à
The c++
stream classes support line oriented functions, getline() and write() to
perform and input and output operations.
à
The
getline () function reads a while line of text that ends with new line or until
the maximum limit is reached.
à
Whereas
the write () function is used print a line of text on the standard output
device.
Example:
#include<iostream.h>
Void
main()
{
Char
st[30];
Cout<<”enter
string:”;
Cin.getline(st,30);
Cout<<”given
string:”;
Cout.write(st,30);
}
Formatted
console i/o operations:
à
C++
supports a wide variety of features to perform input or output in different
formats. they include the following:
§ Ios stream class member functions and flags
§ Standard manipulators
§ User defined manipulators.
Ios class
functions and flags:
à
The
stream class, ios contains a large number of member functions to assist the
formatting the output in a number of ways.
à
The most
important among these functions are shown below.
Width ()
|
Specifies the required number of fields
to be used while displaying the output value.
|
Precision()
|
Specifies the number of digits to be displayed
after the decimal point
|
Fill ()
|
Specifies a character to be used to fill
the unused area of a field by default fills blank space character.
|
Setf ()
|
Sets fromat flag that control the form of
output display
|
Unsetf()
|
Clears the specified flag
|
Files &
Different types of files:
Definition of
file;
Ø
File is a
collection of data or a set of characters or may be a text or a program.
Ø
Basically
there are two types of files in the c++
Types of file:
à Sequential files
à Random access files
Sequential
files:
Ø
The
sequential files are very easy to create than random access files.
Ø
In
sequential files the data or text will be stored or read back sequentially.
Random access
files:
Ø
In random
files data can be accessed and processed randomly.
Ø
The
header file, fstream.h supports the input/output stream processing techniques.
Ø
The c++
input and output (i/o) class package handles file i/o as much as it handles
standard input and output.
Following
methods are used in c++ to read and write file:
ifstream
|
To
read a stream of object from a specified file
|
Ofstream
|
To
write a stream of object on a specified file
|
Fstream
|
Both
to read and write a stream of objects on a specified file
|
File i/o
operations:
Opening a file:
Ø
The
member function open() is used to create a file as well as open the existing
file in the default mode.
Ø
C++
provides a mechanism of opening a file in different modes. They are
Ios::in
|
Opens a file for reading
|
Ios::out
|
Opens a file for writing
|
Ios::ate
|
Fo to the end of file at opening time
|
Ios:;app
|
Opens a file for appending
|
Ios::trunc
|
Truncate the file it it already exists
|
Ios::nocreate
|
Open fails if file does not exist
|
Ios::noreplace
|
Open fails if file already exist
|
Ios:;binary
|
Open as a binary file
|
Example of
opening a file:
à Ifstream infile: infile.open
(“student.dat”,ios::in);
à Ostream infile:
infile.open(“student.dat”,ios::out);
à Fstream
infile:infile.open(“student.data”,ios::in|ios::out);
Closing a file:
Ø
The
member function close() is used to close a file which has been opened for file
processing such as to read, to write and for both.
Example of
closing a file
à Infile.close();
Eof():
Ø
The eof()
member function is used to check whether a file pointer has reached the end of
a file or not.
Ø
If it
reached, eof() function returns a non zero other wise it returns zero value.
Example of eof():
à Infile.eof();
Fail():
Ø
The fail
() member function is used to check whether a file has been opened for input or
output is successfully, or any invalid operations are attempted it returns a
non zero value.
Example of fail():
à Infile.fail();
Bad():
Ø
The bad()
member function is used to check whether any invalid file operations has been attempted.
Ø
The bad()
function returns a non zero if it is true otherwise returns a zero.
Good():
Ø
The
good() member function is used to check whether the previous file operation has
been successful or not.
Get():
Ø
The get()
member function is used to read a character from a specified file.
Example of
get():
à Infile.get();
Put():
Ø
The put()
member function is used to write a character to a specified file.
Write():
Ø
The
write() member function is used to write a specified number of bytes data into
binary file.
Example of
write():
à Infile.write(char *) &num1.sizeof(int);
Read():
Ø
The
read() member function is used to read the specified number of bytes data from
binary file.
Example of
read():
à Infile.read(char *) &num1.sizeof(int);
TEMPLATES:
Ø
A template
is a method for writing a single class or function for a family of similar
classes or functions.
Ø
A
template is considered as a kind of macro. when an object of specific type is
defined the template definition for that class is substituted with the required
data type.
Ø
Since a
template is defined with a parameter, that can be replaced by a specific data
type at the time of actual use of the class of function are called
parameterized classes or functions.
For example of
template:
à A class template for a stack class would
enable to create stacks of various data types
§ Int,float,and character.
Ø
Similarly
a function template for a sort function
would helps to create various versions of sort function for sorting integer,
float and double type values.
Advantages of
templates:
Ø
Templates
will help to define the generic classes.
Ø
Templates
are used for the creation of reusable code.
Ø
By using
template classes to create a frame work that can be applied over to a variety
of programming situations.
Ø
Generic
functions and classes provides a powerful tool used to amplify the programming
efforts.
Ø
Templates
makes the process simpler and safer.
Ø
Once a
template class is written and debugged, a solid software component used in a
variety of different situations.
Ø
By using
templates a high performance object code is generated.
Ø
By using
class templates, eliminates the need for type casts and define parameterized
classes in a safe manner.
Types of
templates:
Ø
They are
two templates in c++
à Function template
à Class template
Function
template:
Ø
A
function template is prefixed with the keyword template and a list of template
type arguments.
Ø
These
template type arguments are called generic types since their exact
representation is not known in the declaration of the function template.
Ø
It is
known only at the point of a call to function template.
Syntax of
function template:
Template <class t1,class t2,………>
Return type name(arguments of type t1 and t2)
{
Local variable of type
}
Class template:
Ø
A class
template is a class definition that describes a family of related classes.
Ø
C++
having the ability to create a class that contains one or more types of generic
or parameterized class templates.
Ø
By
defining a class template the keyword template must be inserted as a first
word.
The general
syntax of the class template is:
Template
<class t>
Class
class_name
{
Private:
………….
Public;
…………
};