Tuesday, 31 March 2015

Program to concatenate two object’s content (using string)

#include <iostream.h>
class concat
{
char *a;
public:
concat(char *b)
{
a = b;
}
concat operator+(concat c)
{
concat temp;
strcpy(temp.a, a);
strcat(temp.a,c.a);
return temp;
}
void show(void)
{
cout<<”The string is”<<a<<endl;
}
};
void main()
{
concat A(“Have a”);
concat B(“ Nice Day”);
concat D(“ “);
D = A + B;
D.show();
}

Limitations of Increment and Decrement Operators

The prefix notation causes a variable to be updated before its value is used in the expression, whereas the postfix notation causes it to be updated after its value is used. However the statements

X1 = A++; and X2 = ++A has exactly the same effect;

When ++ and – operator are overloaded, there is no distinction between the prefix and postfix overloaded operator function.

This problem is avoided in the implementation of C++, which provides addition syntax to express and distinguish between prefix and postfix overloaded operator function. The syntax for overloaded operator function is

Return_type operator++(int)

Sample Program

#include <iostream.h>
class post
{
int val;
public:
post(void)
{
val = 1;
}
int operator++(void)
{
return (++val);
}
int operator++(int)
{
return(val++);
}
};
void main()
{
int x1, x2;
post A;
x1 = A++;
x2 = ++A;
cout<<”x1 is “<<x1<<endl;
cout<<”x2 is “<<x2<<endl;
}

Program to Overload == operator

#include <iostream.h>
class dev
{
int a,b;
public:
dev(int x, int y)
{
a = x;
b = y;
}
int operator==(dev o)
{
if((a == o.a) && (b == o.b))
return 0;
else
return 1;
}
};
void main()
{
dev A(3,2), B(2,4);
int x = A == B;
if(x == 0)
cout<<”The content are same”<<endl;
else
cout<<”The content are not same”<<endl;
}

Operator Return Values

When the member function of operator++ is returning any value, then it is said to operator returning value.

Sample Program

#include <iostream.h>
class index
{
int value;
public:
index(void)
{
value = 0;
}
int operator++(void)
{
value = value + 1;
return(value);
}
};
void main()
{
index A;
int x1, x2;
x1 = A++;
cout<<”X1 value is “<<x1;
x2 = ++A;
cout<<”X2 value is “<<x2;
}

Binary Operator Overloading

The concept of overloading unary operators applies also to the binary operators. The syntax for overloading a binary operator is shown as follows

Return-type operator operator-symbol(arguments)
{
body of the function;
}

The binary overloaded operator function takes the first object as implicit operand, and the second operand must be passed explicitly.

The data members of the first object are accessed without using dot operator whereas the second argument members can be accessed the dot operator, if the argument is an object, otherwise it can be accessed directly.

Arithmetic Operators

The following program demonstrate the concept of + operator overloading which takes two arguments.

Sample Program

#include <iostream.h>

class opera
{
int index;

public:

opera()
{
index = 1;
}
void show(void)
{
cout<<index;
}
opera operator+(opera o)
{
opera temp;
temp.index = index + o.index;
return(temp);
}
};
void main()
{
opera A,B,C;
C = A+B;
A.show();
B.show();
C.show();
}

Sample Program

#include <iostream.h>

class add
{
int x;
public:
add(int a)
{
x = a;
}
void operator+(add y)
{
x = x + y.x;
}
void show(void)
{
cout<<x;
}
};
void main()
{
add x(10);
add y(20);
x + y;
x.show();
y.show();
}

Overloading ++ and - - Operators

Sample Program

#include <iostream.h>
class inc
{
int val;
public:
inc(void)
{
val = 1;
}
void operator++(void)
{
val = val + 1;
}
void display(void)
{
cout<<val;
}
};
void main()
{
inc A;
A.display();
A++;
A.display();
++A;
A.display();
}

Operator Keyword

The keyword operator facilitates overloading of the C++ operators. The general format of operator overloading indicates that the operator symbol following it, is the C++ operator to be overloaded to operate on members of its class. The operator overloaded in a class is known as overloaded operator function.

Return type operator operator-symbol(arguments)
{
body of operator function;
}

Overloading without explicit arguments to an operator function is known as unary operator overloading and overloading with a single explicit argument is known as binary operator overloading. The syntax for overloading unary operator is

Return type operator operator-symbol( )
{
body of operator function;
}

The following illustrate the overloading of unary operators

Operator+();
Operator-();
Operator++();
Operator--();
Operator*();

#include <iostream.h>

class op
{

int x,y,z;

public:

void assign(int a, int b, int c)
{
x = a;
y = b;
z = c;
}
void show(void)
{
cout<<x<<y<<z;
}
void operator-(void)
{
x = -x;
y = -y;
z = -z;
}
};
void main()
{
op A;
A.assign(-2,3,4);
A.show();
-A;
A.show();
}

The process of operator overloading generally involves the following steps:

? Declare a class whose objects are to manipulated using operators.

? Declare the operator function in public part of the class. It can be either a normal
    member function or a friend function.
? Define the operator function either within the body of the class or outside the
    body of the class.
? The syntax for invoking the overloaded unary operator function is as follows
? Object operator
? Operator Object

[ The first syntax can be used to invoke prefix operator function and the second can be used to invoke postfix operator function. The syntax for invoking the overloaded binary operator function is as
follows ]

Object-1 operator Object-2

Note : - When we are invoking the binary operator function one of the operand function must be the object. Overloading without explicit arguments to an operator function is known as unary operator overloading and overloading with a single explicit argument is known as binary operators take two explicit arguments.

Program for ++ unary operator Overloading

Sample Program

#include <iostream.h>

Class index
{
int value;
public:
index()
{
value =0;
}
int getindex()
{
return value;
}
void operator++()
{
value = value + 1;
}
};

void main()
{
index idx1, idx2;
cout<<”Index – 1”<<idx1.getindex();
cout<<”Index – 2”<<idx2.getindex();
++idx1;
idx2++;
cout<<idx1.getindex();
cout<<idx2.getindex();
}

Overloadable Operators

C++ provides a wide variety of operators to perform operations on variance operands.

The operators are classified into unary and binary operators based on number of arguments on which they operate.

The precedence relation of overloadable operators and their expression syntax remains the same even after overloading.



OPERATOR OVERLOADING

The Basics for Operator Overloading

The operator overloading feature of C++ is one of the methods of realising polymorphism. Here poly refers to many or multiple and morphism refers to action. i.e., performing many actions with single operator.

The concepts of operator overloading can also be applied to data conversion. C++ refers automatic conversion of primitive data types. For example, x = a+ b, the compiler implicitly converts the integer result to floating point representation and then assigns to float variable x.

The operator overloading concepts are applied to the following two principal areas.

? The extending capability of operators to operate on user defined data.

? Data conversion

Operator overloading extends the semantics of operator without changing, its syntax. The grammatical rules defined by C++ that govern its use such as the number of operands, precedence, and associativity of the operator remain the same for overloaded operators.

Monday, 30 March 2015

Empty Classes

It is possible to have a class that has neither data nor code. In other words, it is possible to have empty classes. The declaration of empty classes is as follows:

Class class-name{ };

During the initial stages of development of a project, some of the classes are either not fully identified, or not fully implemented. In such cases, they are implemented as empty classes during the first few implementations of the project. Such empty classes are also called as stubs. The significant usage of empty classes
can be found with exception handling.

