Tuesday, March 8, 2016

OOPS

Let us discuss some of the main features of object oriented programming which you will be using in C++.
ObjectsClassesAbstractionEncapsulationInheritanceOverloadingException Handling

Objects
Objects are the basic unit of OOP. They are instances of class, which have data members and uses various member functions to perform tasks.

Class
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. In 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
Polymorphismn 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.
Association, Aggregation, and Composition?
enter image description here
Association is a *has-a* relationship between two classes where there is no particular ownership in place. It is just the connectivity between the two classes. When you define a variable of one class in another class, you enable first to associate functions and properties of the second class. Then again  both Aggregation and Composition are types of Association.


Aggregation is a weak type of Association with partial ownership. For an Aggregation relationship, we use the term *uses* to imply a weak *has-a* relationship. This is weak compared to Composition. Then again, weak meaning the linked components of the aggregator may survive the aggregations life-cycle without the existence of their parent objects. For example, a school department *uses* teachers. Any teacher may belong to more than one department. And so, if a department ceases to exist, the teacher will still exist.
Aggregration
An aggregation is a specific type of composition where no ownership between the complex object and the subobjects is implied. When an aggregate is destroyed, the subobjects are not destroyed.
For example, consider the math department of a school, which is made up of one or more teachers. Because the department does not own the teachers (they merely work there), the department should be an aggregate. When the department is destroyed, the teachers should still exist independently (they can go get jobs in other departments).
Because aggregations are just a special type of compositions, they are implemented almost identically, and the difference between them is mostly semantic. In a composition, we typically add our subclasses to the composition using either normal variables or pointers where the allocation and deallocation process is handled by the composition class.

On the other hand, Composition is a strong type of Association with full ownership. This is strong compared to the weak Aggregation. For a Composition relationship, we use the term*owns* to imply a strong *has-a* relationship. For example, a department *owns* courses, which means that the any course's life-cycle depends on the department's life-cycle. Hence, if a department ceases to exist, the underlying courses will cease to exist as well.
Whenever there is no ownership in place, we regard such a relationship as just an Association and we simply use the *has-a* term, or sometimes the verb describing the relationship. For example, a teacher *has-a* or *teaches* a student. There is no ownership between the teacher and the student, and each has their own life-cycle.
In real-life, complex objects are often built from smaller, simpler objects. For example, a car is built using a metal frame, an engine, some tires, a transmission, a steering wheel, and a large number of other parts. A personal computer is built from a CPU, a motherboard, some memory, etc… Even you are built from smaller parts: you have a head, a body, some legs, arms, and so on. This process of building complex objects from simpler ones is called composition (also known as object composition).
More specifically, composition is used for objects that have a has-a relationship to each other. A car has-a metal frame, has-an engine, and has-a transmission. A personal computer has-aCPU, a motherboard, and other components. You have-a head, a body, some limbs.
Abstraction and Generalization?
Abstraction is an emphasis on the idea, qualities and properties rather than the particulars (a suppression of detail). The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs.
While abstraction reduces complexity by hiding irrelevant detail, generalization reduces complexity by replacing multiple entities which perform similar functions with a single construct. Generalization is the broadening of application to encompass a larger domain of objects of the same or different type. Programming languages provide generalization through variables, parameterization, generics and polymorphism. It places the emphasis on the similarities between objects. Thus, it helps to manage complexity by collecting individuals into groups and providing a representative which can be used to specify any individual of the group.
Abstraction and generalization are often used together. Abstracts are generalized through parameterization to provide greater utility. In parameterization, one or more parts of an entity are replaced with a name which is new to the entity. The name is used as a parameter. When the parameterized abstract is invoked, it is invoked with a binding of the parameter to an argument.

Inheritance:
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class(or parent class or super class), and the new class is referred to as the derived class(or child class or subclass).
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.
A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes.

