Use Case Diagrams

·

A use case is a set of scenarios that describing an interaction between a user and a system. A use case diagram displays the relationship among actors and use cases. The two main components of a use case diagram are use cases and actors.








An actor is represents a user or another system that will interact with the system you are modeling. A use case is an external view of the system that represents some action the user might perform in order to complete a task.

When to Use: Use Cases Diagrams
Use cases are used in almost every project. The are helpful in exposing requirements and planning the project. During the initial stage of a project most use cases should be defined, but as the project continues more might become visible.

How to Draw: Use Cases Diagrams
Use cases are a relatively easy UML diagram to draw, but this is a very simplified example. This example is only meant as an introduction to the UML and use cases. If you would like to learn more see the Resources page for more detailed resources on UML.
Start by listing a sequence of steps a user might take in order to complete an action. 
For example a user placing an order with a sales company might follow these steps.

1. Browse catalog and select items.
2. Call sales representative.
3. Supply shipping information.
4. Supply payment information.
5. Receive conformation number from salesperson.
These steps would generate this simple use case diagram:























This example shows the customer as a actor because the customer is using the ordering system. The diagram takes the simple steps listed above and shows them as actions the customer might perform. The salesperson could also be included in this use case diagram because the salesperson is also interacting with the ordering system.

From this simple diagram the requirements of the ordering system can easily be derived. The system will need to be able to perform actions for all of the use cases listed. As the project progresses other use cases might appear. The customer might have a need to add an item to an order that has already been placed. This diagram can easily be expanded until a complete description of the ordering system is derived capturing all of the requirements that the system will need to perform.


Read More......

Types of UML Diagrams

·

Each UML diagram is designed to let developers and customers view a software system from a different perspective and in varying degrees of abstraction. UML diagrams commonly created in visual modeling tools include:

• Use Case Diagram displays the relationship among actors and use cases.

• Class Diagram models class structure and contents using design elements such as classes, packages and objects. It also displays relationships such as containment, inheritance, associations and others. 

• Interaction Diagrams

• Sequence Diagram displays the time sequence of the objects participating in the interaction. This consists of the vertical dimension (time) and horizontal dimension (different objects).

• Collaboration Diagram displays an interaction organized around the objects and their links to one another. Numbers are used to show the sequence of messages.

• State Diagram displays the sequences of states that an object of an interaction goes through during its life in response to received stimuli, together with its responses and actions.1
Activity Diagram displays a special state diagram where most of the states are action states and most of the transitions are triggered by completion of the actions in the source states. This diagram focuses on flows driven by internal processing.

Physical Diagrams
• Component Diagram displays the high level packaged structure of the code itself. Dependencies among components are shown, including source code components, binary code components, and executable components. Some components exist at compile time, at link time, at run times well as at more than one time.

• Deployment Diagram displays the configuration of run-time processing elements and the software components, processes, and objects that live on them. Software component instances represent run-time manifestations of code units.

Read More......

History of UML

·

Identifiable object-oriented modeling languages began to appear between mid-1970 and the late 1980s as various methodologists experimented with different approaches to object-oriented analysis and design. The number of identified modeling languages increased from less than 10 to more than 50 during the period between 1989-1994. Many users of OO methods had trouble finding complete satisfaction in any one modeling language, fueling the "method wars." By the mid-1990s, new iterations of these methods began to appear and these methods began to incorporate each other’s techniques, and a few clearly prominent methods emerged.1
The development of UML began in late 1994 when Grady Booch and Jim Rumbaugh of Rational Software Corporation began their work on unifying the Booch and OMT (Object Modeling Technique) methods. In the Fall of 1995, Ivar Jacobson and his Objectory company joined Rational and this unification effort, merging in the OOSE (Object-Oriented Software Engineering) method.


As the primary authors of the Booch, OMT, and OOSE methods, Grady Booch, Jim Rumbaugh, and Ivar Jacobson were motivated to create a unified modeling language for three reasons. 

First, these methods were already evolving toward each other independently. It made sense to continue that evolution together rather than apart, eliminating the potential for any unnecessary and gratuitous differences that would further confuse users. 

Second, by unifying the semantics and notation, they could bring some stability to the object-oriented marketplace, allowing projects to settle on one mature modeling language and letting tool builders focus on delivering more useful features. 

Third, they expected that their collaboration would yield improvements in all three earlier methods, helping them to capture lessons learned and to address problems that none of their methods previously handled well.

The efforts of Booch, Rumbaugh, and Jacobson resulted in the release of the UML 0.9 and 0.91 documents in June and October of 1996. During 1996, the UML authors invited and received feedback from the general community. They incorporated this feedback, but it was clear that additional focused attention was still required.

While Rational was bringing UML together, efforts were being made on achieving the broader goal of an industry standard modeling language. In early 1995, Ivar Jacobson (then Chief Technology Officer of Objectory) and Richard Soley (then Chief Technology Officer of OMG) decided to push harder to achieve standardization in the methods marketplace. In June 1995, an OMG-hosted meeting of all major methodologists (or their representatives) resulted in the first worldwide agreement to seek methodology standards, under the aegis of the OMG process.1
During 1996, it became clear that several organizations saw UML as strategic to their business. A Request for Proposal (RFP) issued by the Object Management Group (OMG) provided the catalyst for these organizations to join forces around producing a joint RFP response. Rational established the UML Partners consortium with several organizations willing to dedicate resources to work toward a strong UML 1.0 definition. Those contributing most to the UML 1.0 definition included: Digital Equipment Corp., HP, i-Logix, IntelliCorp, IBM, ICON Computing, MCI Systemhouse, Microsoft, Oracle, Rational Software, TI, and Unisys. This collaboration produced UML 1.0, a modeling language that was well defined, expressive, powerful, and generally applicable. This was submitted to the OMG in January 1997 as an initial RFP response.