Nested Classes

The power of abstraction of a class can be increased by including other class declarations inside a class. A class declared inside the declaration of another class is called nested class. Nested classes provide classes with non-global status. Host and nested classes follow the same access rules for members that exist between nonnested classes. Nested classes could be used to hide specialized clases and their instances within a host class.

A member of a class may itself be a class. Such nesting enables of very powerful data structures. The student class can be enhanced to accommodate the date of birth of a student. The new member data type date is a class by itself as show below.

Sample program


#include <iostream.h>
class Student
{
int rno;
char name[30];
char branch[40];
int marks;
public:
class date
{
int day;
int month;
int year;
public:
void setdate(void)
{
cin>>day>>month>>year;
}
void showdate(void)
{
cout<<day<<”-“<<month<<”-“<<year<<endl;
}
}dob;
void setstud(void)
{
cout<<”Enter the Student Number”;cin>>rno;
cout<<”Enter the Student Name”;cin>>name;
cout<<”Enter the Student Branch”;cin>>branch;
cout<<”Enter the Date of Birth”; dob.setdate();
}
void showstud( void)
{
cout<<”Student Number”<<rno;
cout<<”Student Name”<<name;
cout<<”Student Date of Birth”;dob.showdate();
}
};
void main()
{
Student A1;
A1.setstud();
A1.showstud();
}

Constant Parameters and Member Functions

Certain member functions of a class, access the class data members without modifying them. It is advisable to declare such functions as const functions. The syntax for declaring const member functions is shown as follows:

Return_type function_name (argument) const

Sample Program
#include <iostream. h>
class con
{
int eno;
float sal;
public:
void setdata(int x, float y)
{
eno = x;
sal = y;
}
void display(void) const
{
cout<<”Employee Number “<<eno<<endl;
cout<<”Employee Salary “<<sal<<endl;
}
};
void main()
{
con A;
A.setdata( 10,4500.50);
A.display();
}

Sunday, 29 March 2015

Specific Member Function of one class is friend to another class

When only specific member function of one class should be friend function of another class, it must be specified explicitly using the scope resolution operator as shown below.

Friend friend-classname :: friend-functionname(object as argument)

Sample Program

#include <iostream.h>
class B;
class A
{
int a;
float b;
public:
void show1(void)
{
cout<<a;
}
void show2(void)
{
cout<<b;
}
void print(void)
{
cout<<a<<b;
}
friend B::getdata(A ob);
};
class B
{
public:
void getdata(A ob1, A ob2)
{
ob1.a = 5;
ob2.b = 5.5;
}
void print(A ob1, A ob2)
{
return(ob1.a+ob2.b);
}
};
void main()
{
A x;
B y;
y.getdata(x);
y.print(x);
x.show1();
x.show2();
x.print();
}

Friend Class

Friend functions permit an exception to the rules of data encapsulation. The friend keyword allows a function, or all the functions of another class to manipulate the private members of the original class. The syntax of declaring friend class is shown as follows:

Friend class class-name;

Sample Program

#include <iostream.h>
class boyd
{
int income1;
int income2;
public:
void setdata(int in1, int in2)
{
income1 = in1;
income2 = in2;
}
friend class girl;
};
class girl
{
int income;
public:
int girfunc(boy b1)
{
return b1.income1+b1.income2;
}
void setdata(int in)
{
income = in;
}
void show(void)
{
boy b1;
b1.setdata(100,200);
cout<<”Boy’s income1 in show() “<<b1.income1<<endl;
cout<<”Girl’s income in show() “<<income<<endl;
}
};
void main()
{
boy b1;
girl g1;
b1.setdata(500,1000);
g1.setdata(300);
cout<<”Boy b1 total income “<<g1.girlfunc(b1)<<endl;
g1.show();
}

The statement in the class boy

Friend class girl;

Declares that all the member functions of the class girl are friend functions of class boy but not the other way. The objects of the class girl can access all the members of the class boy irrespective of their access  privileges.


Friend Functions with Two Classes

Consider a situation of operating on objects of two different classes. In such a situation, friend functions can be used to bridge the two classes.

Sample program

#include <iostream.h>
class two;
class one
{
int data1;
public:
void setdata(int init)
{
data1 = init;
}
friend int add(one a, one b);
};
class two
{
int data2;
public:
void setdata2(int init)
{
data2 = init;
}
friend int add(one a, one b);
};
int add(one a, one b)
{
return a.data1 + b.data2;
}
void main()
{
one a;
two b;
a.setdata(10);
b.setdata(20);
cout<<”Sum of one and two is”<<add(a,b);
}

observe the following declaration at the beginning of the program

class two;

it is necessary, since a class cannot be referred until it has been declared before the class one. It informs the compiler that the class two’s specification will appear later.

Though friend functions, add flexibility to the language and make programming convenient in certain situations, they are controversial; it goes against the philosophy that only member functions can access a class’s private data. Friend functions are useful in certain situations. One such example is when a friend is used to increase the versatility of overloaded operators.

Friend functions are useful in the following situations

? Function operating on objects of two different classes. This is the ideal
   situation where the friend function can be used to bridge two classes.
? Friend functions can be used to increase the versatility of overloaded
   operators.
? Sometimes, a friend allows a more obvious syntax for calling a function,
   rather than what a member function can do.


Friend Functions

The concept of encapsulation and data hiding dictate that non-member functions should not be allowed to access an object’s private and protected members. The policy is, if you are not a member you cannot get it. Sometimes this feature leads to considerable inconvenience in programming. Imagine that the user wants a function to operate on two different classes. At such times, it is required to allow functions outside a class to access and manipulate the private members of the class. At such times, it is required to allow functions outside a class to access and manipulate the private members of the class. In C++ this is achieved by using the concept of Friends.

C++ allows non-member functions to access even the private members of a class using friend functions or friend classes. It permits a function or all the functions of another class to access a different class’s private members.

Syntax

friend return_type function-name(arguments)
{
function body;
}

The function declaration must be prefixed by the keyword friend whereas the function definition must not. The function could be defined anywhere in the program similar to any normall C++ function. The functions that are declared with the keyword friend are called friend functions. A function can be friend to multiple
classes. A friend function possesses the following special characteristics.


? 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.
? Unlike class member functions, it cannot access the class members directly.
   However, it can use the object and the dot operator with each member name to
   access both the private and public members.
? It can be either declared in the private part or the public part of a class without
   affecting its meaning.

Sample program

#include <iostream.h>
class one
{
int data;
public:
void setdata(void)
{
data = 100;
}
friend void show(one);
};
void show(one o)
{
cout<<o.data<<endl;
}
void main()
{
one A;
cout<<”object value is”;show();
}



Returning Objects From Function

Similar to sending objects as parameters to functions, it is also possible to return objects from functions. The syntax used is similar to that of returning variables from function. The return type of the function is declared as the return object type.

Sample Program

#include <iostream.h>
class add
{
int a,b;
public:
void setvalue(int x, int y)
{
a = x;
b = y;
}
add addobj(add o1, add o2)
{
o1.a = o1.a + o2.a;
o1.b = o1.b + o2.b;
return(o1);
}
void show(void)
{
cout<<a<<b<<endl;
}
};
void main()
{
add A,B,C,D;
A.setvalue(5,10);
B.setvalue(1,2);
D = C.addobj(A,B);
D.show();
A.show();
B.show();
}