Types of Inheritance:
Single
Multiple
Hierarchical
Multilevel
Hybrid
In C++, we have 5 different types of Inheritance. Namely,
  1. Single Inheritance
  2. Multiple Inheritance
  3. Hierarchical Inheritance
  4. Multilevel Inheritance
  5. Hybrid Inheritance (also known as Virtual 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.
Single Inheritance in C++

Multiple Inheritance

In this type of inheritance a single derived class may inherit from two or more than two base classes.
Multiple Inheritance in C++

Hierarchical Inheritance

In this type of inheritance, multiple derived classes inherits from a single base class.
Hierarchical Inheritance in C++

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.
Multilevel Inheritance in C++

Hybrid (Virtual) Inheritance

Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.
Hybrid Inheritance in C++


Thursday, March 3, 2016

Friend

FRIEND FUNCTIONS
 A friend function has access to all private and protected members of the class for which it is a friend. To declare a friend function, include its prototype within the class, preceding it with the keyword friend.

FRIENDS
A friend is permitted full access to private and protected members. A friend can be a function, function template, or member function, or a class or class template.
 Use the friend specifier to declare a friend in the class granting friendship.
Note that friendship is given, not taken.
In other words, if class A contains the declaration friend class B;, class B can access the private members of A, but A has no special privileges to access B (unless B declares A as a friend).
By convention, the friend specifier is usually first, although it can appear in any order with other function and type specifiers. The friend declaration can appear anywhere in the class; the access level is not relevant.
You cannot use a storage class specifier in a friend declaration. Instead, you should declare the function before the class definition (with the storage class, but without the friend specifier), then redeclare the function in the class definition (with the friend specifier and without the storage class). The function retains its original linkage. If the friend declaration is the first declaration of a function, the function gets external linkage. For example:
class demo;
void func(demo d);
class demo {
  friend void func(demo);
};



#include <iostream>
class myclass {
int a, b;
public:
friend int sum(myclass x);
void getdata (int i, int j);
};
void myclass:: getdata(int i, int j)
{
a = i;
b = j;
}
// Note: sum() is not a member function of any class.
int sum(myclass x)
{
/* Because sum() is a friend of myclass, it can directly access a and b. */
return (x.a + x.b);
}
int main()
{
myclass A;
A. getdata(3, 4);
cout << sum(n);
return 0;
}
In this example, the sum() function is not a member of myclass. However, it still has full access to its private members. Also, notice that sum() is called without the use of the dot operator. Because it is not a member function, it does not need to be (indeed, it may not be) qualified with an object's name.
Although there is nothing gained by making sum() a friend rather than a member function of myclass, there are some circumstances in which friend functions are quite valuable. First, friends can be useful when you are overloading certain types of operators. Second, friend functions make the creation of some types of I/O functions easier. The third reason that friend functions may be desirable is that in some cases, two or more classes may contain members that are interrelated relative to other parts of your program.

#include<iostream.h>
#include<conio.h>
class A;
class B
{
private:int p;
public:
friend void getdata(A p, B &q);// try without these references
void friend dispdata(A &p, B &q);
};

class A
{
private:int p;
public:
friend void getdata(A p, B &q);
void friend dispdata(A &p, B &q);
};

void getdata(A q, B &r)
{
cout<<"\nenter values\t";
cin>>q.p>>r.p   ;
}

void dispdata(A &q, B &r)
{
cout<<"the values are\t";
cout<<endl<<q.p<<endl<<r.p   ;
}


void main()
{
clrscr();
int a=10;
//add(a);
cout<<endl<<a;
A o1;
B o2;
getdata(o1,o2);
dispdata(o1,o2);
getch();
}

Default Arguments

Default Function Arguments
C++ allows a function to assign a parameter a default value when no argument corresponding to that parameter is specified in a call to that function. The default value is specified in a manner syntactically similar to a variable initialization. For example, this declares myfunc() as taking one double argument with a default value of 0.0:
void myfunc(double d = 0.0)
{
// ...
}
Now, myfunc() can be called one of two ways, as the following examples show:
myfunc(198.234); // pass an explicit value
myfunc(); // let function use default
The first call passes the value 198.234 to d. The second call automatically gives d the default value zero.
One reason that default arguments are included in C++ is because they provide another method for the programmer to manage greater complexity. To handle the widest variety of situations, quite frequently a function contains more parameters than are required for its most common usage. Thus, when the default arguments apply, you need specify only the arguments that are meaningful to the exact situation, not all those needed by the most general case.
If you supply a default parameter, all other parameters following that parameter in the parameter list must have defaults too.
Using default arguments is essentially a shorthand form of function overloading.
To give a parameter a default argument, simply follow that parameter with an equal sign and the value you want it to default to if no corresponding argument is present when the function is called. For example, this function gives two parameters default values of 0:
void f(int a=0, int b=0);
Notice that this syntax is similar to variable initialisation. This function can now be called three different ways:
• It can be called with both arguments specified.
• It can be called with only the first argument specified (in this case b will default to 0).
• It can be called with no arguments (both a and b default to 0).

That is the following calls to the function f are valid,
f( ); // a and b default to 0
f(10); // a is 10 and b defaults to 0
f(10, 99); // a is 10 and b is 99


default parameter (also called an optional parameter or a default argument) is a function parameter that has a default value provided to it. If the user does not supply a value for this parameter, the default value will be used. If the user does supply a value for the default parameter, the user-supplied value is used instead of the default value.

Rules to implement the concept of Default Arguments:
1. When you create a function that has one or more default arguments, those arguments must be specified only once: either in the function's prototype or in the function's definition if the definition precedes the function's first use. 
2. The defaults cannot be specified in both the prototype and the definition. This rule applies even if you simply duplicate the same defaults.
3. All default parameters must be to the right of any parameters that don't have defaults. Further, once you begin define default parameters, you cannot specify any parameters that have no defaults.
4. Default arguments must be constants or global variables. They cannot be local variables or other parameters.
5. Default arguments often provide a simple alternative to function overloading. Of course there are many situations in which function overloading is required.
6. It is not only legal to give constructor functions default arguments, it is also common. Many times a constructor is overloaded simply to allow both initialised and uninitialised objects to be created.




Monday, November 30, 2015

Files in C: MCA I

Files in C
Files are used to store data’s in the secondary memory(eg:- hard disk, floppy, flash disk etc).
There are various file operations that can be done in C like Creating a file, deleting a file, renaming a file, opening a file to read/write/append data’s etc.

Syntax for declaring a file pointer in C

FILE *file_pointer;
Eg :- FILE *fp;
Where,
FILE = keyword
*fp = user defined file pointer variable.

Once the file pointer is declared next step is to create/open a file.

Creating / opening a file in C

fopen() is used to open a specified file from disk, if it exist. If it doesn’t exist a new file will be created and opened for further file operations.

Syntax for fopen() in C

fp=fopen(“file_name with extension”,”mode”);
Where,
fp= user defined file pointer variable.
filename= name of the file with file type as extension.
mode= mode in which the file is to be opened.

Eg :-
To Read – “r”, To Write - “w”, To Append – “a”
To Read & Write – “w+”, To Read and write – “ r+” 
To Read Write with append – “a+”

In w+ mode the contents in existing file is destroyed and then can perform read/write operations.
In r+ mode just read and write operations can be performed.
In a+ mode we can perform read and write operations with appending contents. So no existing data’s in a file are destroyed.
Eg :-
fp=fopen(“data.txt”,”a+”);

After a file is opened, we have to perform read or wrote operations into it.

Writing to a file in C

fprintf()

fprintf() is used to write data’s to a file from memory.

Syntax for fprintf()

fprintf(file pointer,”control string”,variables);
eg:- fprintf(fp,”%s”,name);

Reading from a file in C

fscanf() is used to read data from a file to the memory.

Syntax for fscanf()

fscanf(file pointer,”control string”,variables);
eg:- fscanf(fp,”%s”,name);

Closing a file in C

fclose() is used to close a file in C.

Syntax for fclose()

fclose(fp);
Where, fp= user-defined file pointer.

Reading and Writing to a file in C

Sample Program :
fprintf_fscanf.c
#include<stdio.h>
#include<conio.h>

void main()
{
FILE *fp;
char c[60];
int no,n;
fp=fopen("data2.txt","a+");

printf("Enter the Employee Name and No : ");
scanf("%s %d",c,&no);
fprintf(fp,"\n\n%s\n%d",c,no);

rewind(fp);

printf("Enter the Employee No : ");
scanf("%d",&n);
while(!feof (fp))
{
fscanf(fp,"%s %d",c,&no);
if(no==n)
{
printf("\n%s \n %d",c,no);
}
}
fclose(fp);
getch();
}



Input Output Functions in C: MCA I

getchar(): It reads a character from the keyboard. It is executed when a key is pressed and the pressed key is echoed to screen.
getch(): getch() function returns just after the keypress and the pressed key is not echoed to screen. It can be used in an interactive environment.
getche(): getch() function returns just after the keypress and the pressed key is echoed to the screen. It can be used in an interactive environment.

putchar(): At current cursor position, putchar() prints a character to screen

Formatted I/O in C :

The formatted Input / Output functions can read and write values of all data types, provided the appropriate conversion symbol is used to identify the datatype.
scanf is used for receiving formatted Input andprintf is used for displaying formatted output.
Syntax for scanf :
scanf(“control_string 1, - - , control_string n”,&variable1, - - - - ,variable n);
Syntax for printf :
printf(“control_string 1, - - , control_string n”,variable1, - - - - , variable n);
Sample Program :
printf_scanf.c
#include<stdio.h>
#include<conio.h>
void main()
{
int no;
char ch;
char s[20];

printf("Enter a character : ");
scanf("%c",&ch);

printf("Enter a No : ");
scanf("%d",&no);


printf("Enter a Word or String : ");
scanf("%s",&s);

printf("\n Character : %c",ch);
printf("\n No : %d",no);
printf("\n String : %s",s);

getch();
}


Unformatted I/O in C

            Unformatted I/O functions works only with character datatype (char).
            The unformatted Input functions used in C are getch(), getche(), getchar(), gets().

Syntax for getch () in C :
variable_name = getch();
getch() accepts only single character from keyboard. The character entered through getch() is not displayed in the screen (monitor).
Syntax for getche() in C :
variable_name = getche();
Like getch(), getche() also accepts only single character, but unlike getch(), getche() displays the entered character in the screen.
Syntax for getchar() in C :
variable_name = getchar();
getchar() accepts one character type data from the keyboard.
Syntax for gets()  in C :
gets(variable_name);
gets() accepts any line  of string including spaces from the standard Input device (keyboard). gets() stops reading character from keyboard only when the enter key is pressed.

The unformatted output statements in C are putch, putchar and puts.
Syntax for putch in C :
putch(variable_name);
putch displays any alphanumeric characters to the standard output device. It displays only one character at a time.
Syntax for putchar in C :
putchar(variable_name);
putchar displays one character at a time to the Monitor.
Syntax for puts in C :
puts(variable_name);
puts displays a single / paragraph of text to the standard output device.
Sample program :
gets_puts.c
#include<stdio.h>
#include<conio.h>
void main()
{
char a[20];
gets(a);
puts(a);

getch();
}


String functions / Operations in C

1) strlen() in C :