In January 1997 IBM, ObjecTime, Platinum Technology, Ptech, Taskon, Reich Technologies and Softeam also submitted separate RFP responses to the OMG. These companies joined the UML partners to contribute their ideas, and together the partners produced the revised UML 1.1 response. The focus of the UML 1.1 release was to improve the clarity of the UML 1.0 semantics and to incorporate contributions from the new partners. It was submitted to the OMG for their consideration and adopted in the fall of 1997.

Read More......

Why Use UML?

·

As the strategic value of software increases for many companies, the industry looks for techniques to automate the production of software and to improve quality and reduce cost and time-to-market. 

These techniques include component technology, visual programming, patterns and frameworks. Businesses also seek techniques to manage the complexity of systems as they increase in scope and scale. 

In particular, they recognize the need to solve recurring architectural problems, such as physical distribution, concurrency, replication, security, load balancing and fault tolerance. Additionally, the development for the World Wide Web, while making some things simpler, has exacerbated these architectural problems. The Unified Modeling Language (UML) was designed to respond to these needs.

Read More......

Goals of UML

·

The primary goals in the design of the UML were:

1. Provide users with a ready-to-use, expressive visual modeling language so they can develop and exchange meaningful models.

2. Provide extensibility and specialization mechanisms to extend the core concepts.

3. Be independent of particular programming languages and development processes.

4. Provide a formal basis for understanding the modeling language.

5. Encourage the growth of the OO tools market.

6. Support higher-level development concepts such as collaborations, frameworks, patterns and components.

7. Integrate best practices.

Read More......

What is UML?

·

The Unified Modeling Language (UML) is a standard language for :-
  1. specifying, 
  2. visualizing, 
  3. constructing, 
  4.  documenting ,
the artifacts of software systems, as well as for business modeling and other non-software systems. 

The UML represents a collection of best engineering practices that have proven successful in the modeling of large and complex systems.

The UML is a very important part of developing object oriented software and the software development process. 

The UML uses mostly graphical notations to express the design of software projects. Using the UML helps project teams communicate, explore potential designs, and validate the architectural design of the software.

Read More......

INDEX OF C LANGUAGE

·

  1. History C LANGUAGE

  2. Structure of a C Program

  3. C Program to convert a temperature given in Celsius to Fahrenheit

  4. NUMERIC CONSTANTS

  5. C Variables and Their Types

  6. DATA INPUT AND OUTPUT

  7. Arithmetic operators In C

  8. Type casting

  9. UNARY OPERATORS

  10. LOGICAL OPERATORS

  11. ASSIGNMENT OPERATORS

  12. THE CONDITIONAL OPERATOR

  13. THE DECISION CONTROL

  14. The Loop Control structure

  15. The break Statement

  16. The continue Statement

  17. The Case Control structure-switch Statement

  18. ARRAYS

  19. FUNCTIONS

  20. WHY USE FUNCTIONS

  21. CALL BY VALUE

  22. CALL BY REFERENCE

  23. STANDARD LIBRARY STRING FUNCTIONS

  24. POINTERS -DYNAMIC DATA STRUCTURES IN C

  25. The dynamic allocation functions - malloc( ) and calloc( )

  26. POINTERS VS. ARRAY

  27. POINTERS AND FUNCTIONS

  28. POINTERS TO FUNCTIONS

  29. POINTERS TO POINTERS

  30. ARRAY OF POINTERS

  31. STRUCTURES IN C

  32. Array of structures

  33. structures within structures

  34. UNIONS

  35. DISK I/O FUNCTIONS

  36. Opening a file

  37. Closing the file

  38. File Opening Modes

  39. Reading & writting from a File(Unformatted Character)

  40. The fprintf and fscanf functions(Formatted I/o)

  41. fseek function

  42. ftell

  43. Text Mode Versus Binary Mode:-

Read More......

Text Mode Versus Binary Mode:-

·

(i) New Lines:-In text mode, a newline character is converted into the carriage return -linefeed combination before being written to the disk. Like wise, the carriage return-line feed combination on the disk is converted back in to a newline when the file is read by a c program. However if file is opened in binary mode, as opposed to text mode, these conversions will not take place.

(ii) End of File:-The difference is that in text mode when end-of-file is detected a special character whose asciI value is 26, is inserted after the last character in the file to mark the end of file. If this character is detected at any point in the file, the read function will return the EOF signal to the program.

As against this, there is no such special character present in the binary mode files to mark the end of file. The binary mode file keeps track of the end of file from the number of characters present in directory entry of the file.

Text Mode:-
The only function available for storing in a disk file is the fprintf( ) in text mode. Here numbers are stored as string of characters when written to the disk. These 1234, even though it occu- pies two bytes in memory, when transferred to the disk using fprintf( ), it would occupy four bytes, one byte per character. Similarly the floating point number 1234.56 would occupy 7 bytes on disk. These, numbers with more digits would require more disk space.

In binary by using the functions (fread( ) and fwrite( )) numbers are stored in binary format. It means each number would occupy the same number of bytes on disk as it occupies in memory.