Functions Returning Strings

#include <iostream.h>
#include <conio.h>
class retu
{
char name[40];
int tot;
public:
void set(void)
{
cout<<”Enter Total”;
cin>>tot;
}
char * strret(void)
{
if(tot >500)
strcpy(name,”Pass”);
else
strcpy(name,”Fail”);
return(name);
}
void display(void)
{
cout<<”Toal<<tot<<endl;
cout<<”Result”<<name<<endl;
}
};
void main()
{
retu R;
R.set();
R.display();
}

Passing Objects by Pointer

The members of objects passed by pointer are accessed by using the -> operator,
and they have similar effect as those passed by value. The above program requires
the following changes if parameters are to be passed by pointer.

? The prototype of the member function monetransfer() has to changed to

   Void monetransfer(ac *ac1, float amt);

? The definition of the member function moneytransfer() has to changed to

Void ac::moneytransfer(ac &ac1, float amt)
{
bal = bal – amt;
acc->bal = acc->bal + amt;
}

? The statement invoking the member function moneytransfer() has to changed to

Ac1.moneytransfer(&ac1, tmon);


Passing objects by Reference

Accessibility of the objects passed by reference is similar to those passed by value. Modifications carried out on such objects in the called function will also be reflected in the calling function. The method of passing objects as reference parameters to a function is illustrated in the program.

#include <iostream.h>
class ac
{
int acno;
float bal;
public:
void getdata(void)
{
cout<<”Enter the account number for ac1 object”;
cin>>accno;
cout<<”Enter the balance”;
cin>>bal;
}
void setdata(int an)
{
acno = an;
bal = 0;
}
void setdata(int an, float b)
{
acno = an;
bal = b;
}
void display(void)
{
cout<<”Account Number is “<<acno<<endl;
cout<<”Balance is “<<bal<<endl;
}
void moneytransfer(ac &a1, float amt);
};
void ac::moneytransfer(ac &a1, float amt)
{
bal = bal – amt;
a1.bal = al.bal + amt;
}
void main()
{
ac ac1, ac2, ac3;
int tmon;
ac1.getdata();
ac1.setdata(10);
ac3.setdata(20,750.5);
cout<<”Account Information”<<endl;
ac1.display();
ac2.display();
ac3.display();
cout<<”Enter money to transfer”;
cin>>tmon;
cout<<”Updated information about accounts”<<endl;
ac1.display();
ac2.display();
ac3.display();
}

Passing Objects by Value

#Include <iostream.h>
class distance
{
float feet;
float inches;
public:
void init(float ft, float in)
{
feet = ft;
inches = in;
}
void read(void)
{
cout<<”Enter Feet”;cin>>feet;
cout<<”Enter inches”;cin>>inches;
}
void show(void)
{
cout<<feet<<”-“<<inches<<endl;
}
void add(distance d1, distance d2)
{
feet = d1.feet + d2.feet;
inches = d1.inches + d2.inches;
if(inches > 12.0)
{
feet = feet + 1.0;
inches = inches – 12.0;
}
}
};
void main()
{
distance d1,d2,d3;
d2.init(11.0,6.25);
d1.read();
cout<<”d1 = “;
d1.show();
cout<<”d2=”;
d2.show();
d3.add(d1,d2);
cout<<”d3 = d1 + d2”;
d3.show();
}

Friday, 27 March 2015

Passing Objects as arguments to Function

It is possible to have functions which accept objects of a class as arguments, just as there are functions which accept other variables as arguments. Like any other data type, an object can be passed as an argument to a function by the following ways:

? Pass-by-value (a copy of entire object is passed to the function)
? Pass-by-reference (only the address of the object is passed implicitly to
  the function)
? Pass-by-pointer (the address of the object is passed explicitly to the
  function)

In the case of pass-by-value a copy of the object is passed to the function and any modification made to the object inside the function is not reflected in the object used to call the function. Whereas, in pass -by-reference or pointer, an address of the object is passed to the function and any changes made to the object inside the function is reflected in the actual object. The parameter passing by reference or pointer is more
efficient since, only the address of the object is passed and not a copy of the entire object.

Static Member Functions

Like static member variable, we can also have 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:

                    Class-name :: function -name;

The general syntax for defining static member function is

Static return_type function-name(arguments)
{
function body;
}

Sample Program

#include <iostream.h>

Class test
{
int code;
static int count;
public:
void setcode(void)
{
code = ++count;
}
void showcode(void)
{
cout<<”Object number “<<code<<endl;
}
static void showcount(void)
{
cout<<”count is “<<count<<endl;
}
};

int test::count;

void main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
}

Static Data Members

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. A static member variable has certain special characteristics:

? It is initialized to zero when the first object of its class is 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, no matter how many objects are created.
? It is visible only within the class, but its lifetime is the entire program.

Private Static data member

Static variables are normally used to maintain values common to the entire class. For example, a static data member can be used as a counter that records the occurrences of all the objects. First, notice the following statement in the program

int item :: count;

Note that the type and scope of each static member variable must be defined outside the class definition. This is necessary because the static data members are stored separately rather than as a par of an object. Since they are associated with the class itself rather than with any class object, they are also know as class variable .

Sample Program

#include <iostream.h>
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number = a;
count++;
}
void getcount(void)
{
cout<<”count”;
cout<<count<<endl;
}
};
int item :: count;
void main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<”After reading data”;
a.getcount();
b.getcount();
c.getcount();
}

the statement int stat :: count reveals that the variable is stored separately rather than as a part of an object it is associated with the class itself rather than with any class object. It is also known as class variable.

Public Static data member

The public static data members can be accessed using the scope resolution operator or through objects with member access operator. Using the scope resolution operator is a completely new notation for member access. However, the accessibility of private static data member is same as that of normal private members.
The static data members which are declared public are similar to normal global variables. They can be addressed by the program by prefixing class name and scope resolution operator. It is illustrated in the following code fragment.

Sample Program

#include <iostream.h>

class Test
{
public:
static int pint;
private:
static int print;
};
void main()
{
Test::pint = 45; // ok
Test::print = 12; // wrong, because it private
Test Myobj;
Myobj.pint = 45; // ok
Myobj.print = 12 //wrong
}

the static data member pint defined in the class test can be accessed using the scope resolution operator prefixed by its class name as follows:

Test::pint = 45

Whereas, the data members print cannot be accessed using the scope resolution operator. Therefore, the statement

Test::print = 12; //wrong

Leads the compiler error. Objects accessing the static data member access the same data that is accessed by using the scope resolution operator.




Inline Functions

Function execution involves the ove rhead of jumping to and from the calling statement. Trading of this overhead in execution time is considerably large whenever a function is small, and hence is such cases, inline functions can be used. A function in C++ can be treated as a macro if the keyword inline precedes its definition. 

The syntax is

Inline return_type function_name(parameters)
{
body of the function
}

The significant feature of inline functions is that there is no explicit function call, the function body is substituted at the point of inline function call. Thereby, the runtime overhead for function linkage mechanism is reduced. Sample program

#inlcude <iostream.h>

inline float square(float x)
{
return(x*x);
}
void main()
{
float num;
cout<<”Enter the Number”;
cin>>num;
cout<<”its square is”<<square(num);
}

