Members BookmarksPolls Fresher Jobs Strange Photos Academic Projects New Member FAQ  



My Profile
Active Members
TodayLast 7 Days more...



Awards & Gifts
Online Exams

Fresher Jobs


Our fresher job section is exclusively for fresh graduates! Find jobs for freshers in major Indian cities including Bangalore, Chennai, Hyderabad, Pune or Kochi

Resources


Find educational articles, blogs, discussion threads and other resources.

Colleges


Find details about any college in India or search for courses.

Advertisements


website counter




Computer - Arrays and Functions :-


Posted Date: 03 Feb 2008    Resource Type: Articles/Knowledge Sharing    Category: Computer & Technology

Posted By: prakash       Member Level: Silver
Rating:     Points: 5



Arrays:
Definition:
• An array is a group of related data items that share a common name.
• Array is a collection of identical data objects, which are stored in consecutive memory locations in a common heading or a variable name.
• We can define an array name ‘a’ to represent a set of values.
• A particular value is indicates by writing a number called index number or subscript in brackets after the array name.
Eg: int a[10];



• In C, arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9.
• The complete set of values is referred to as an array, the individual values are called elements.
• The subscript, which specifies a single element of an array, is simply an integer expression in square brackets.
• The first element of the array is a[0], the second element is a[1], etc. Array can be of any variable type.

One-Dimensional array
• A list of items are given in one variable name using only one subscript and such a variable is called a single-subscripted variable or a one-dimensional array.
• Eg: If we wants to represent a set of five numbers, say(35,40,20,57,19) by an array variable number, then we may declare the variable number as follows,
int num [5];





The computer reserves five storage locations as,

num[0] 35
num[1] 40
num[2] 20
num[3] 57
num[4] 19

These elements used in programs just like any other C variable.
Some valid statements,
a = num[0]+10;
num[4]=num[0]+num[2];
num[2]=x[5]+y[10];
values[6]=num[i]*3;

Declaration of Arrays
Arrays have to declare before they are used. The general form of array declaration is,
type variable-name[size];
The type specifies the type of element that will be contained in the array, such as int, float or char and the size indicates the maximum number of elements that can be stored inside the array.
Eg: float height[50]; ?height contains 50 real elements.
int group[10]; ?group contain maximum of 10 integer constants.
char name[10]; ?name as a character array(string) variable that can hold a maximum of 10 characters .

Eg: “WELL DONE”
Each character of the string is treated as an element of the array name and is stored in the memory as follows:

‘W’
‘E’
‘L’
‘L’
‘ ‘
‘D’
‘O’
‘N’
‘E’

When the compiler sees a character string, it terminates it an additional null character. Thus, the element name [9] holds the null character ‘\0’ at the end. When declaring arrays, we must always allow one extra element space for the null terminator.

Initialization of Arrays
We can initialize the elements in the array in the same way as the ordinary variables when they are declared. The general form of initialization off arrays is:
static type array_name[size] = {list of values};
The values in the list care separated by commas, for example the statement
static int number[3]={0,0,0};
Will declare the array size as a array of size 3 and will assign zero to each element if the number of values in the list is less than the number of elements, then only that many elements are initialized. The remaining elements will be set to zero automatically.
In the declaration of an array the size may be omitted, in such cases the compiler allocates enough space for all initialized elements. For example the statement
int counter[]={1,1,1,1};
Will declare the array to contain four elements with initial values 1. This approach works fine as long as we initialize every element in the array.
The initialization of arrays in c suffers two drawbacks
1. There is no convenient way to initialize only selected elements.
2. There is no shortcut method to initialize large number of elements.
Example:
/* Program to count the number of positive and negative numbers*/
#include< stdio.h >
void main( )
{
int a[50],n,count_neg=0,count_pos=0,i;
printf(“Enter the size of the array\n”);
scanf(“%d”,&n);
printf(“Enter the elements of the array\n”);
for i=0;i < n;i++)
scanf(“%d”,&a[i]);
for(i=0;i < n;i++)
{
if(a[i] < 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the array\n”,count_neg);
printf(“There are %d positive numbers in the array\n”,count_pos);
}