Binary Mode:-
A file can be opened in binary mode as follows:
fp = fopen(“Poem. txt”, “rb”)
Here fp is file pointer
Poem. txt is file name
rb denotes that file is opened in binary mode for read operation.

Read More......

ftell

·

ftell takes a file pointer and returns a number of type long that corresponds to the current position. This function is useful in saving the current position of a file, which can be used later in the program. It takes the following form:-

n = ftell(fp);
n would give the relative offset(in bytes) of the current position. This means that n bytes have already been read (or written).

rewind takes a file pointer and resets the position to the start of the file.
for e.g.
rewind(fp);
n = ftell(fp);
n would return 0

Read More......

fseek function

·

fseek function is used to move the file position to a desired location within the file. It takes the following form:
fseek(file ptr, offset, position)

File ptr is a pointer to the file concerned, offset is a number variable of type long and position is an integer number. The offset specifics the number of positions(bytes) to the moved from the location specified by position.

The position can take one of the following three values
Values -----------Meaning
0 --------------Beginning of file
1 --------------Current position
2 ----------------End of file
offset may be positive meaning move forwards or negative meaning move backwards.

The following examples illustrate the operation of the fseek function:
Statement ----------------------------Meaning
fseek(fp,0L,0) ------------------Go to beginning
fseek(fp, 0L, 1) -------------Stays at current position
fseek(fp, 0L, 2) --------Go to end of the file, past the last character of the file
fseek(fp, m, 0) -----------Move to (m+1)th byte in the file
fseek(fp, m, 1) ---------Go forwared by m bytes
fseek(fp, -m, 1) ----Go backward by m bytes from the current position
fseek(fp, - m, 2) ------Go backward by m bytes from the end

Read More......

The fprintf and fscanf functions(Formatted I/o)

·

The general form of fprintf is:-
fprintf(fp, “control string”, list)
eg:-
fprintf(f1, “%s %d %f”, name, age, 7.5);
Name is an array variable of type char and age is an int variable. The function fprintf will cause the value name age and 7.5 to be written to the file pointed by variable f1.

The general format of fscanf is
fscanf(fp, “control string”, list);
This statement would cause the reading of the items in the list from the file specified by fp, according to the specifications contained in the control string.
eg.
fscanf(f2, “%s %d”, item, & quantity);

Like scanf fscanf also returns number of items that are successfully read. When the end of the file is reached, it returns the value EOF.

Read More......

Reading & writting from a File(Unformatted Character)

·

To read the file’s contents from memory there exists a function called fgetc( )
e.g
ch = fgetc(fp);
Writing to a File(Unformatted Character)
There exists a fputc( ) function that writes to the file
fputc(ch, ft);
here value of ch variable will be written to file whose file pointer is ft.

Read More......

File Opening Modes

·

The “r” mode mentioned above is one of the several modes in which we can open a file. These are mentioned below:

(i) “r” Searches the file. If the file exists, loads it in to memory and sets up a pointer which points to the first character in it. If the file doesn’t exist it returns NULL.

(ii) “w” Searches file if the file exists it contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.

Operations possible - writing to the file.

(iii) “a” Searches file. If the file exists, loads it in to memory and sets up a pointer which points to the first character in it. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file. Operations possible - Appending new contents at the end of file.

(iv) “r+” Searches file. If it exists, loads it in to memory and sets up a pointer which points to the first character in it. If file doesn’t exist it returns NULL.

Operations possible - reading existing contents, writing new contents, modifying existing contents of the file.

(v) “w+” Searches file. If the file exists, it contents are destroyed. It the file doesn’t exist a new file is created. Returns NULL if unable to open file. Operations possible - writing new contents, reading them back and modifying existing contents of the file. “a+” Searches if the file exists, loads it in to memory and sets up a pointer which points to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file. Operations possible - reading existing contents, appending new contents to the end of file. Canot modify existing contents.

Read More......

Closing the file

·

When we have finished reading or writing from the file, we need to close it. This is done using the function fclose( ) through the statement.
fclose(fp);
fp is file pointer here.

e.g
A file - copy program here is a program which copies the contents of one file in to another:-
# include "stdio.h"
main( )
{
FILE *fs, *ft;
char ch;
fs = fopen(“pr1.c”, “r”);
if(fs = = NULL)
{
puts(“canot open source file”)’
exit( );
}
ft = fopen (“pr2.c”, “w”);
it (ft = =NULL)
{
puts(“canot open target file”);
fclose(fs);
exit( );
}
while (1)
{
else
}
ch = fgetc(fs);
if(ch = = EOF)
break;
fputc(ch,ft);
fclose(fs);
fclose(ft);
}

Read More......

Opening a file

·

We make the following declaration before opening a file
FILE * fp
Now let us understand the following statements,

FILE * fp;
fp = fopen (“PR1.C”,”r”);
fp is a pointer variable which contains address of the structure FILE which has been defined in the header file “stdio.h”.
fopen( ) will open a file “PRI.C” in read mode.

fopen( ) performs three important tasks when you open the file i “r” mode:

(i) Firstly it searches on the disk the file to be opened.

(ii) If the file is present, it loads the file from the disk in to memory. Of course if the file is very big, then it loads the file part by part. If the file is absent, fopen( ) returns a NULL. NULL is a macro defined in “stdio.h” which indicates that you failed to open the file.

(iii) It sets up a character pointer (which is part of the FILE structure) which points to the first character of the chunk of memory where the file has been loaded.