Member functions defined inside a class are considered as inline functions by default thus, offering both advantages and limitations of inline functions. However in some implementations, member functions having loop instructions such as for, while, do..while, etc., are not treated as inline functions.

Conditions for inline functions

? For functions returning values, if a loop, a switch, or a goto exists
? For functions not returning values, if a return statement exists.
? If functions contain static variables.
? If inline functions are recursive.

When to use Inline functions

? In general, inline functions should not be used.
? Defining inline functions can be considered once a fully developed and tested  program runs too slowly and    shows bottlenecks in certain functions.
? Inline functions can be used when member functions consist of one very    simple statement such as the          return statement.
? It is only useful to implement an inline function if the time spent during a    function call is more compared to    the function body execution time.

Outside function as Inline

C++ treats all the member functions that are defined within a class as inline functions and those defined outside as non-inline. Member function declared outside the class declaration can be made inline by prefixing the inline to its definition as show below.

Inline return_type Class_Name :: function_name(arguments)
{
function body;
}

Sample Program

#include <iostream.h>
class date
{
int d,m,y;
public:
void set(void);
void show(void);
};
inline void date::set(int a, int b, int c)
{
d = a;
m =b;
y = c;
}
inline void date::show(void)
{
cout<<d<<”-“<<m<<”-“<<y<<endl;
}
void main()
{
data d1;
d1.set(27,12,1977);
d1.show();
}

Thursday, 26 March 2015

Arrays of Objects

We know that an array can be of any data type including struct. Similarly, we can also have arrays of variables that are of the type class. Such variables are called arrays of objects . Consider the following class definition:

Class employee
{
char name[40];
float age;
public:
void getdata(void);
void putdata(void);
};

The identifier employee is a user -defined data type and can be used to create objects that relate to different categories of the employees.

For example 
Employee manager[10];

The array manager contains ten objects, namely manager[0], manager[1] ..
manager[9] of type employee class.

Sample Program
#include <iostream.h>
class employee
{
char name[40];
float age;
public:
void getdata(void);
void putdata(void);
};
void employee::getdata(void)
{
cout<<”Enter name”;
cin>>name;
cout<<”Enter age”;
cin>>age;
}
void employee::putdata(void)
{
cout<<”Name “<<name<<endl;
cout<<”Age “<<age<<endl;
}
const int size = 3;
void main()
{
employee manager[size];
for(int i =0;i<size;i++)
{
cout<<”Details of manager “<<i+1<<endl;
manager[i].getdata();
}
for(int i =0;i<size;i++)
{
cout<<”Manager “<<i+1<<endl;
manager[i].putdata();
}
}

Arrays within Class

The arrays can be used as member variables in a class. The following class definition is valid.

Const size = 10;
Class array
{
int a[size];
public:
void setval(void);
void display(void);
};

The array variable a[ ] declared as a private member of the class array can be used in the member functions like any other array variable. We can perform any operation on them. For instance, in the above class definition, the member functions setval( ) sets the values of elements of the array a [ ] and display( ) function displays the values. Similarly we may use other member functions to perform any other operations on the array values.

Private Member Functions

The private members of a class have strict access control. Only the member functions of the same class can access these members. The private members of a class are inaccessible outside the class, thus providing a mechanism for preventing accidental modifications of the data members.

Example

Class person
{
private:
private members;
………….
Int age;
Int getage( );
};

If w e are setting the private member function to assign the values for the private data members, even though the private member functions are invoked only by the public member functions, i.e., by using the object we cannot invoke directly the private member function. For the reason only in private section data members are
declared, in public section the member functions are declared.

Sample Program

#include <iostream.h>
Class pri
{
int a,b;
void setab(void)
{
a = 2;
b = 4;
}
public:
void callsetad(void)
{
setab();
}
void show(void)
{
cout<<a<<b;
}
};
void main()
{
pri X;
X.callsetab();
X.show();
}

Nesting of Member Functions

A member function of a class is accessed by the objects of that class using the dot operator. A member function of a class can call any other member function of its own class irrespective of its privilege and this situation is called nesting of member functions. The method of calling member function of one’s own class is similar to calling any other standard functions as illustrated in the following program.

Sample Program

#include <iostream.h>
Class NumberPairs
{
int num1,num2;
public:
void read()
{
cout<<”Enter the First Number”;
cin>>num1;
cout<<”Enter the second Number”;
cin>>num2;
}
int max(void)
{
if(num1 > num2)
return num1;
else
return num2;
}
void showmax(void)
{
cout<<”Maximum is “<<max();
}
};
void main()
{
NumberPairs N;
N.read();
N.showmax();
}

CLASSES AND OBJECTS

Class Declaration

Objected – oriented programming constructs modeled out of data types called classes. Defining variables of a class data type is known as a class instantiation and such variables are called objects. A cla ss encloses both the data and functions that operate on the data, into a single unit. A class is a way to bind the data and its associated functions together. It allows the data to be hidden, if necessary from external use. When defining a class, we are creating a new abstract data type that can be treated like any other built-in data type. Generally a class specification has two parts

? Class declaration.
? Class function definitions.

The general form of a class declaration is



The functions and variables which declared inside the class are collectively called members. They are usually grouped under two sections, namely, private and public to denote which of the members are private and which of them are public . The keywords private and public are known as visibility labels.

The members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also.

The data hiding is the key feature of object-oriented programming. The use of the keyword private is optional. By default, the members of a class are private . If both the labels are missing, then, by default, all members are private. Such a class is completely hidden from the outside world and does not serve any purpose.

The variables declared inside the class are known as data members and the functions are known as member functions. Only the member functions can have access to the private data members and private functions. However, the public members can be accessed from outside the class.

The binding of data and functions together into a single class -type variable is referred to as Encapsulation.

Class Objects

The idea of creating a class is to serve as blueprint for creating objects. A class defines a new data type. This new data type can be used to create objects of that type. The class is a template and the object is a physical entity. The necessary resources are allocated only when a class is instantiated. The syntax for defining
objects of a class is shown below.

[class] Class_name Object_name1,…..

Example
Stud S1,S2,S3;

Here the s1,s2 and s3 are objects and the ‘stud’ is the class name The definition of an object is similar to that of a variable of any primitive data type. Objects can also be created by placing their names immediately after the closing brace like in the creation of the structure variables. Thus the definition is

Class student
{
…………….
…………….
}s1,s2,s3,s4;

An object is a conceptual entity possessing the following properties:

? It is identifiable
? It has features that span a local state space.
? It has operations that can change the status of the system locally, while also
   inducing operations in peer objects.
? It refers to a thing, either a tangible or a mental construct, which is
   indentifiable by the users of the target system.

Accessing Class Members

Once an object of a class has been created, there must be provision to access its members. This is achieved by using the member access operator, called dot (.). The syntax for accessing members of a class is shown as

Object_Name.Data_Member

(a) Syntax for accessing data members of a class

Object_Name.Function_Name(Actua l_argument)

(b) Syntax for accessing member function of a class

Sample Program

#include <iostream.h>
Class stud
{
private:
int rno;
float avg;
public:
void setdata(int r, float a)
{
rno = r;
avg = a;
}
void showdata(void)
{
cout<<rno<<endl;
cout<<avg<<endl;
}
};
void main()
{
stud A;
A.setdata();
A.showdata();
}

Defining Member Functions