This function is used to determine the length of a given string.
Syntax :
variable=strlen(“string”);
The string length will be returned to the variable.
Sample Program
str_length.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[30];
int l;
printf("Enter a string : ");
scanf("%s",&a);
l=strlen(a);
printf("\n Length of the Given String is : %d",l);

getch();
}


2) strcpy() in C :
This function copies the string from one variable to another variable.
Syntax :
strcpy(source_variable, destination_variable);
Sample Program
str_cpy.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[30],b[30];
printf("Enter a string : ");
scanf("%s",&a);
strcpy(b,a);
printf("Value of a : %s",a);
printf("\nValue of b : %s",b);
getch();
}

3) strcmp() in C :
This function is used to compare two strings. They are case sensitive.
Syntax :
strcmp(string1,string2);
If both the strings are equal return value will be 0, else non_zero value will be returned.
Sample program :
str_cmp.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[30],b[30];
int n;
printf("Enter string one : ");
scanf("%s",&a);
printf("Enter string two : ");
scanf("%s",&b);
n=strcmp(a,b);
if(n==0)
{
printf("Both the Strings are Equal");
}
else
{
printf("Strings are not Equal");
}
getch();
}

4) strlwr() in C :
This function converts uppercase characters to lowercase.
Syntax :
strlwr(“string”);
Sample program :
str_lwr.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[30];
printf("Enter a string in uppercase : ");
scanf("%s",&a);