# include "stdio.h"
main( )
{


FILE *fp;
fp = fopen(“PRI.C”, “r”);
if (fp= = NULL)
{
puts (“ cannot open file”);
exit( );
}
}

Read More......

DISK I/O FUNCTIONS

·

Disk I/O operations are performed on entities called files. The brief categorisation of Disk I/O functions is given below:-












From above we can see that the file I/o functions are further categorised in to text and binary.
This classification arises out of the mode in which a file is opened for input or output. Which of these two modes is used to open the file determines:

(a) How new lines (\n) are stored
(b) How end of file is indicated
(c) How numbers are stored in the file

Read More......

UNIONS

·

Unions, like structure contain members, whose individual data types may vary. This is a is major distinction between them in terms of storage .In structures each member has its own storage location, where as all the members of a union use the same location.

Like structures, a union can be declared using the keyword union is follows:
union item
{
int m;
float x;
char c;
} code;

This declares a variable code of type union item. The union contains item members, each with a different date type. However, we can use only one of them at a time. This is due to the fact that only one location is allocated for a union variable, irrespective of its size















The compiler allocates a piece of storage that is large enough to hold the largest variable
type in the union. In the declaration above, the member x requires 4 bytes which is the largest among the members. The above figure shown how all the three variables share the same address, this assumes that a float variable requires 4 bytes of storage.

To access a union member, we can use the same syntax that we as for structure members, that is:-
code. m
code. x
code. c
are all valid
When accessing member variables, we should make sure that we are accessing the member whose value is currently in storage. For example
code. m = 565;
code. x = 783.65;
printf(“%d”, code. m);
would produce erroneous output.

# include "stdio.h"
main( )
{
union
{
int one;
char two;
} val;
val. one = 300;
printf(“val. one = %d \n”, val. one);
printf(“val. two = %d \n”, val. two);
}

The format of union is similar to structure, with the only difference in the keyword used.
The above example, we have 2 members int one and char two we have then initialised the member ‘one’ to 300. Here we have initialised only one member of the union. Using two printf statements, then we are displaying the individual members of the union val as:
val. one = 300
val. two = 44
As we have not initialised the char variable two, the second printf statement will give a random value of 44.

The general formats of a union thus, can be shown as.
union tag {
member 1;
member 2;
- - -
- - -
member m;
};

The general format for defining individual union variables:
Storage-class Union tag variable 1, variable 2,........., variable n;
Storage-class and tag are optional variable 1, variable 2 etc, are union variable of type tag.
Declaring union and defining variables can be done at the same time as shown below:

Stroage-calss union tag {
member 1;
member 2;
- - -
- - -
- - -
member m;

} variable 1, variable 2, - - - , variable n;

Read More......

structures within structures

·

structure with in a structure means nesting of structures. Let us consider the following
struc- ture defined to store information about the salary of employees.

struct salary
{
char name[20];
char department[10];
int basic_pay;
int dearness_allowance;
int city_allowance;
}
employee;

This structure defines name, department, basic pay and 3 kinds of allowance. we can group all the items related to allowance together and declare them under a substructure as shown below:

struct salary
{
char name [20];
char department[10];
struct
{
int dearness;
int hous_rent;
int city;
}
allowance;
}
employee;
The salary structure contains a member named allowance which itself is a structure with 3 members. The members contained in the inner, structure namely dearness, hous_rent, and city can be referred to as :

employee .allowance. dearness
employee. allowance. hous_rent
employee. allowance. city

An inner-most member in a nested structure can be accessed by chaining all the concerned. structure variables (from outer-most to inner-most) with the member using dot operator. The following being invalid.

employee. allowance (actual member is missing)
employee. hous_rent (inner structure variable is missing)

Read More......

Array of structures

·

Each element of the array itself is a structure. See the example shown below. Here we want to store data of 5 persons for this purpose, we would be required to use 5 different structure variables, from sample1 to sample 5. To have 5 separate variable will be inconvenient.