The data members of a class must be declared within the body of the class, whereas the member functions of the class can be defined in any one of the following steps:

? Outside the class specification
? Inside the class specification

Outside the class specification

Member functions that are declared inside a class have to be defined separately outside the class. Their definitions are very much like the normal functions. They should have a function header and a function body.

An important difference between a member function and a normal function is that a member function incorporates a membership ‘identity label’ in the header. This ‘label’ tells the compiler which class the function belongs to. The general form

Return_type class-name : : function_name(arguments)
{
function body;
………..
};

The label class-name:: informs the compiler that the function_name is the member of the class class-name. The scope of the function is restricted to only the objects and other members of the class.

The member functions have some special characteristics that are often used in the program development.

? Several different classes can use the same function name. The ‘membership
   label’ will resolve their scope.

? Member functions can access the private and of the class. A non-member
   function cannot do so.

? However this is exception for friend function.

? A member function can call another member function directly, without using
   the dot operator.

? Member functions defined as public act as an interface between the service
   provider and the service seeker.

? A class can have multiple member functions with the same name as long as
   they differ in terms of argument specification.

Sample program

#include <iostream.h>

class bank
{
int cno;
float amt;
public:
void setdata(int x, float y);
void display(void);
};
void bank::setdata(int x, float y)
{
cno = x;
amt = y;
}
void bank::display(void)
{
cout<<”Number is “<<cno;
cout<<”Amount is “<<amt;
}
void main()
{
bank B;
B.setdata(10,4350);
B.display();
}

Inside the Class Definition

Another method of defining a member function is to replace the function declaration by the actual function definition inside the class. The example is Sample Program

#include <iostream.h>
class sample
{
int a,b;
public:
void setab(void)
{
cout<<”Enter the value for a”;
cin>>a;
cout<<”Enter the value for b”;
cin>>b;
}
void showab(void)
{
cout<<”a value is”<<a<<”b value is “<<b<<endl;
}
};
void main()
{
sample s;
s.setab();
s.showab();
}

Sunday, 22 March 2015

To find the root of a equation using Secant Method Using C

# include <stdio.h>
# include <conio.h>
# include <math.h>

# define EPS 0.000001
# define MAXIT 50
# define F(x) (x) * (x) * (x) - 2 * (x) - 5

void main()
{
float a, b, root, x1, x2 ;
int count, status ;
clrscr() ;
printf("Input two starting points : ") ;
scanf("%f %f", &a, &b) ;
sec(&a, &b, &x1, &x2, &root, &count, &status) ;
if(status == 1)
{
printf("\nDivision by zero") ;
printf("\nLast x1 = %f", x1) ;
printf("\nLast x2 = %f", x2) ;
printf("\nNo. of iterations = %d", count) ;
}
else if(status == 2)
{
printf("\nNo convergence in %d iterations", MAXIT) ;
}
else
{
printf("\nRoot = %f", root) ;
printf("\n\nFunction value at root = %f", F(root)) ;
printf("\n\nNo. of iterations = %d", count) ;
}
getch() ;
}
sec(float *a, float *b, float *x1, float *x2, float *root,
int *count, int *status)
{
float x3, f1, f2, error ;
*x1 = *a ;
*x2 = *b ;
f1 = F(*a) ;
f2 = F(*b) ;
*count = 1 ;
begin :
if(fabs(f1 - f2) <= 1.E-10)
{
*status = 1 ;
return ;
}
x3 = *x2 - f2 * (*x2 - *x1) / (f2 - f1) ;
error = fabs((x3 - *x2) / x3) ;
if(error > EPS)
{
if(*count == MAXIT)
{
*status = 2 ;
return ;
}
else
{
*x1 = *x2 ;
}
*x2 = x3 ;
f1 = f2 ;
f2 = F(x3) ;
*count = *count + 1 ;
goto begin ;
}
else
{
*root = x3 ;
*status = 3 ;
return ;
}
}

RUN 1 :
~~~~~~~
Input two starting points : 2 3
Root = 2.094552
Function value at root = 0.000001
No. of iterations = 6

Find the root of a equation using Bisection method Using C

# include <stdio.h>
# include <conio.h>
# include <math.h>
# define EPS 0.000001
# define F(x) (x) * (x) * (x) - 2 * (x) - 5
void main()
{
int s, count ;
float a, b, root ;
clrscr() ;
printf("Input starting values : ") ;
scanf("%f %f", &a, &b) ;
bim(&a, &b, &root, &s, &count) ;
if(s == 0)
{
printf("\nStarting points do not bracket any root.") ;
printf("\nCheck whether they bracket EVEN roots.") ;
}
else
{
printf("\nRoot = %f", root) ;
printf("\n\nF(root) = %f", F(root)) ;
printf("\n\nIterations = %d", count) ;
}
getch() ;
}
bim (float *a, float *b, float *root, int *s, int *count)
{
float x1, x2, x0, f0, f1, f2 ;
x1 = *a ;
x2 = *b ;
f1 = F(x1) ;
f2 = F(x2) ;
if(f1 * f2 > 0)
{
*s = 0 ;
return ;
}
else
{
*count = 0 ;
begin :
x0 = (x1 + x2) / 2.0 ;
f0 = F(x0) ;
if(f0 == 0)
{
*s = 1 ;
*root = x0 ;
return ;
}
if(f1 * f0 < 0)
{
x2 = x0 ;
}
else
{
x1 = x0 ;
f1 = f0 ;
}
if(fabs((x2 - x1) / x2) < EPS)
{
*s = 1 ;
*root = (x1 + x2) / 2.0 ;
return ;
}
else
{
*count = *count + 1 ;
goto begin ;
}
}
}

RUN 1 :
~~~~~~~
Input starting values : 2 3
Root = 2.094552
F(root) = 0.000006
Iterations = 18


Find the root of a equation using Newton Raphson Using C

# include <stdio.h>
# include <conio.h>
# include <math.h>

# define EPS 0.000001
# define MAXIT 20
# define F(x) (x) * (x) * (x) - 2 * (x) - 5
# define FD(x) 3 * (x) * (x) - 2

void main()
{
int count ;
float x0, xn, fx, fdx ;
clrscr() ;
printf("Input initial value of x : ") ;
scanf("%f", &x0) ;
count = 1 ;
begin :
fx = F(x0) ;
fdx = FD(x0) ;
xn = x0 - fx / fdx ;
if(fabs((xn - x0) / xn) < EPS)
{
printf("\nRoot = %f", xn) ;
printf("\n\nNumber of iterations = %d", count) ;
}
else
{
x0 = xn ;
count = count + 1 ;
if(count < MAXIT)
{
goto begin ;
}
else
{
printf("\nSolution does not coverage in %d iterations",
MAXIT) ;
}
}
getch() ;
}

RUN 1 :
~~~~~~~
Input initial value of x : 0
Root = 2.094552
Number of iterations = 19

Implentation of queue using arrays Using C

