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










Tuesday, November 24, 2015

template programs

#include<iostream.h>
#include<conio.h>
template <class T>
T add(T a, T b)
{
T c;
c=a+b;
return(c);
}
template < class T>
void print (T a, int b)
{
for(int i=0;i<b;i++)
{cout<<a;}

}

template < class T>
T max( T a, T b, T c)
{
if(a>b && a>c)
{return(a);}

if(b>c && b>c)
{return(b);}
if(c>a && c>b )
{return(c);}

}


void main()
{
clrscr();
cout<<add(4,5);
cout<<add(3.4,4.5);
cout<<add('A','B');
print('%',3);
print("&&",2);
cout<<max(9,6,56);
cout<<max('A', 'D', 'B');
getch();
}

===============================================


#include<iostream.h>
#include<conio.h>
template <class T>
class Array
{
T *A;
int sz;
public:
Array(int n)
{
sz=n;
}
//template <class T>
void getdata()
{
int i;
for(i=0;i<sz;i++)
{
cin>> A[i];
}
}
//template <class T>
void disp()
{
int i;
for(i=0;i<sz;i++)
{
cout<< A[i];
}
}
} ;


void main()
{
clrscr();
Array <int> Obj1(3);
Array <char> Obj2(4);
Obj1.getdata();
Obj1.disp();
Obj2.getdata();
Obj2.disp();
getch();
}

generic programming

Generic programming is about generalizing software components so that they can be easily reused in a wide variety of situations. In C++, class and function templates are particularly effective mechanisms for generic programming because they make the generalization possible without sacrificing efficiency.


Generic programming means that you are not writing source code that is compiled as-is but that you write "templates" of source codes that the compiler in the process of compilation transforms into source codes.


The goal of generic programming is to write code that is independent of the data types. In C language, all codes are tied to a specific data type. For container data structures (such as array and structure), you need to specify the type of the elements. For algorithms (such as searching or sorting), the code works only for a specific type, you need to rewrite the code for another type. Can we write a single sorting routine that works on all types (or most of the types) by specifying the type during invocation? Can we have a general container that can work on all types?
Template lets you program on generic type, instead of on a specific type. Template supports so-called parameterized type - i.e., you can use type as argument in building a class or a function (in class template or function template). Template is extremely useful if a particular algorithm is to be applied to a variety of types, e.g., a container class which contains elements, possibly of various types.

Function Template

function template is a generic function that is defined on a generic type for which a specific type can be substituted. Compiler will generate a function for each specific type used. Because types are used in the function parameters, they are also called parameterized types.
The syntax of defining function template is:
template <typename T> OR template <class T>
return-type function-name(function-parameter-list) { ...... }

Class Template

The syntax for defining a class template is as follow, where T is a placeholder for a type, to be provided by the user.
template <class T>    // OR template <typename T>
class ClassName {
   ......
}
The keywords class and typename (newer and more appropriate) are synonymous in the definition of template.
To use the template defined, use the syntax ClassName<actual-type>.

Friday, November 20, 2015

Virtual Functions Programs:I II III

#include<iostream.h>
class Base
{
public:
int b;
void show()
{
cout<<"\n Hello I m in Base";
}
};

class Derv:public Base
{
public:
int d;
void show()
{
cout<<"\n Hello I m in Derv";
}
}  ;


int main()
{
Base B, *bptr;
Derv D,*dptr;

//CASE I
bptr=&B;
bptr->show(); // In Base

//CASE II
bptr=&D;
bptr->show(); // In Base

//CASE III
//dptr=&B; //Not OK, cant convert

//CASE IV
dptr=&D;
dptr->show();           //In Derv

}



==============================
#include<iostream.h>
class Base
{
public:
int b;
void show()
{
cout<<"\n Hello I m in Base show";
}
virtual void disp()
{
cout<<"\n Hello I m in Base disp";
}
virtual void display()
{
cout<<"\n Hello I m in Base display";
}
};
class Derv:public Base
{
public:
int d;
void show()
{
cout<<"\n Hello I m in Derv show";
}
void disp()
{
cout<<"\n Hello I m in Derv disp";
}
}  ;


int main()
{
Base B, *bptr;
Derv D,*dptr;
B.show();        //Base
B.disp();       // Base
B.display();    //Base

D.show();        //Derv
D.disp();       //Derv
D.display();    //Base


bptr=&B;
bptr->show(); // In Base
bptr->disp(); // In Base //////********
bptr->display();  // In Base

bptr=&D;
bptr->show(); // In Base
bptr->disp(); // In Derv   ////////*********
bptr->display(); // In Base

//////*****This is run time polymorphism
}
=================


#include<iostream.h>
class Figure
{
public:
virtual void showarea(){};
};
class Tri:public Figure
{
public:
void showarea()
{
cout<<"\n Hello I m in Triangle";
}
}  ;


class Rect:public Figure
{
public:
void showarea()
{
cout<<"\n Hello I m in Rectangle";
}
}  ;


class Square:public Figure
{
public:
void showarea()
{
cout<<"\n Hello I m in Square";
}
}  ;


int main()
{
Figure *fptr[3];
Tri T;
Rect R;
Square S;
fptr[0]=&T;
fptr[1]=&R;
fptr[2]=&S;
for(int i=0;i<3;i++)
{
fptr[i]->showarea();
}
}

Virtual Functions

Virtual Function
A Virtual function is a function which is declared in base class using the keyword virtual. We write the body of virtual function in the derived classes. Its purpose is to tell the compiler that what function we would like to call on the basis of the object of derived class. C++ determines which function to call at run time on the type of object pointer to.
=============
The way to retain the behavior of the object’s instantiated type is through the use of virtual functions. To declare a method to be a virtual function, you simply use the virtual keyword when declaring the method in the class definition. When you call a function, it will check the dynamic type of the object before choosing which function to call—this process is called reification.

It is important that you declare the function to be virtual throughout your class hierarchy, or its behavior will be quite unexpected. A virtual method can call a nonvirtual method and vice-versa. Overloaded operator functions can be virtual functions, but static methods can’t be.
A constructor cannot be a virtual function because it needs to know the exact type to create. However, a destructor can be declared as virtual, and generally should be. virtual functions may not seem significant at first, but they enable a ton of code reuse when using class hierarchies. und Circle, Shape, and Rectangle objects, the client doesn’t have to as long as all of the relevant functions are virtual==========
===================