printf("RESULT : %s",strlwr(a));

getch();
}


5) strupr() in C :
This function converts lowercase characters to uppercase.
Syntax :
strupr(“string”);
Sample program :
str_upr.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[30];
printf("Enter a string in lowercase : ");
scanf("%s",&a);

printf("RESULT : %s",strupr(a));

getch();
}


6) strrev() in C :
This function is sued to reverse the characters in a given string.
Syntax :
strrev(string);
Sample program :
str_rev.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[30];
printf("Enter string : ");
scanf("%s",&a);
strrev(a);

printf("Reversed String : %s",a);

getch();
}



Thursday, November 26, 2015

Storage Classes in C : MCA I

Storage classes

In C language, each variable has a storage class which decides scope, visibility and lifetime of that variable. The following storage classes are most oftenly used in C programming,
  1. Automatic variables
  2. External variables
  3. Static variables
  4. Register variables

Automatic variables

A variable declared inside a function without any storage class specification, is by default an automatic variable. They are created when a function is called and are destroyed automatically when the function exits. Automatic variables can also be called local variables because they are local to a function. By default they are assigned garbage value by the compiler.
void main()
{
 int detail;
 or 
 auto int detail;    //Both are same
}

External or Global variable

A variable that is declared outside any function is a Global variableGlobal variables remain available throughout the entire program. One important thing to remember about global variable is that their values can be changed by any function in the program.
int number;
void main()
{
 number=10;
}
fun1()
{
 number=20;
}
fun2()
{
 number=30;
}
Here the global variable number is available to all three functions.