# include <stdio.h>
# include <conio.h>
# define SIZE 10
int arr[SIZE], front = -1, rear = -1, i ;
void enqueue() ;
void dequeue() ;
void display() ;
void main()
{
int ch ;
clrscr() ;
do
{
printf("\n[1].ENQUEUE [2].DEQUEUE [3].Display [4].Exit\n") ;
printf("\nEnter your choice [1-4] : ") ;
scanf("%d", &ch) ;
switch(ch)
{
case 1 :
enqueue() ;
break ;
case 2 :
dequeue() ;
break ;
case 3 :
display() ;
break ;
case 4 :
break ;
default :
printf("\nInvalid option\n") ;
getch() ;
}
} while(ch != 4) ;
getch() ;
}
void enqueue()
{
if(rear == SIZE - 1)
{
printf("\nQueue is full (overflow)\n") ;
getch() ;
return ;
}
rear++ ;
printf("\nEnter the element to ENQUEUE : ") ;
scanf("%d", &arr[rear]) ;
if(front == -1)
front++ ;
}
void dequeue()
{
if(front == -1)
{
printf("\nQueue is empty (underflow)\n") ;
getch() ;
return ;
}
printf("\nThe DEQUEUE element is : %d\n", arr[front]) ;
getch() ;
if(front == rear)
front = rear = -1 ;
else
front++ ;
}
void display()
{
if(front == -1)
{
printf("\nQueue is empty (underflow)\n") ;
getch() ;
return ;
}
printf("\nThe elements in queue are :\n\nFRONT ->") ;
for(i = front ; i <= rear ; i++)
printf(" ... %d", arr[i]) ;
printf(" ... <- REAR\n") ;
getch() ;
}


RUN 1 :
~~~~~~~
[1].ENQUEUE [2].DEQUEUE [3].Display [4].Exit
Enter your choice [1-4] : 1
Enter the element to ENQUEUE : 10
[1].ENQUEUE [2].DEQUEUE [3].Display [4].Exit
Enter your choice [1-4] : 1
Enter the element to ENQUEUE : 20
[1].ENQUEUE [2].DEQUEUE [3].Display [4].Exit
Enter your choice [1-4] : 3
The elements in queue are :
FRONT -> ... 10 ... 20 ... <- REAR
Enter your choice [1-4] : 2
The DEQUEUE element is : 10
[1].ENQUEUE [2].DEQUEUE [3].Display [4].Exit
Enter your choice [1-4] : 3
The elements in queue are :
FRONT -> ... 20 ... <- REAR
[1].ENQUEUE [2].DEQUEUE [3].Display [4].Exit
Enter your choice [1-4] : 2
The DEQUEUE element is : 20
[1].ENQUEUE [2].DEQUEUE [3].Display [4].Exit
Enter your choice [1-4] : 2
Queue is empty (underflow)
[1].ENQUEUE [2].DEQUEUE [3].Display [4].Exit
Enter your choice [1-4] : 4


Implentation of stack using arrays Using C

# include <stdio.h>
# include <conio.h>

# define SIZE 10
int arr[SIZE], top = -1, i ;

void push() ;
void pop() ;
void display() ;

void main()
{
int ch ;
clrscr() ;
do
{
printf("\n[1].PUSH [2].POP [3].Display [4].Exit\n") ;
printf("\nEnter your choice [1-4] : ") ;
scanf("%d", &ch) ;
switch(ch)
{
case 1 :
push() ;
break ;
case 2 :
pop() ;
break ;
case 3 :
display() ;
break ;
case 4 :
break ;
default :
printf("\nInvalid option\n") ;
getch() ;
}
} while(ch != 4) ;
getch() ;
}
void push()
{
if(top == SIZE - 1)
{
printf("\nStack is full (overflow)\n") ;
getch() ;
return ;
}
top++ ;
printf("\nEnter the element to PUSH : ") ;
scanf("%d", &arr[top]) ;
}
void pop()
{
if(top == -1)
{
printf("\nStack is empty (underflow)\n") ;
getch() ;
return ;
}
printf("\nThe POP element is : %d\n", arr[top]) ;
getch() ;
top-- ;
}
void display()
{
if(top == -1)
{
printf("\nStack is empty (underflow)\n") ;
getch() ;
return ;
}
printf("\nThe elements in stack are :\n\nTOP") ;
for(i = top ; i >= 0 ; i--)
printf(" -> %d", arr[i]) ;
printf("\n") ;
getch() ;
}

RUN 1 :
~~~~~~~
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 1
Enter the element to PUSH : 10
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 1
Enter the element to PUSH : 20
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 3
The elements in stack are :
TOP -> 20 -> 10
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 2
The POP element is : 20
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 3
The elements in stack are :
TOP -> 10
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 2
The POP element is : 10
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 2
Stack is empty (underflow)
[1].PUSH [2].POP [3].Display [4].Exit
Enter your choice [1-4] : 4


Wednesday, 18 March 2015

To sort the given numbers in ascending & descending order Using C