# include "stdio.h"
main( )
{
struct person
{
char name [25];
char age;
};

struct person sample[5];
int index;
char into[8];
for( index = 0; index <5;>
{
print(“Enter name;”);
gets(sample [index]. name);
printf(“%age;”);
gets(info);
sample [index]. age = atoi (info);
}
for (index = 0; index <5;>
{
printf(“name = %5\n”, sample [index]. name);
printf(“Age = %d \n”, sample [index]. age);
getch( );
}
}
The structure type person is having 2 elements:
Name is an array of 25 characters and character type variable age

Using the statement:
struct person sample[5]; we are declaring a 5 element array of structures. Here, each ele- ment of sample is a separate structure of type person.
We, then defined 2 variable indexes and an array of 8 characters’ info.

Here, the first loop executes 5 times, with the value of index varying from 0 to 4. The first printf statement displays. Enter name gets( ) function waits for the input string. For the first time this name you enter will go to sample[0]. name. The second printf display age the number you type is will be 5 stored as character type, because the member age is declared as character type. The function atoi( ) converts this into an integer. atoi stands for alpha to integer. This will be stored in sample[0] age. The second for loop in responsible for printing the information stored in the array of structures.

Read More......

STRUCTURES IN C

·

A structure is a convenient tool for handling a group of logically related data items. structure help to organize complex data in a more meaningful way. It is powerful concept that we may after need to use in our program Design. A structure is combination of different data types using the & operator, the beginning address of structure can be determined. This is variable is of type structure, then & variable represent the starting address of that variable.

structure Definition
A structure definition creates a format that may be used to declare structure variables
con-sider the following example.

struct book_bank
{
char title [20];
char author [15];
int pages;
float price;
};

Here keyword struct hold the details of four fields these fields are title, author, pages, and price, these fields are called structure elements. Each element may belong to different types of data. Here book_bank is the name of the structure and is called the structure tag.

It simply describes as shown below. struct book-bank






The general format of a structure definition is as follows
struct teg_name
{
data_type member 1;
data_type member 2;
- - - - - -
- - - - - -
- - - - - -
}

Read More......

ARRAY OF POINTERS

·

The way there can be an array of ints or an array of floats, similarly there can be an array of pointers. Since a pointer variable always contain an address, an array of pointers would be nothing but collection of addresses. The addresses present in the array of pointers can be addresses of isolated variables or addresses of array elements or any other addresses. All rules that apply to an ordinary array apply to the array of pointers as well.

eg.

main ( )
{
int * arra [ 4 ];
int i = 31, j = 5, k = 19, L = 71, m;
arra [0] = & i ;
arra [1] = & j ;
arra [2] = & k ;
arra [3] = & l ;
for (m=0; m<=3 ; m+ +) printf (“\n% d”, * (arr[m])) ; } The output will be -
31
5
19
71

Read More......

POINTERS TO POINTERS

·

The concept of pointers can be further extended. Pointer we know is a variable which contains address of another variable. Now this variable itself could be another pointer. These we now have a pointer which contains another pointer’s address. The following example should make this point clear.






























In this program i is an integer type value, j is a pointer to this variable and k is another pointer
type variable pointing to j.
All the addresses are assumed addresses K is pointing to the variable j. These K is a pointer
to pointer. In principle, there could be a pointer to a pointer’s pointer, of a pointer to a pointer to a pointer’s pointer. There is no limit on how far can we go on extending this definition.

Read More......

POINTERS TO FUNCTIONS

·

A function like a variable, has an address location in the memory. It is therefore, possible to declare a pointer to a function, which can then be used as an argument in another function. A pointer to a function is declared as follows:

type ( * fp) ( ) ;

This tells the compiler that fp is a pointer to a function which returns type value.

We can make a function pointer to point to a specific function by simply assigning the name of the function to the pointer.

For example,
double (*P1)( ), mul ( ) ;
P1 = mul ;
declare P1 as a pointer to a function and mul as a function and then make P1 to point to the
function mul. To call the function mul, we may now use the pointer P1 with the list of param- eters. That is,
(*P1) (x,y)
is equivalent to mul ( x,y )

Read More......

POINTERS AND FUNCTIONS

·

When an array is passed to a function as an argument, only the address of the first element of the array is passed, but not the actual values of the array elements. The function uses this address for manipulating the array elements. Similarly, we can pass the address of a variable as an argument to a function in the normal fashion.

When we pass addresses to a function, the parameters receiving the addresses should be pointers. The process of calling function using pointers to pass the address of variable is known as call by reference. The function which is called by reference can change the value of the variable used in the call.
eg.
main ( )
{
int X ;
X = 40 ;
change ( & X ) ;
printf ( “ %d”, X ) ;
{
change ( int * P )
{
* P = * P + 10 ;
}

When the function change is called, the address of the variable X, not its value, is passed into
the function change ( ). Inside change ( ), the variable P is declared as a pointer and therefore
P is the address of the variable X. The statement,

* P = * P + 10 ;
means add 10 to the value stored at address P. Since P represents the address of X, the value of X is changed from 50. Therefore, the output of the program will be 50 not 40.

Thus, call by reference provides a mechanism by which the function can change the stored values in the calling function.

Read More......

POINTERS VS. ARRAY

·

When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the location of the first element (index 0) of the array. The compiler also defines the array name as a constant pointer to the first element suppose we declare an array X as follows :
static int X [ 6 ] = { 1, 2, 3, 4, 5, 6 } ;

Suppose the base address of X is 1000 and assuming that each integer requires two bytes, the five elements will be stored as follows :
ELEMENTS: x [0] x[1] x[2] x[3] x[4] x[5]
VALUE : 1 2 3 4 5 6
Address : 1000 1002 1004 1006 1008 1010

BASE ADDRESS
The name X is defined as a constant pointer pointing to the first clement, x[0] and therefore the value of X is 1000, the location whose X[0] is stored. That is ;

X = & x[0] = 1000
If we declare P as an integer pointer, then we can make the pointer P to point to the array X
by the following assignment : P = X ;
This is equivalent to P = & X[0] ;
Now we can access every value of x using P++ to move from one element to another. The relationship between P and X is shown below :
P=& x[0] ( = 1000)
P+1=& x[1] ( = 1002)
P+2=& x[2] ( = 1004)
P+3=& x[3] ( = 1006)
P+4=& x[4] ( = 1008)
P+5=& x[5] ( = 1010)
The address of an element is calculated using its index and the scale factor of the data type. For instance,
address of X[3] = base address + (3 x Scale factor of int)
= 1000 + (3 x 2) = 1006

When handling array, instead of using array indexing, we can use pointers to access array elements. Note that *(x+3) gives the value of X[3]. The pointer accessing method is more faster than array indexing.

Read More......

The dynamic allocation functions - malloc( ) and calloc( )

·

Most often we face situations in programming where the data is dynamic in nature. That is, the number of data items keep changing during execution of the program. For example, consider a program for processing the list of customers of a company. The list grows when names are added and shrinks when names are deleted. When list grows we need to allocate more memory space to the list to accommodate additional data items. Such situations can be handled more easily and effectively by using what is called dynamic data structures.

DYNAMIC MEMORY ALLOCATION
C language requires that the number of elements in an array should be specified at compile time. Our initial judgement of size, if it is wrong, may cause failure of the program or wastage of memory space.

Many languages permit a programmer to specify an array’s size at run time. Such languages take the ability to calculate and assign, during execution, the memory space required by the variables in a program. The process of allocating memory at run time is known as dynamic memory allocation. The library functions used for allocating memory are :






Memory Allocation Process
Let us first look at the memory allocation process associated with a C program. Fig. below shows the conceptual view of storage of a C program in memory.














The program instructions and global and static variables are stored in a region known as
permanent storage area and the local variables are stored in another area called stack. The memory space that is located between these two regions is available for dynamic allocation during execution of the program. The free memory region is called the heap. The size of the heap keeps changing when program is executed due to creation and death of variables that are local to functions and blocks. Therefore, it is possible to encounter memory “overflow” during dynamic allocation process. In such situations, the memory allocations functions men- tioned above returns a NULL pointer.

ALLOCATING A BLOCK OF MEMORY
A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form;

ptr = ( Cast type * ) malloc ( byte size ) ;
ptr is a pointer of type cast type.
The malloc returns a pointer (of cast type) to an area of memory with size byte - size.
Example :
X = ( int * ) malloc ( 100 *sizeof ( int )) ;
On successful execution of this statement, a memory space equivalent to “100 times the size of an int” bytes is reserved and the address of the first byte of the memory allocated is as- signed to the pointer X of type int.
Similarly, the statement
Cptr = ( char * ) malloc (10) ;
Allocates 10 bytes of space for the pointer Cptr of type char







Remember, the malloc allocates a block of adjacent bytes. The allocation can fail if the space
in the heap is not sufficient to satisfy the request. If it foils, it returns a NULL. We should therefore check whether the allocation is successful before using the memory pointer.
Example :
Write a program that uses a table of integers whose size will be specified interactively at run time.
Program -
# include "stdio.h"
# include "conio.h"
# define NULL O
main ( )
{
int * P, * table ;
int size ;
printf ( “\n What is the sizeof table ? “ ) ;
scanf ( “ % d”, &size ) ;
printf ( “\n” ) ;
if (( table = (int * ) malloc (size * sizeof (int)) = = NULL )
{
printf (“No space available \ n”) ;
exit ( 1) ;
}
printf (“\n address of the first byte is % u\n”, table );
printf(“\n Input table values”);
for ( P = table; P <>
scanf (“%d”, *P );
for ( P = table + size - 1; P > = table; P- - )
printf (“%d is stored at address %u\n”, *P, P );
}

Allocating Multiple Blocks of Memory
calloc is another memory allocation function that is normally used for requesting memory space at runtime for storing derived data types such as arrays and structures. While malloc allocates a single block of storage space, calloc allocates multiple blocks of storage, each of the same size, and then allocates all bytes to O. The general form of calloc is :
ptr = (Cast type * ) calloc ( n, elem_size );
The above statement allocates contiguous space for n blocks, each of size elem-size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space, a NULL pointer is returned.

The following program allocates space for a structure variable.
#include <>
#include <>
struct student
{
char name (25);
float age;
long int num;
} ;
typedef struct student record ;
record * ptr ;
int class_size = 30 ;
ptr = ( record * ) calloc ( class_size, sizeof ( record )) ;
- - - -
- - - -record is of type struct student having three number :
name, age and num.
The calloc allocates memory to hold data for 30 such records. We should check if the requested memory has been allocated successfully before using the ptr.
This may be done as follows:
if ( ptr == NULL )
{
printf ( “Available memory not sufficient”) ;
exit ( 1 ) ; }

Read More......

POINTERS -DYNAMIC DATA STRUCTURES IN C

·

A pointer is a variable that represents the location of a data item, such as a variable or an array element. Pointers are used frequently in C, as they have a number of useful applic- tions.
For example, pointers can be used to pass information back and forth between a function and its reference point. Pointers provide a way to return multiple data items from a function via function arguments to be specified as arguments to a given function.

Pointers are also closely associated with arrays and therefore provide an alternate way to access individual array elements.

Within the computer’s memory, every stored data item occupies one or more adjacent memory cells. The number of memory cells required to store a data item depends on the type of data item. For example, a single character will be stored in 1 byte of memory integer usually requires two adjacent bytes, a floating point number may require four adjacent bytes.

Suppose V is a variable that represents some particular data item. The compiler will automati- cally assign memory cells for this data item. The data item can be accessed if we know the location of the first memory cell. The address of V’s memory location can be determined by the expression &V, where & is a unary operator, called the address operator, that evaluates the address of its operand.

Now let us assign the address of V to another variable, PV.
Thus, PV = & V
This new variable is called a pointer to V, since it “Points” to the location where V is stored in memory. Remember, however, that PV represents V’s address, not its value. Thus, PV is called pointer variable.
address of V value of V
PV V

Relationship between PV and V (where PV = &V and V = *PV)

The data item represented by V can be accessed by the expression *PV where * is a unary operator, that operates only on a pointer variable. Therefore, PV and V both represent the same data item. Furthermore, if we write PV = &V and U = PV, then U and V will both represent the same values i.e., the value of V will indirectly be assigned to U.

Example :
int quantity = 179 ;

The statement instructs the system to find a location for the integer quantity and puts the value 179 in that location. Let us reassume that the system has chosen the address location
5000 for quantity.








Remember, since a pointer is a variable, its value is also stored in the memory in another location.

The address of P can be assumed to be 5048.









Declaring and initializing Pointers
Since pointer variables contain addresses that belong to a separate data type, they must be declared as pointers before we use them. The declaration of a pointer variable takes the following form:
data type * Pt _ name

This tells the compiler three things about the variable Pt_name.
1. The * tells that the variable Pt_name is a pointer variable.
2. Pt_name needs a memory location.
3. Pt_name ponts to a variable of type data type.

Example : int * P ;
Declares the variable P as a pointer variable that points to an integer data type. float * y ;
declares y as a pointer to a floating point variable.
Once pointer variable has been declared, it can be made to point to a variable using an assignment statement such as

P = & quantity ;
which causes P to point to quantity. P contains the address of quantity. This is known as pointer initialization.

Pointer expressions
Like other variables, pointer variables can be used in expressions. For example, if P1 and P2
are properly declared and initialized pointers, then the following statements are valid.






Note that there is a blank space between / and * in the item 3 above.
if P1 and P2 are pointers then the expressions such as,
P1 + 4 , P2 - 2 , P1 - P2 , P1 ++ , — P2 are allowed also,
Sum = Sum + *P2 ; P1 ++ ;
- -P2 ; P1 > P2
P1 = = P2
P1 ! = P2
are all allowed expressions.

The expressions such as,
P1 / P2 or P1 * P2 or P1/3
are not allowed.

Pointer assignments
After declaring a pointer, pointer is assigned a value, so that it can point to a particular vari- able.
eg. int * P ; int i ; P = & i ;
This is called assignment expression in which pointer variable P is holding the address of i.

Pointer arithmetic
Two pointer values can be added, multiplied, divided or subtracted together.
eg.
if int i ;
int j ;
int * P , * q ;
i = 5 , j = 10 ;
Now, various pointer arithmetic can be performed
eg. * j = * i + * j ;
The value of variable j is changed from 10 to 15.
* j = * j - * i ;
The value of variable j is changed from 10 to 5.
* i = * i ** j ;
The value of i is changed from 5 to 50 ;
Consider another example,
if there is array and a pointer is pointing to it int i [10] ;
int * P ; P = i ;
Now, arithmetic operations like
P = P + 4 ;
Will move the pointer P from the starting address of the array to the fourth subscript of array. Similarly, if P1 and P2 are both pointers to the same array, then P2 - P1 gives the number of
elements between P1 and P2.

arithmetic operations like
P1/P2 or P1 x P2 or P/3 are not allowed.

Pointer Comparison
In addition to arithmetic operations, pointers can also be compared using the relational op- erators. The expressions such as
P1 > P2 , P1 = = P2 , P1 ! = P2 are allowed.
However, any comparison of pointers that refer to separate and unrelated variables make no sense. Comparisons can be used meaningfully in handling arrays and strings.

Read More......

STANDARD LIBRARY STRING FUNCTIONS

·

For string handling C provides a standard set of library functions. Though there exists many
such functions four of them will be discussed here.

The strcmp( ) Function
This function is used to check whether two strings are same or not. If both the strings are same it return a 0 or else it returns the numeric difference between the ASCII values of nonmatching characters e.q. the following program

# include"stdio.h"
main( )
{
char string1 [ ] = “orange”;
char string2 [ ] = “banana”;
printf(“%d\n”, strcmp(string1, string2));
printf(“%d\n”, strcmp(string2, “banana”);
printf(“%d”, strcmp(string1, “Orange”));
getch( );
}
output
13
0
32
In the first printf statement we use the strcmp( ) function with string1 and string2 as it argu- ments. As both are not equal (same) the function strcmp( ) returned 13, which is the numeric difference between “orange” and “banana” ie, between string2 and b.

In the second printf statement the arguments to strcmp() are string2 and “banana”. As string2
represents “banana”, it will obviously return a 0.

In the third printf statement strcmp( ) has its arguments “orange” and “Orange” because string1 represents “Orange”. Again a non-zero value is returned as “orange” and “Orange” are not equal.


strcpy( ) Function


The function copies one string to another for e.g. the following program


# include "stdio.h"
main( )
{
char source [ ] = “orange”; char target [20];
strcpy(target, source);
clrscr( );
printf(“source: %s\n”, source);
printf(“target:%s”, target);
getch( );
}
output will be
source : orange target : orange

strcat( )
This function concatenates the source string at the end of the target string for e.g, “Bombay” and “Nagpur” on concatenation would result in to a string “Bombay Nagpur”. Here is an ex- ample of strcat( ) at work.

main( )
{
char source [ ] = “Folks”;
char target [30] = “Hello”;
strcat(target, source);
printf(“\n source string = %s”, source);
printf(“\n target string = %s”, target);
}
And here is the output source string = folks target string = Hello folks

strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in the following program.
main( )
{
char arr[ ] = “Bamboozled”
int len1, len 2;
len1 = strlen(arr);
len2 = strlen(“Hunpty Dumpty”);
printf(“\n string = %s length = %d”, arr, len1);
printf(“\n string = %s length = %d”, “Humpty Dumpty”, len2);
}
The output would be
string = Bamboozled length=10
string = Humpty Dumpty length = 13
while calculating the length of the string it does not count ‘\0’.

Read More......

CALL BY REFERENCE

·

In CALL BY REFERENCE the addresses of actual arguments in the calling function are copied in to formal arguments of the called function. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them the following program illustrates this.

main ( )
{
int a = 10, b =20, swapr (&a, &b);
printf (“\n a = %d b= %d”, a, b);
}
swapr (int *x, int * y)
{
int t;
t = *x
*x = *y;
*y = t;
}

The output of the above program would be
a = 20 b =10

Read More......

CALL BY VALUE

·

In the preceding examples we have seen that whenever we called a function we have always passed the values of variables to the called function. Such function calls are called ‘calls by value’ by this what it meant is that on calling a function we are passing values of variables to it.

The example of call by value are shown below ;
sum = calsum (a, b, c);
f = factr (a);

In this method the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual argument in the calling function. the following program illustrates this

main ( )
{
int a = 10, b=20;
swapy (a,b);
printf (“\na = % d b = % d”, a,b);
}
swapy (int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf ( “\n x = % d y = % d” , x, y);
}

The output of the above program would be;
x = 20 y = 10
a =10 b =20

Read More......

WHY USE FUNCTIONS

·

Two reasons :
(i) Writing functions avoids rewriting the same code over and over. Suppose that there is a section of code in a program that calculates area of a triangle. If, later in the program we want to calculate the area of a different triangle we wont like to write the same instructions all over again. Instead we would prefer to jump to a ‘section of code’ that calculates area and then jump back to the place from where you left off. This section of code is nothing but a function.

(ii) Using functions it becomes easier to write programs and keep track of what they are doing. If the operation of a program can be divided in to separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code in to modular functions also makes the pro- gram easier to design and understand.

(a) Functions declaration and prototypes
Any function by default returns an int value. If we desire that a function should return a value other than an int, then it is necessary to explicitly mention so in the calling functions as well as in the called function. e.g
main ( )
{
float a,b,
printf (“\n Enter any number”);
scanf (“\% f”, &a );
b = square (a);
printf (“\n square of % f is % f”, a,b);
}
square (Float x)
{
float y;
y = x * x;
return (y);
}

the sample run of this program is
Enter any number 2.5
square of 2.5 is 6.000000
Here 6 is not a square of 2.5 this happened because any C function, by default, always returns an integer value. The following program segment illustrates how to make square ( ) capable of returning a float value.

main ( )
{
float square ( );
float a, b;
printf (“\n Enter any number “);
scanf (“%f” &a);
b = square (a);
printf (“\n square of % f is % f, “ a, b);
}
float square (float x)
{
float y; y= x *x; return ( y);
}
sample run
Enter any number 2.5
square of 2.5 is 6.2500000

Read More......

FUNCTIONS

·

A computer program cannot handle all the tasks by it self. Instead its requests other program
like entities - called ‘functions in C - to get its tasks done. A function is a self contained block of statements that perform a coherent task of some kind.
e.g

#include"stdio.h"
message();
{
message ( );
printf (“\n Hello “);
}
main ( )
{
message ( )
printf (“\n I am in main “);
}
output of the program will be
Hello
I am in main

Here main ( ) is the calling function and message is the called function. When the function message ( ) is called the activity of main ( ) is temporarily suspended while the message ( ) function wakes up and goes to work. When the message ( ) function runs out of statements to execute, the control returns to main ( ), which comes to life again and begins executing its code at the exact point where it left off.

The General form of a function is :-
function (arg1, arg2, arg3)
type arg1, arg2, arg3
{
statement 1;
statement2;
statement3;
statement4;
}

There are basically two types of functions
(i) Library functions e.g printf ( ), scanf ( ) etc
(ii) user defined function e.g the function message( ) mentioned above.

The following point must be noted about functions
(i) C program is a collection of one or more functions
(ii) A function gets called when the function name is followed by a semicolon for e.g. main ( )
{
message ( );
}
(iii) A function is defined when function name is followed by a pair of braces in which one or more statements may be present for e.g.
message ( )
{
statement 1;
statement2;
statement 3;
}
(iv) Any function can be called from any other function even main ( ) can be called from other functions. for e.g.
main ( )
{
message ( );
}
message ( )
{
printf (“ \n Hello”);
main ( );
}
(v) A function can be called any number of times for eg. main ()
{
message ( );
message ( );
}
message ( )
{
printf (“\n Hello”);
}
(vi) The order in which the functions are defined in a program and the order in which they get called need not necessarily be same for e.g.
main ( );
{
message1 ( );
message2 ( );
}
message2 ( )
{
printf (“\n I am learning C”);
}
message1 ( )
{
printf ( “\n Hello “);
}
(vii) A function can call itself such a process as called ‘recursion’.
(viii) A function can be called from other function, but a function cannot be defined in an- other function. Thus the following program code would be wrong, since argentina is being defined inside another function main ( ).
main ( )
{
printf (“\n I am in main”);
argentina ( )
{
printf {“\n I am in argentina”);
}
}
(ix) Any C program contains at least one function
(x) If a program contains only one function, it must be main ( )
(xi) In a C program if there are more than one functional present then one of these func- tional must be
main ( ) because program execution always begins with main ( )

(xii) There is no limit on the number of functions that might be present in a C program.
(xiii) Each function in a program is called in the sequence specified by the function calls in
main ( )
(xiv) After each function has done its thing, control returns to the main ( ), when main ( ) runs out of function calls, the program ends.

Read More......

About Me

Blog Archive