Two – Dimensional arrays
• Suppose we need to store the elements in a row and column order then we declare two-dimensional arrays.
• Two dimensional arrays are declared as follows
data_type array_name[row_size][column_size];
Example: int a[3][3];
Initialization of two-dimensional Arrays:
• We can initialize the elements of arrays as variable
• General form is
static type array-name[row-size][column-size] = { list of values };
• Example: static int num[2][3] = {{0,0,0}, {1,1,1}};

Example:
/* MATRIX ADDITION */
main(){
int a[10][10],b[10][10],c[10][10],n,i,j;

clrscr();
printf("Enter the order of matrix\n");
scanf("%d",&n);
printf("\nEnter the values of matrix A one by one\n");
for(i=0;i for(j=0;j scanf("%d",&a[i][j]);
printf("\nEnter the values of matrix B one by one\n");
for(i=0;i for(j=0;j scanf("%d",&b[i][j]);
for(i=0;i for(j=0;j c[i][j]=a[i][j]+b[i][j];
printf("\nMatrix C is:\n");
for(i=0;i for(j=0;j printf("%d\t",c[i][j]);
printf("\n");
}
getch();
}

OUTPUT:
Enter the order of matrix
3
Enter the values of matrix A one by one
1
1
1
1
1
1
1
1
1
Enter the values of matrix B one by one
1
2
3
4
5
6
7
8
9
Matrix C is:
2 3 4
5 6 7
8 9 10





Multidimensional Array
C language provides the facility for multidimensional arrays. Multidimensional array means arrays of three or more dimensions. The compiler determines the exact limit. The general form is
type array-name [s1][s2][s3]……..s[i]
Where
si=size of the ith dimension.
Example:
int mark[5][5][5];
This declares mark as a three dimensional integer array containing 125 elements of integer type.
Dynamic arrays:
Dynamic memory management techniques permit us to allocate additional memory space or to release unwanted space at the run time.
The process of allocating memory at run time is known as dynamic memory allocation.
Memory management functions:
1. malloc ? allocates requested size of bytes and returns a pointer to the first byte of the allocated space.
2. calloc ?allocates space for an array of elements. Initialize them to 0 and then returns to a pointer to the memory.
3. free ?frees previously allocated spaces.
4. realloc ? Modifies the size of previously allocated spaces.
Memory allocation process:
The memory space that is located between two regions (permanent storage area and local variables are stored in another area called stack) is available for dynamic allocation during execution of the program. This free memory region is called heap. The size of the heap keeps changing when program is executed due to creation and deletion of variables that are local to function and blocks.
Local variables
Free memory
Global variables
C program instructions

} stack
}Heap
}Permanent Storage area

It is possible to encounter memory overflow during dynamic allocation process. In that time, the memory allocation functions returns a NULL pointer.
Allocating a block of memory:
A block mf 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 equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int
Allocating multiple blocks of memory:
calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is:
ptr=(cast-type*) calloc(n,elem-size);
The above statement allocates contiguous space for n blocks each size of elements 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.
Releasing the used space:
Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function.
free(ptr);
ptr is a pointer that has been created by using malloc or calloc.
To alter the size of allocated memory:
The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is :
ptr=realloc(ptr,newsize);

This function allocates new memory space of size newsize to the pointer variable ptr ans returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.
/*Example program for reallocation*/
#include< stdio.h >
#include< stdlib.h >
define NULL 0
main()
{
char *buffer;
/*Allocating memory*/
if((buffer=(char *) malloc(10))==NULL)
{
printf(“Malloc failed\n”);
exit(1);
}
printf(“Buffer of size %d created \n,_msize(buffer));
strcpy(buffer,”Bangalore”);
printf(“\nBuffer contains:%s\n”,buffer);
/*Reallocation*/
if((buffer=(char *)realloc(buffer,15))==NULL)
{
printf(“Reallocation failed\n”);
exit(1);
}
printf(“\nBuffer size modified.\n”);
printf(“\nBuffer still contains: %s\n”,buffer);
strcpy(buffer,”Mysore”);
printf(“\nBuffer now contains:%s\n”,buffer);
/*freeing memory*/
free(buffer);
}


Character Arrays and Strings:
Introduction:
A string is a sequence of characters. Any sequence or set of characters defined within double quotation symbols is a constant string. In c it is required to do some meaningful operations on strings they are:
• Reading string displaying strings
• Combining or concatenating strings
• Copying one string to another.
• Comparing string & checking whether they are equal
• Extraction of a portion of a string
Declaring and initializing string variables:
A string variable is any valid C variable name and is always declared as an array. The general form of declaration of a string variable is
char string_name[size];
The size determines the number of characters in the string-name. Some examples are,
char city[10];
char name[30];
/*String.c string variable*/
#include < stdio.h >
main()
{
char month[15];
printf (“Enter the string”);
gets (month);
printf (“The string entered is %s”, month);
}
In this example string is stored in the character variable month the string is displayed in the statement.
printf(“The string entered is %s”, month”);

J
A
N
U
A
R
Y
\0














It is one dimension array. Each character occupies a byte. A null character (\0) that has the ASCII value 0 terminates the string. The figure shows the storage of string January in the memory recall that \0 specifies a single character whose ASCII value is zero. Character string terminated by a null character ‘\0’.

Reading Strings from Terminal:
The function scanf() with %s format specification is needed to read the character string from the terminal.
Example:
char address[15];
scanf(“%s”,address);

scanf() statement has a draw back it just terminates the statement as soon as it finds a blank space, suppose if we type the string newyork then only the string new will be read and since there is a blank space after word “new” it will terminate the string.
Note that we can use the scanf() without the ampersand symbol before the variable name.
In many applications it is required to process text by reading an entire line of text from the terminal.
The function getchar() can be used repeatedly to read a sequence of successive single characters and store it in the array.
We cannot manipulate strings since C does not provide any operators for string. For instance we cannot assign one string to another directly.

For example:
String=”xyz”;
String1=string2;
are not valid. To copy the chars in one string to another string we may do so on a character to character basis.
Writing Strings to Screen:
The printf() statement along with format specifier %s to print strings on to the screen. The format %s can be used to display an array of characters that is terminated by the null character.
For example

printf(“%s”,name);

can be used to display the entire contents of the array name.


String handling functions:
C library supports a large number of string-handling functions that can be used to carry out many of the string manipulations. Most commonly used string- handling functions.

Functions Action
strcat() concatenate two strings
strcmp() compare two strings
strcpy() copies one string over another
strlen() finds the length of a string
strlen() function:
This function counts and returns the number of characters in a string. The length does not include a null character.
Syntax n=strlen(string);
Where n is integer variable. This receives the value of length of the string.
Example
length =strlen(“Hollywood”);
The function will assign number of characters 9 in the string to a integer variable length.
/*write a c program to find the length of the string using strlen() function*/
#include < stdio.h >
include < string.h >
void main()
{
char name[100];
int length;
printf(“Enter the string”);
gets(name);
length=strlen(name);
printf(“\nNumber of characters in the string is=%d”,length);
}
strcat() function:
When you combine two strings, you add the characters of one string to the end of other string. This process is called concatenation. The strcat() function joins 2 strings together. It takes the following form
Syntax: strcat(string1,string2)
string1 & string2 are character arrays. When the function strcat is executed string2 is appended to string1. the string at string2 remains unchanged.
Example
strcpy(string1,”sri”);
strcpy(string2,”Bhagavan”);
printf(“%s”,strcat(string1,string2);
From the above program segment the value of string1 becomes sribhagavan. The string at str2 remains unchanged as bhagawan.
Strcmp() function:
In C you cannot directly compare the value of 2 strings in a condition like if(string1==string2)
Most libraries however contain the strcmp() function, which returns a zero if 2 strings are equal, or a non zero number if the strings are not the same. The syntax of strcmp() is given below:
strcmp(string1,string2)
String1 & string2 may be string variables or string constants. String1, & string2 may be string variables or string constants some computers return a negative if the string1 is alphabetically less than the second and a positive number if the string is greater than the second.
Example:
strcmp(“Newyork”,”Newyork”) ? will return zero because 2 strings are equal.
strcmp(“their”,”there”) ? will return a 9 which is the numeric difference between ASCII ‘i’ and ASCII ’r’.
strcmp(“The”, “the”) ? will return 32 which is the numeric difference between
ASCII “T” & ASCII “t”.

strcmpi() function :
This function is same as strcmp() which compares 2 strings but not case sensitive.
Example strcmpi(“THE”,”the”); will return 0.
strcpy() function:
C does not allow you to assign the characters to a string directly as in the statement name=”Robert”;
Instead use the strcpy(0 function found in most compilers the syntax of the function is illustrated below.
strcpy(string1,string2);
strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a string constant.
strcpy(Name,”Robert”);
In the above example Robert is assigned to the string called name.
/* Example program to use string functions*/
#include < stdio.h >
#include < string.h >
void main()
{
char s1[20],s2[20],s3[20];
int x,l1,l2,l3;
printf(“Enter the strings”);
scanf(“%s%s”,s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{
printf(“\nStrings are not equal\n”);
strcat(s1,s2);
}
else
printf(“\nStrings are equal”);
strcpy(s3,s1);
l1=strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf(“\ns1=%s\t length=%d characters\n”,s1,l1);
printf(“\ns2=%s\t length=%d characters\n”,s2,l2);
printf(“\ns3=%s\t length=%d characters\n”,s3,l3);
}
strlwr () function:
This function converts all characters in a string from uppercase to lowercase.
Syntax : strlwr(string);
For example: strlwr(“EXFORSYS”) converts to Exforsys.

strrev() function:
This function reverses the characters in a string.
Syntax : strrev(string);
For ex:ample: strrev(“program”) reverses the characters in a string into “margrop”.

strupr() function:
This function converts all characters in a string from lower case to uppercase.
Syntax : strupr(string);
For example: strupr(“exforsys”) will convert the string to EXFORSYS.
Table of Strings:
A list of names can be treated as a table of strings and a two-dimensional character array can be used to store the entire list. For example, a character array stu[30][15] may be used to store a list of 30 names, each of length not more 15 characters.
C h a N d i g a r h
M a d R a s
A h m E d a b a d
H y d E r a b a d
B o m b a y




This table can be conveniently stored in a character array city by using the following declaration:
static char city[][]
{
“Chandigarh”,
“Madras”,
“Ahmedabad”,
“Hyderabad”,
“Bombay”
};

User defined functions
Introduction:
A function is a complete and independent program which is used (or invoked) by the main program or other subprograms.
C function can be classified into two categories, namely, library functions and user-defined functions. main is an example of user-defined functions. printf and scanf() belong to the category of library functions. The main distinction between these two categories is that library functions are not required to be written by us whereas a user-defined function has to be developed by the user at the time of writing a program.

Need for user-defined functions:
Every program must have a main function to indicate where the program has to begin its execution. The program becomes too large and as a result the task of debugging, testing, and maintaining becomes difficult. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These subprograms called functions are much easier to understand, debug, and test. In program, the operation or calculation is repeated at many points throughout a program. We may repeat the program statements wherever they needed.

A multi-function program:
A function is a self-contained block of code that performs a particular task. Once a function has designed and packed, it can be treated as a ‘block box’ that takes some data from the main program and returns a value. The inner details of operation are invisible to the rest of the program.

The form of C functions:
All functions have the form,
Function-name(argument list)
Argument declaration;
{
Local variable declarations;
Executable statement1;
Executable statement2;
…………
…………
Return (expression);
}
All parts are not essential. Some may be absent. The declaration of local variables is required only when any local variables are used in the function.
A function can have any number of executable statements. A function that does nothing may not include any executable statements for all. The return statement is the mechanism for returning a value to the calling function. The absence indicates that no being returned to the calling function.

Function name:
A function must follow the same rules of formation as other variable names in C.
Argument list:
The argument list contains valid variable names separated by commas. The list must be surrounded by parenthesis. Note that no semicolon follows the closing parenthesis.
Eg:
Prime(a)
Quadratic(x,n)
Mul(a,b)

All arguments variables must be declared for their types after the function header and before the opening brace of the function body.


Return values and their types:
Return statement is used to return a value to the calling function. The general form is
return; [or] return(expression);
if there is no expression, the return statement acts as a closing brace and return back the control to the calling function.
If there is expression it returns the value of the expression. The parentheses around the expression is optional.
Example:
return; ?no return value. But the control is transferred to calling function
return(a+b); ?the value of the expression a+b is calculated and returned to the calling function.
Function Calls:
A defined function can be called from other functions by specifying its name followed by a list of arguments enclosed within parentheses. The general form is
function-name(list of arguments);
where
function-name -name of a already defined function
list of arguments -actual arguments
Rules:
• Function-name should be the name used in the function definition (called function)
• List of arguments are optional
• If the function call has no arguments, an empty pair of parentheses is a must.
• Data type of the arguments should match with the already defined function (called function) arguments
• The called function returns only one value per call

Category of functions:
1. Functions with no arguments and no return values:
Let us consider the following program
/* Program to illustrate a function with no argument and no return values*/
#include
main()
{
staetemtn1();
statement2();
}
/*function to print a message*/
statement1()
{
printf(“\n Sample subprogram output”);
}
statement2()
{
printf(“\n Sample subprogram output two”);
}
In the above example there is no data transfer between the calling function and the called function. When a function has no arguments it does not receive any data from the calling function. Similarly when it does not return value the calling function does not receive any data from the called function. A function that does not return any value cannot be used in an expression it can be used only as independent statement.
2. Functions with arguments but no return values:
The nature of data communication between the calling function and the arguments to the called function and the called function does not return any values to the calling function this shown in example below:
Consider the following:
Function calls containing appropriate arguments. For example the function call
value (500,0.12,5)
Would send the values 500,0.12 and 5 to the function value (p, r, n) and assign values 500 to p, 0.12 to r and 5 to n. the values 500,0.12 and 5 are the actual arguments which become the values of the formal arguments inside the called function.
Both the arguments actual and formal should match in number type and order. The values of actual arguments are assigned to formal arguments on a one to one basis starting with the first argument as shown below:

main()
{
function1(a1,a2,a3……an)
}

function1(f1,f2,f3….fn);
{
function body;
}
here a1,a2,a3 are actual arguments and f1,f2,f3 are formal arguments.
The no of formal arguments and actual arguments must be matching to each other suppose if actual arguments are more than the formal arguments, the extra actual arguments are discarded. If the number of actual arguments is less than the formal arguments then the unmatched formal arguments are initialized to some garbage values. In both cases no error message will be generated.
The formal arguments may be valid variable names; the actual arguments may be variable names expressions or constants. The values used in actual arguments must be assigned values before the function call is made.
When a function call is made only a copy of the values actual arguments is passed to the called function. What occurs inside the functions will have no effect on the variables used in the actual argument list.
Let us consider the following program
/*Program to find the largest of two numbers using function*/
#include
main()
{
int a,b;
printf(“Enter the two numbers”);
scanf(“%d%d”,&a,&b);
largest(a,b)
}
/*Function to find the largest of two numbers*/
largest(int a, int b)
{
if(a>b)
printf(“Largest element=%d”,a);
else
printf(“Largest element=%d”,b);
}
In the above program we could make the calling function to read the data from the terminal and pass it on to the called function. But function foes not return any value.

3. Functions with arguments and return values:
The function of the type Arguments with return values will send arguments from the calling function to the called function and expects the result to be returned back from the called function back to the calling function.
The function receives arguments (data) from the calling function and returns the computed value back to the calling function.

Example:
main()
{
int a,b;
………..
………..
message(a,b); /* actual arguments to sent*/
………….
………….
}
message(x,y) /* formal arguments to receive*/
{
int x,y; /* formal arguments declaration*/
int value; /* local variable declaration*/
………….
value = x + y;
return(value); /* this statement returns the value to the calling function */
}

Functions with No arguments but return values:

main()
{
int c;
………..
………..
c = message(); /* actual arguments to sent*/
………….
………….
}
int message() /* formal arguments to receive*/
{
int x,y; /* formal arguments declaration*/
int value; /* local variable declaration*/
………….
value = x + y;
return(value); /* this statement returns the value to the calling function */
}
Nesting functions:
C permits nesting of two functions freely. There is no limit how deeply functions can be nested. Suppose a function a can call function b and function b can call function c and so on. Consider the following program:
main()
{
int a,b,c;
float ratio();
scanf(“%d%d%d”,&a,&b,&c);
printf(“%f\n”,ratio(a,b,c));
}
float ratio(x,y,z)
int x,y,z;
{
if(difference(y,z))
return(x/y-z));
else
return(0,0);
}
difference(p,q)
{
int p,q;
{
if(p!=q)
return(1);
else
return(0);
}
the above program calculates the ratio a/b-c; and prints the result. We have the following three functions:
main()
ratio()
difference()
main reads the value of a,b,c and calls the function ratio to calculate the value a/b-c) this ratio cannot be evaluated if(b-c) is zero. Therefore ratio calls another function difference to test whether the difference (b-c) is zero or not.
Recursion:
Recursive function is a function that calls itself. When a function calls another function and that second function calls the third function then this kind of a function is called nesting of functions. But a recursive function is the function that calls itself repeatedly.
A simple example:
main()
{
printf(“this is an example of recursive function”);
main();
}
when this program is executed. The line is printed repeatedly and indefinitely. We might have to abruptly terminate the execution.
Functions and arrays:
We can pass an entire array of values into a function just as we pass individual variables. In this task it is essential to list the name of the array along with functions arguments without any subscripts and the size of the array as arguments
For example: The call
Largest(a,n);
Will pass all the elements contained in the array a of size n. the called function expecting this call must be appropriately defined. The largest function header might look like:
float smallest(array,size);
float array[];
int size;
The function smallest is defined to take two arguments, the name of the array and the size of the array to specify the number of elements in the array. The declaration of the formal argument array is made as follows:
float array[];
The above declaration indicates to compiler that the arguments array is an array of numbers. It is not necessary to declare size of the array here. While dealing with array arguments we should remember one major distinction. If a function changes the value the value of an array element then these changes will be made to the original array that passed to the function. When the entire array is passed as an argument, the contents of the array are not copied into the formal parameter array instead information about the address of the array elements are passed on to the function. Therefore any changes introduced to array elements are truly reflected in the original array in the calling function.
The scope and lifetime of variables in functions:
The scope and lifetime of the variables define in C is not same when compared to other languages. The scope and lifetime depends on the storage class of the variable in c language the variables can be any one of the four storage classes:
1. Automatic Variables
2. External variable
3. Static variable
4. Register variable.
The scope actually determines over which part or parts of the program the variable is available. The lifetime of the variable retains a given value. During the execution of the program, Variables can also be categorized as local or global. Local variables are the variables that are declared within that function and are accessible to all the functions in a program and they can be declared within a function or outside the function also.
Automatic variables:
Automatic variables are declared inside a particular function and they are created when the function is called and destroyed when the function exits. Automatic variables are local or private to a function in which they are defined by default all variable declared without any storage specification is automatic. The value of variable remains unchanged to the changes that may happen in other functions in the same program and by doing this no error occurs.
/* A program to illustrate the working of auto variables*/
#include
void main()
{
int m=1000;
function2();
printf(“%d\n”,m);
}

function1()
{
int m=10;
printf(“%d\n”,m);
}
function2()
{
int m=100;
function1();
printf(“%d\n”,m);
}
A local variable lives through out the whole program although it accessible only in the main. A program with two subprograms function1 and function2 with m as automatic variable and is initialized to 10,100,1000 in function 1 function2 and function3 respectively. When executes main calls function2 which in turns calls function1. When main is active m=1000. But when function2 is called, the main m is temporarily put on the shelf and the new local m=100 becomes active. Similarly when function1 is called both previous values of m are put on shelf and latest value (m=10) become active, a soon as it is done main (m=1000) takes over. The output clearly shows that value assigned to m in one function does not affect its value in the other function. The local value of m is destroyed when it leaves a function.
External variables:
Variables which are common to all functions and accessible by all functions of a program are internal variables. External variables can be declared outside a function.
Example
int sum;
float percentage;
main()
{
…..
…..
}
function2()
{
….
….
}
The variables sum and percentage are available for use in all the three functions main, function1, function2. Local variables take precedence over global variables of the same name.
For example:
int i = 10;
void example(data)
int data;
{
int i = data;
}

main()
{
example(45);
}
In the above example both the global variable and local variable have the same name as i. The local variable i take precedence over the global variable. Also the value that is stored in integer i is lost as soon as the function exits.
A global value can be used in any function all the functions in a program can access the global variable and change its value the subsequent functions get the new value of the global variable, it will be inconvenient to use a variable as global because of this factor every function can change the value of the variable on its own and it will be difficult to get back the original value of the variable if it is required.
Global variables are usually declared in the beginning of the main program ie., before the main program however c provides a facility to declare any variable as global this is possible by using the keyword storage class extern. Although a variable has been defined after many functions the external declaration of y inside the function informs the compiler that the variable y is integer type defined somewhere else in the program. The external declaration does not allocate storage space for the variables. In case of arrays the definition should include their size as well. When a variable is defined inside a function as extern it provides type information only for that function. If it has to be used in other functions then again it has to be re-declared in that function also.
Example:
main()
{
int n;
out_put();
extern float salary[];
……
…..
out_put();
}

void out_put()
{
extern float salary[];
int n;
….
…..
}
float salary[size];
A function when its parameters and function body are specified this tells the compiler to allocate space for the function code and provides type info for the parameters. Since functions are external by default we declare them (in calling functions) without the qualifier extern.
Structures:
C supports a constructed data type known as structure, which is a method for packing data of different types.
Structure is a convenient tool for handling a group of logically related data items. Structure is a derived data types used to store data items of different types.
Structure Definition:
A structure definition creates a format that may be used to declare structure variables. Ex: Let us create book structure
struct book_bank
{
char title[20];
char author[40];
int pages;
float price;};
};
Explanation:
The keyword struct declares a structure to store four fields title, author, pages, and price. These fields are called structure elements or members.
Each member belongs to different types.
book_bank is the name of the structure called structure tag. The tag name may be used subsequently to declare variables that have the tag’s structure.
The general format of a structure :
struct tag_name
{
data type member1;
data type member2;
:
:
:
data type member n;
};

Structure variable can declare as
struct tag_name struct_name1, struct_name2;
For Example :
struct book_bank
{
char title[20];
char author[40];
int pages;
float price;};
};

struct book_bank book1, book2,book3;

Points to remember in defining structure:
The template is terminated with a semicolon.
While the entire declaration is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template.
The tag name such as book_bank can be used to declare structure variables of its type later in the program.It is also allowed to combine both the template declaration. More than one variable can be declared in one statement. The declaration is as follows:
struct book_bank
{
char title[20];
char author[40];
int pages;
float price;};
}; book1,book2,book3;

Use of tag name is optional here.
Structures definitions appear at the beginning of the program file , before any variables or function are defined . they may also appear before the main( ).

Accessing Structure Members:

We can assign values to the member of a structure in a number of ways. The link between a member and variable is established using the member the member operator ‘ . ’ which is known as dot operator or period operator.

For Example .:
book.price
scanf(“%f\n”,&book1.price);



Structure Initialization:

A structure variable can be initialized, however a structure must be declared as static if it is not to be initialized inside a function.
We can initialize the variable using static keyword,

main( )
static struct
{
int weight;
float height;
}
student = {60,180.75};

This assigns the value 60 to student .weight an d180.75 students height. There is a one- one correspondence between the members and their initializing values. A lot of variation is possible in initializing a structure. The following statements initializing two structure variables, here it is essential to use tag name.

main( )
{
struct st_record
{
int weight;
float height;
};
static struct st_record student1={60,180.57};
static struct st_record tsudent2={53.170.60};
}

Another method is to initialize structure variables outside the function.

struct st_record
{
int weight;
float height;
student1={60,180.57};
};

main( )
{
static struct st_record student2 = {53.170.60};
}

C language does not permit the initialization of individual structure members within the template. The initialize must be done only in the declaration of the actual variables.

Comparison of Structures Variables:

Two variables of the same structure type can be compared the same way as ordinary variables.
If the person1 and person2 belong to the same structure, then the following operation are valid:

Operation Meaning


person1 = person2 Assign person2 to person1
person1 == person2 Compare all member of
person1 and person2 and
return 1 if they are equal , 0
otherwise.
person1!= person2 Return 1 if all the members are
not equal , 0 otherwise



Arrays of Structures:

It is possible to declare array of structure, each element of the array representing a structure variable.
For Example : struct class student[100];

The above statement defines the structure variable in an array called student. That consist of 100 elements. Each element is defined to be of the type struct class.

For Example .:

struct marks
{
int subject1;
int subject2;
int subject3;
};

main( )
{
static struct marks student[3]={{45,68,78}{65,57,78}{56,78,89}};
:
:
:
:
:
}
This declares the student as an array of three elements student[0], student[1], student[2] and initializes their member as follows:

student[0].subject1=45;
student[0].subject =56;
…………………………
…………………………
student[2].subject[2]=89;

Here student is an array. We use the usual array accessing methods to access individual’s elements and then the member operator to access member. An array of structures is stored inside the memory in the same way as a multidimensional array.

Arrays within Structures:

C permits these of array as structure members. Single or multi dimensional array of type of int or float. The following structure declaration is valid:

struct marks
{
int number ;
float subject[3];
}student[2];

Member subject contains three elements subject[0], subject[1], subject[2]. These elements can be accessed using appropriately subscript

Structures within Structures:

Structures defined with in structure means nesting of structures.

For Example .
struct salary
{
char name [20];
char department[10]

struct
{
int dearness;
int house_rent;
int city;
}allowances;

}employee;
The salary structure contains a member named allowance which itself is a structure with three members. The members contained in the inner structure namely dearness, house_rent, and city can be referred to as

employee. allowance.drearness
employee. allowance.house_rent
employee. allowance.city

An inner most member in a nested structure can be accessed by chaining all the concerned structure variables with the member using dot operator. We can also create more than one structure variable to the inner structure.

Structure and Functions:
We can pass structure variables as arguments to the functions. there are three methods by which the values of a structure can be transferred from one function to another.

1st ?It is to pass each member of the structure as an actual argument of the function call. The actual arguments are then treated independently like ordinary variables.

2nd ? Involves passing of a copy of the entire structure to the called function. Since the function is working on a copy of the structure, any changes to structure members with in the function is not reflected in the original structure.

3rd ?It employees a concept called pointer to pass the structure as an arguments. The address location of the structures is passed to the called function. The function can accessed indirectly the entire structure and work on it. The function passed to function.

The General Form:
function name (structure variables name )

The called function will take the following form:

data_type function name (st_name)

struct_type st_name;
{
……
……
…….
return(expression);
}





Example Program: Employee Pay Bill Using Structure

#include
#include

main()
{
struct employee
{
int eno;
char ename[15];
float bp;
}e[20];
int n,i;
float pf,lic,ded,gp,np,ta,bp;
clrscr();
printf("Enter the N Records\n");
scanf("%d",&n);
for(i=0;i{
scanf("%d" ,&e[i].eno);
scanf("%s", e[i].ename);
scanf("%f", &e[i].bp);
ta =e[i].bp*(0.3);
lic=e[i].bp*(0.2);
pf=e[i].bp*(0.5);
ded=pf+lic;
gp=e[i].bp+ta;
np=gp-ded;
}
printf("\n\n");
printf("ENO NAME BP DED GP NP\n");
for(i=0;i{
printf("%d %10s %.2f",e[i].eno,e[i].ename,e[i].bp);
printf(" %.2f",ded);
printf(" %.2f",gp);
printf(" %.2f",np);
printf("\n\n");
}
getch();
}




Unions:

Unions are similar to structure. It contains many members with different types. In structure each member of a unions use the same location, where all the members of the unions use the same location.
A union can be declared using the keyword union as follows:

union item
{
int m;
float x;
char c;
}code;

This declares a variable code of type union item. Dot ’ . ’ operator is used to access the union member.

For Eg:
code.m=345;
printf(“%d”, code.m);

Size of structure:

The unary operator sizeof( ) tell us the size of a structures. The expression will evaluate the number of bytes required to hold all the members of the structure x.

sizeof (sturct x)

If y is a simple structure variable of type sturct x, then the expression
sizeof(y);

Bit Fields:

A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length. a word can therefore be divided into number of bit fields. The name and size of bits fields are defined using a structure.







Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Overview of C:-
Previous Resource: MICROPROCESSOR AND APPLICATIONS:-
Return to Discussion Resource Index
Post New Resource
Category: Computer & Technology


Post resources and earn money!
 
Related Resources


Contact Us    Privacy Policy    Terms Of Use   

SpiderWorks Technologies Pvt Ltd. 2006 - 2007 All Rights Reserved.