# include <stdio.h>
# include <conio.h>
void main()
{
int a[10], t, i, j, n ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nEnter the numbers :\n\n") ;
for(i = 0 ; i < n ; i++)
scanf("%d", &a[i]) ;
for(i = 0 ; i < n - 1 ; i++)
for(j = 0 ; j < n - 1 ; j++)
if(a[j] > a[j + 1])
{
t = a[j] ;
a[j] = a[j + 1] ;
a[j + 1] = t ;
}
printf("\nThe numbers in ascending order is :\n\n") ;
for(i = 0 ; i < n ; i++)
printf("%d\t", a[i]) ;
printf("\n\nThe numbers in descending order is :\n\n") ;
for(i = n -1 ; i >= 0 ; i--)
printf("%d\t", a[i]) ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter the limit : 5
Enter the numbers :
20 30 10 50 40
The numbers in ascending order is :
10 20 30 40 50
The numbers in descending order is :
50 40 30 20 10

Program to sort the given numbers using quick sort using C


# include <stdio.h>
# include <conio.h>
# include <values.h>
int a[10] ;
void main()
{
int i, n ;
void qsort(int, int) ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nEnter the elements :\n\n") ;
for(i = 0 ; i < n ; i++)
scanf("%d", &a[i]) ;
a[i] = MAXINT ;
qsort(0, n - 1) ;
printf("\nThe sorted elemets are :\n\n") ;
for(i = 0 ; i < n ; i++)
printf("%d\t", a[i]) ;
getch() ;
}
void qsort(int left, int right)
{
int i, j, t, v ;
if(left < right)
{
i = left + 1 ;
j = right ;
v = left ;
for( ; ; )
{
while(a[v] >= a[i])
i++ ;
while(a[v] < a[j])
j-- ;
if(i < j)
{
t = a[i] ;
a[i] = a[j] ;
a[j] = t ;
}
else
break ;
}
t = a[v] ;
a[v] = a[j] ;
a[j] = t ;

qsort(left, j - 1) ;
qsort(j + 1, right) ;
}
return ;
}


RUN 1 :
~~~~~~~
Enter the limit : 5
Enter the elements :
20 40 30 50 10
The sorted elemets are :
10 20 30 40 50

Program to sort the given numbers using shell sort Using C


# include <stdio.h>
# include <conio.h>
void main()
{
int i, j, k, n, a[10], t ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nEnter the elements :\n\n") ;
for(i = 0 ; i < n ; i++)
scanf("%d", &a[i]) ;
for(i = (n + 1) / 2 ; i >= 1 ; i = i / 2)
for(j = i ; j < n ; j++)
{
t = a[j] ;
for(k = j - i ; k >= 0 && t < a[k] ; k = k - i)
a[k + i] = a[k] ;
a[k + i] = t ;
}
printf("\nThe sorted elemets are :\n\n") ;
for(i = 0 ; i < n ; i++)
printf("%d\t", a[i]) ;
getch() ;
}

RUN 1 :
~~~~~~~
Enter the limit : 5
Enter the elements :
20 40 30 50 10
The sorted elemets are :
10 20 30 40 50

Program to sort the given numbers using bubble sort Using C


# include <stdio.h>
# include <conio.h>
void main()
{
int a[10], t, i, j, n ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nEnter the numbers :\n\n") ;
for(i = 0 ; i < n ; i++)
scanf("%d", &a[i]) ;
for(i = 0 ; i < n - 1 ; i++)
{
for(j = 0 ; j < n - 1 ; j++)
{
if(a[j] > a[j + 1])
{
t = a[j] ;
a[j] = a[j + 1] ;
a[j + 1] = t ;
}
}
}
printf("\nThe sorted elemets are :\n\n") ;
for(i = 0 ; i < n ; i++)
printf("%d\t", a[i]) ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter the limit : 5
Enter the numbers :
20 40 30 50 10
The sorted elemets are :
10 20 30 40 50

To sort the given numbers using selection sort Using C


# include <stdio.h>
# include <conio.h>
void main()
{
int i, j, k, left, n, a[10], t ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nEnter the elements :\n\n") ;
for(i = 0 ; i < n ; i++)
scanf("%d", &a[i]) ;
for(i = 0 ; i < n ; i++)
{
left = a[i] ;
k = i ;
for(j = i + 1 ; j < n ; j++)
if(left > a[j])
{
left = a[j] ;
k = j ;
}
a[k] = a[i] ;
a[i] = left ;
}
printf("\nThe sorted elemets are :\n\n") ;
for(i = 0 ; i < n ; i++)
printf("%d\t", a[i]) ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter the limit : 5
Enter the elements :
20 40 30 50 10
The sorted elemets are :
10 20 30 40 50

To sort the given numbers using insertion sort Using C


# include <stdio.h>
# include <conio.h>
void main()
{
int i, j, n, a[10], t ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nEnter the elements :\n\n") ;
for(i = 0 ; i < n ; i++)
scanf("%d", &a[i]) ;
for(j = 1 ; j < n ; j++)
{
t = a[j] ;
for(i = j - 1 ; i >= 0 && t < a[i] ; i--)
a[i + 1] = a[i] ;
a[i + 1] = t ;
}
printf("\nThe sorted elemets are :\n\n") ;
for(i = 0 ; i < n ; i++)
printf("%d\t", a[i]) ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter the limit : 5
Enter the elements :
20 40 30 50 10
The sorted elemets are :
10 20 30 40 50

Program to search an element using linear search Using C


# include <stdio.h>
# include <conio.h>
void main()
{
int a[10], i, n, item, flag = 0 ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nEnter the numbers :\n\n") ;
for(i = 0 ; i < n ; i++)
scanf("%d", &a[i]) ;
printf("\nEnter the element to be searched : ") ;
scanf("%d", &item) ;
for(i = 0 ; i < n ; i++)
{
if(item == a[i])
{
flag = 1 ;
break ;
}
}
if(flag == 1)
printf("\nThe element is found at location : %d", i + 1) ;
else
printf("\nThe element is not found") ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter the limit : 5
Enter the numbers :
20 40 30 50 10
Enter the element to be searched : 30
The element is found at location : 3

RUN 2 :
~~~~~~~
Enter the limit : 5
Enter the numbers :
20 40 30 50 10
Enter the element to be searched : 70
The element is not found

Program to search an element using binary search Using C


# include <stdio.h>
# include <conio.h>
void main()
{
int a[10], f, l, i, j, k, mid, n, t, flag = 0 ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nEnter the elements :\n\n") ;
for(i = 0 ; i < n ; i++)
scanf("%d", &a[i]) ;
for(i = 0 ; i < n ; i++)
for(j = i + 1 ; j < n ; j++)
if(a[i] > a[j])
{
t = a [i] ;
a[i] = a[j] ;
a[j] = t ;
}
printf("\nThe ordered elements are : \n\n") ;
for(i = 0 ; i < n ; i++)
printf("%d\t", a[i]) ;
printf("\n\nEnter the element to be searched : ") ;
scanf("%d", &k) ;
f = 0 ;
l = n - 1 ;
while(f <= l)
{
mid = (f + l) / 2 ;
if(a[mid] == k)
{
flag = 1 ;
break ;
}
else if(a[mid] < k)
f = mid + 1 ;
else
l = mid - 1 ;
}
if(flag == 1)
printf("\nThe element is found at location : %d", mid + 1) ;
else
printf("\nThe element is not found") ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter the limit : 5
Enter the elements :
20 40 30 50 10
The ordered elements are :
10 20 30 40 50
Enter the element to be searched : 30
The element is found at location : 3

RUN 2 :
~~~~~~~
Enter the limit : 5
Enter the elements :
20 40 30 50 10
The ordered elements are :
10 20 30 40 50
Enter the element to be searched : 70
The element is not found

Program to merge the contents of two files Using C


# include <stdio.h>
# include <conio.h>
void main()
{
char c ;
FILE *fptr1, *fptr2, *fptr3 ;
clrscr() ;
printf("Enter the text to be stored in the file - 1.\n") ;
printf("Use ^Z or F6 at the end of the text and press
ENTER : \n\n") ;
fptr1 = fopen("FIRST.DAT","w") ;
while((c = getc(stdin)) != EOF)
fputc(c, fptr1) ;
fclose(fptr1) ;
printf("\nEnter the text to be stored in the file - 2.\n") ;
printf("Use ^Z or F6 at the end of the text and press
ENTER : \n\n") ;
fptr2 = fopen("SECOND.DAT","w") ;
while((c = getc(stdin)) != EOF)
fputc(c, fptr2) ;
fclose(fptr2) ;
fptr1 = fopen("FIRST.DAT","r") ;
fptr2 = fopen("SECOND.DAT","r") ;
fptr3 = fopen("MERGE.DAT","w") ;
while((c = fgetc(fptr1)) != EOF)
fputc(c, fptr3) ;
fclose(fptr1) ;
while((c = fgetc(fptr2)) != EOF)
fputc(c, fptr3) ;
fclose(fptr2) ;
fclose(fptr3) ;
printf("\nThe content of the merged file is : \n\n") ;
fptr3 = fopen("MERGE.DAT", "r") ;
while((c = fgetc(fptr1)) != EOF)
putchar(c) ;
fclose(fptr3) ;
getch() ;
}


RUN 1 :
~~~~~~~

Enter the text to be stored in the file - 1.
Use ^Z or F6 at the end of the text and press ENTER :
Computer Practice - I
I - Semester
^Z
Enter the text to be stored in the file - 2.
Use ^Z or F6 at the end of the text and press ENTER :
Computer Practice - II
II - Semester
^Z
The content of the merged file is :
Computer Practice - I
I - Semester
Computer Practice - II
II - Semester

Program to encrypt and decrypt a file Using C


# include <stdio.h>
# include <conio.h>

void main()
{
FILE *fptr;
char c ;
clrscr() ;
printf("Enter the text to be stored in the file.\n") ;
printf("Use ^Z or F6 at the end of the text and press
ENTER : \n\n") ;
fptr = fopen("ENCDEC.DAT","w") ;
while((c = getchar()) != EOF)
fputc(c, fptr) ;
fclose(fptr) ;
printf("\n\nData output in encrypted form : \n\n") ;
fptr = fopen("ENCDEC.DAT", "r") ;
while((c = fgetc(fptr)) != EOF)
printf("%c", c+1) ;
fclose(fptr) ;
printf("\n\nData output in decrypted form : \n\n") ;
fptr = fopen("ENCDEC.DAT", "r") ;
while((c = fgetc(fptr)) != EOF)
printf("%c", c) ;
fclose(fptr) ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter the text to be stored in the file.
Use ^Z or F6 at the end of the text and press ENTER :
Computer Practice - II
D.D. Publications
^Z
Data output in encrypted form :
Dpnqvufs!Qsbdujdf!.!JJ
E/E/!Qvcmjdbujpot
Data output in decrypted form :
Computer Practice - II
D.D. Publications

Program to maintain employee details using files in C


# include <stdio.h>
# include <conio.h>
void main()
{
FILE *fptr ;
int i, n, empno ;
float bpay, allow, ded ;
char name[10] ;
clrscr() ;
fptr = fopen("EMPLOYEE.DAT", "w") ;
printf("Enter the number of employees : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the employee number : ") ;
scanf("%d", &empno) ;
printf("\nEnter the name : ") ;
scanf("%s", name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%f %f %f", &bpay, &allow, &ded) ;
fprintf(fptr, "%d %s %f %f %f \n", empno,name,bpay,allow,ded);
}
fclose(fptr) ;
fptr = fopen("EMPLOYEE.DAT", "r") ;
printf("\nEmp. No.Name\t\t Bpay\t\t Allow\t\t Ded\t\t Npay\n\n");
for(i = 0 ; i < n ; i++)
{
fscanf(fptr,"%d%s%f%f%f\n", &empno,name,&bpay,&allow,&ded);
printf("%d \t %s \t %.2f \t %.2f \t %.2f \t %.2f \n",
empno, name, bpay, allow, ded, bpay + allow - ded) ;
}
fclose(fptr) ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter the number of employees : 2
Enter the employee number : 101
Enter the name : Udaya
Enter the basic pay, allowances & deductions : 6000 1000 500
Enter the employee number : 102
Enter the name : Priya
Enter the basic pay, allowances & deductions : 5000 1000 450

Emp. No. Name   Bpay      Allow     Ded     Npay

101          Udaya  6000.00 1000.00 500.00 6500.00
102          Priya    5000.00 1000.00 450.00 5550.00

Read integers and store odd & even no. in a file Using C


# include <stdio.h>
# include <conio.h>

void main()
{
FILE *fptr1, *fptr2, *fptr3 ;
int n, i, num ;
clrscr() ;
printf("Enter number of values : ") ;
scanf("%d", &n) ;
printf("\nEnter the values : ") ;
fptr1 = fopen("NUMBERS.DAT", "w") ;
for(i = 0 ; i < n ; i++)
{
scanf("%d", &num) ;
putw(num, fptr1) ;
}
fclose(fptr1) ;
fptr1 = fopen("NUMBERS.DAT", "r") ;
fptr2 = fopen("ODD.DAT", "w") ;
fptr3 = fopen("EVEN.DAT", "w") ;
while((num = getw(fptr1)) != EOF)
{
if(num % 2 == 0)
putw(num, fptr3) ;
else
putw(num, fptr2) ;
}
fclose(fptr1) ;
fclose(fptr2) ;
fclose(fptr3) ;
fptr2 = fopen("ODD.DAT", "r") ;
fptr3 = fopen("EVEN.DAT", "r") ;
printf("\nContents of ODD file is : ") ;
while((num = getw(fptr2)) != EOF)
printf("%d\t", num) ;
printf("\n\nContents of EVEN file is : ") ;
while((num = getw(fptr3)) != EOF)
printf("%d\t", num) ;
fclose(fptr2) ;
fclose(fptr3) ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter number of values : 6
Enter the values : 11 22 33 44 55 66
Contents of ODD file is : 11 33 55
Contents of EVEN file is : 22 44 66

Program to maintain student details using files Using C


# include <stdio.h>
# include <conio.h>
void main()
{
FILE *fptr ;
int i, n, rollno, s1, s2 ;
char name[10] ;
clrscr() ;
fptr = fopen("STUDENT.DAT", "w") ;
printf("Enter the number of students : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the roll number : ") ;
scanf("%d", &rollno) ;
printf("\nEnter the name : ") ;
scanf("%s", name) ;
printf("\nEnter the marks in 2 subjects : ") ;
scanf("%d %d", &s1, &s2) ;
fprintf(fptr, "%d %s %d %d \n", rollno, name, s1, s2) ;
}
fclose(fptr) ;
fptr = fopen("STUDENT.DAT", "r") ;
printf("\nRoll No. Name \t\t Sub1 \t Sub2 \t Total\n\n") ;
for(i = 0 ; i < n ; i++)
{
fscanf(fptr,"%d %s %d %d \n", &rollno, name, &s1, &s2) ;
printf("%d \t %s \t\t %d \t %d \t %d \n", rollno, name,
s1, s2, s1 + s2) ;
}
fclose(fptr) ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter the number of students : 2
Enter the roll number : 101
Enter the name : Udaya
Enter the marks in 2 subjects : 75 80
Enter the roll number : 157
Enter the name : Viji
Enter the marks in 2 subjects : 60 70

Roll No. Name Sub1 Sub2 Total
101       Udaya 75     80     155
157       Viji      60     70     130

Program to write and read data from a file Using C


# include <stdio.h>
# include <conio.h>
void main()
{
char c ;
FILE *fptr1 ;
clrscr() ;
printf("Enter the text to be stored in the file.\n") ;
printf("Use ^Z or F6 at the end of the text and press
ENTER: \n\n") ;
fptr1 = fopen("COURSES.DAT","w") ;
while((c = getc(stdin)) != EOF)
fputc(c, fptr1) ;
fclose(fptr1) ;
printf("\nThe content of the file is : \n\n") ;
fptr1 = fopen("COURSES.DAT", "r") ;
do
{
c = fgetc(fptr1) ;
putchar(c) ;
} while(c != EOF) ;
fclose(fptr1) ;
getch() ;
}

RUN 1 :
~~~~~~~
Enter the text to be stored in the file.
Use ^Z or F6 at the end of the text and press ENTER:
Computer Science & Engineering
Information Technology
Electronics & Communication Engineering
^Z
The content of the file is :
Computer Science & Engineering
Information Technology
Electronics & Communication Engineering

To compare the given two string using pointers Using C


# include <stdio.h>
# include <conio.h>
void main()
{
char *str1, *str2 ;
clrscr() ;
printf("Enter the first string : ") ;
scanf("%s", str1) ;
printf("\nEnter the second string : ") ;
scanf("%s", str2) ;
while(*str1 == *str2 && (*str1 != '\0' || *str2 != '\0'))
{
str1++ ;
str2++ ;
}
if(*str1 == '\0' && *str2 == '\0')
printf("\nThe given strings are equal") ;
else
printf("\nThe given strings are not equal") ;
getch() ;
}

RUN 1 :
~~~~~~~
Enter the first string : cse
Enter the second string : ece
The given strings are not equal
RUN 2 :
~~~~~~~
Enter the first string : mech
Enter the second string : mech
The given strings are equal