extern keyword

The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else. The extern declaration does not allocate storage for variables.
extern keyword in c

Problem when extern is not used

main()
{
  a = 10;      //Error:cannot find variable a
  printf("%d",a);    
}

Example Using extern in same file

main()
{
  extern int x;  //Tells compiler that it is defined somewhere else
  x = 10;      
  printf("%d",x);    
}

int x;    //Global variable x

Static variables

static variable tells the compiler to persist the variable until the end of program. Instead of creating and destroying a variable every time when it comes into and goes out of scope, static is initialized only once and remains into existence till the end of program. A static variable can either be internal or external depending upon the place of declaraction. Scope of internal static variable remains inside the function in which it is defined. External static variables remain restricted to scope of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.
void test();   //Function declaration (discussed in next topic)
 
main()
{
 test();
 test();
 test();
}
void test()
{
 static int a = 0;        //Static variable
 a = a+1;
 printf("%d\t",a);
}
output :
1 2 3

Register variable

Register variable inform the compiler to store the variable in register instead of memory. Register variable has faster access than normal variable. Frequently used variables are kept in register. Only few variables can be placed inside register.
NOTE : We can never get the address of such variables.
Syntax :
register int number;

Theory: UML BCA III

A Class Diagram provides an overview of a system by showing its classes and the relationships among them. Class diagrams are static - they display what interacts, but not what happens when they do interact.

Object Diagrams show instances instead of classes. They are useful for explaining small pieces with complicated relationships, especially recursive relationships. Objects are indicated by placing the name of the object (instance name) to the left of the class name and separating the two names by a colon. Object names are typically underlined in a UML diagram to visually help in distinguishing them from classes (e.g. anObject:ClassA).

UML Statechart Diagram (STD)

          Shows the sequences of states that objects of a class go through during its life cycle in response to external events and also the responses and actions in reaction to an event.
          Model elements
        States
        Transitions
        Events
        Actions and activities
STD Elements
          A Event - is a significant or noteworthy occurrence
        e.g. a phone receiver is taken off the hook
          A State - is the condition of an object at a moment in time
                             - the time between events.
        e.g. a phone is in the state of being “idle” after the receiver is placed on the hook until it is taken off the hook.
          A transition - is a relationship between two states that indicates that when an event occurs, the object moves from the prior state to the subsequent state.
        e.g. when the the event “off hook” occurs, transition the phone from the “idle” to “active” state.














Event Types
          External Event (also known as system event)
        is caused by something outside the system boundary
        e.g. when a cashier presses the “enter item” button on a POST, an external event has occurred.
          Internal Event
        is caused by something inside our system boundary.
        In terms of SW, an internal event arises when an operation is invoked via a message sent from another internal object. (The messages in collaboration diagrams suggest internal events)
          Temporal Event
        is caused by the occurrence of a specific date and time or passage of time.
State
          Abstraction of attribute values and links of an object
          Sets of values are grouped together into a state
          Corresponds to the interval between two events received by the object
        events represent points in time
        states represent intervals of time
        Has duration
        Often associated with a
        continuous activity
        value satisfying some condition
        Event separates two states
        State separates two events
State Diagram
          Graph relating events and states
          Nodes are states; arcs are events
          Describes behaviour of a single class of objects
          Can represent
        one-shot life cycles
        continuous loops
          Continuous loop
        graph is a loop
        no definite start state
        not concerned about how the loop starts


Transition
A transition is a relationship between two states indicating that an object in the first state will, when a specified set of events and conditions are satisfied, perform certain actions and enter the second state. A transition has:
Transition Components
        a source state
        an event trigger
        an action
        a target state
Transition Actions, Guard Conditions
          Transition Actions
        a transition can cause an action to fire. In SW, this may represent the invocation of a method of an object
          Transition Guard conditions
        a transition may also have a conditional guard -- or boolean test. The transition is only taken if the test passes.



Nested State Diagrams
          State diagrams can get complex
          For better understanding and management
          A State in a state diagram can be expanded into a state diagram at another level
          Inheritance of transitions



Some very important examples