Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 58

V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

ARRAYS
C Language provides a capability called array that enables the user to combine similar datatypes
into a single unit. Ordinary variables are able to store only one value at a time. If there were a
large amount of similar data to be handled then using a different variables for each data item
would make the job difficult and clumsy. C supports a derived datatype known as array that can
be used for such applications. An array is a fixed size sequenced collection of elements of the
same datatype. Since an array provides a convenient structure for representing data, it is
classified as one of the data structures in C.
An array is a group of elements consisting of similar type of data. All the element values
are identified by a single variable name along with the index. These array elements are allotted
memory locations in continuous manner, and so, it is easy to retrieve them. The use of an array
reduces the usage of so many variables in the program. Arrays are classified into 2 types as
follows:
(a) Single Dimensional arrays
(b) Multi Dimensional arrays.

SINGLE DIMENSIONAL ARRAYS:- In this type of array, we give only one dimension. The
dimension is the no. of elements that we want to have in an array. Each element in the array is
identified by its array name and its subscript or index. The index of an array starts from 0 and
lasts till size-1.
Syntax:
datatype array_name[size];
Data type is the type of data we want to store in an array, size indicates the no. of values that can
be stored in the array and array_name indicates the name of the array.
Assigning values to an array:- We can assign the values to an array in the following ways.
i) We can assign values into an array while declaring the array itself.
Eg: int a[5]={23,5,6,7,10};.
ii) We can also assign the values after declaring a variable.
eg: int a[5];
a[0]=5;
a[1]=12;
a[2]=4;
a[3]=10;
a[4]=55;
iii) We can assign the values to an array without specifying the size also. Here, the compiler
automatically assigns the size depending on the no. of values.
Eg: int a[ ]={4,8,12,16,18};
iv) We can also assign the values into an array during runtime also by using scanf. In this
we give the address of each and every element in which the value should be stored. This
makes the statement too long.
Eg: int a[5];
scanf(“%d%d%d%d%d”, &a[0],&a[1],&a[2],&a[3],&a[4]);
v) The above problem can be overcome by using loops in the program while accepting and
displaying. as shown below.
Eg: int a[5], i ;
for(i=0;i<5;i++)

Page 1
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

scanf(“%d”,&a[i]);

Eg: /*to accept array values and display them*/


main()
{
int a[5], i;
clrscr();
printf(“\nEnter the values :”);
for(i=0;i<5;i++)
scanf(“%d”,&a[i]);
printf(“\nThe values are :”);
for(i=0;i<5;i++)
printf(“\n%d”,a[i]);
getch();
}

MULTI DIMENSIONAL ARRAYS:- Arrays having more than one dimension are called
multi-dimensional arrays. There are 2 types of multi-dimensional arrays which are two
dimensional arrays (2D arrays) and three dimensional arrays (3D arrays).
Two dimensional arrays (2D arrays):- When we want values to be stored in the form of a row
and column i.e., like a matrix form, we have to use 2D arrays. In this type of array, we have to
specify the no. of rows and columns required and all the elements are allocated memory in
continuous locations.
Syntax to declare a 2D arrays:
datatype array_name[row_size][column_size];
Eg: int a[3][3];
The datatype indicates the type of data, array_name indicates the name for the array, row_size
indicates the no. of rows and column_size indicates the no. of columns. Each and every element
is identified with its index number showing the row and column position. The first element index
is [0][0] and the last index is [row_size-1][column_size-1]. For the array in the example above,
the elements are identified as a[0][0], a[0][1], a[0][2], a[1][0], a[1][1] ,a[1][2], a[2][0], a[2][1]
and a[2][2]. These elements are allocated memory in continuous locations only, even though
they are identified as separate rows.
Assigning values to a 2D arrays: We can assign values to a two dimensional array same way as
the single dimensional array as shown below.
i) We can assign the values into an array while declaring the array itself.
Eg: int a[2][2]={ 10,14,23,56}
ii) We can also assign the values by separating each row values in braces as shown below.
Eg: int a[3][3]={{3,4,7},{6,7,2},{10,12,11}};
iii) We can also values without specifying the row size also.
Eg: int a[ ][3]={2,4,6,8,10,12,14,16,18};
Here the row size is automatically taken as 3 depending on the no. of values given.
iv) We can also assign values after declaring the array also as shown below.
Eg: int a[2][2];
a[0][0]=10;
a[0][1]=20;

Page 2
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

a[1][0]=30;
a[1][1]=40;
Here the number of statements will be more as the size of the array is increased and also we have
to make changes the program to have new values in the array which is very risky.
v) We can also assign the values during the runtime by using scanf() as shown below.
Eg: int a[2][3];
scanf(“%d%d%d%d%d%d”,&a[0][0],&a[0][1],&a[0][2], &a[1][0],&a[1][1],&a[1][2]);
This method increases the length of the statement and there is a chance of making mistakes by
the user while typing the program.
vi) To avoid the above problem, we use scanf in looping statements as shown below.
Eg: int a[2][3], i, j;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf(“%d”,&a[i][j]);
In the above example, an array ‘a’ of size 2 rows and 3 columns is declared. The variables ‘i’
and ‘j’ are used for identifying the row index and column index respectively. We have to use two
for loops, the outer loop for row indexing and inner loop for column indexing.

Eg: /*multiplication of matrices*/


#include<stdio.h>
#include<conio.h>
main()
{
int a[10][10],b[10][10],i,j,m,n,p,q,k,c[10][10];
clrscr();
printf("\nEnter no. of rows and columns for first matrix a");
scanf("%d%d",&m,&n);
printf("\nEnter no. of rows and columns for second matrix b");
scanf("%d%d",&p,&q);
if(n= =p)
{
printf(“\nMultiplicatipon is possible”);
printf("\nEnter values into a array”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter values into b array");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<p;k++)

Page 3
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf("\nThe product of 2 matrices is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf(" %d",c[i][j]);
printf("\n");
}
}
else
printf("\nCannot multiply");
getch();
}

Note: C does not perform bound checking. Therefore, care should be exercised to ensure that
the array indices are within the declared limits.
Three Dimensional arrays (3D Arrays):- C allows array of two or more dimensions. A
maximum number of dimensions a C program can have depend on the compiler we are using.
Generally, an array having one dimension is called 1D array, array having two dimensions called
2D array and so on. So in C programming an array can have two or three or four or even ten or
more dimensions. More dimensions in an array means more data it can hold and of course more
difficulties to manage and understand these arrays. The following is the syntax for a 3D array.
Syntax:
datatype <array_name>[size1][size2][size3];
Eg:
int table[3][3][3];
In the above example array “table” is a 3D (A 3D array is an array of arrays of arrays.) array
which can hold 27 integer type elements. A 3D array can be assumed as an array of arrays of
arrays. It is array (collection) of 2D arrays and as we know 2D array itself is array of 1D array. A
diagram can help you to understand this.

3D Array Conceptual View

3D array memory map.

Page 4
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

We can initialize a 3D array at the compile time as we initialize any other variable or array, by
default an un-initialized 3D array contains garbage value. Let’s see a complete example on how
we can work with a 3D array.
/*program of Declaration and Initialization 3D Array*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, k, arr[3][3][3];
clrscr();
printf(“\nEnter values into 3x3x3 array”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
scanf(“%d”,&a[i][j][k];
}
}
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
printf("%d\t",arr[i][j][k]);
printf("\n");
}
printf("\n");
}
getch();
}

Working with characters and strings


Working with characters: To accept a single characters or a string, there are some functions in
C which are described below.
1) getch():- This function is used to accept a single character. The character while accepting
will not be seen on the screen. Using output statement we can display it on the screen.
There is no need to press ‘enter’ key. The control automatically goes to next statement for
execution.
2) getche():- This function is also used to accept a single character. The character while
accepting will be echoed (displayed) on the screen. There is no need to press ‘enter’ key.
The control automatically goes to next statement for execution.

Page 5
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

3) getchar():- This function is also used to accept a single character. In this, after accepting
a character, we have to press ‘enter’ key to execute the next statement. While using this
function, include file stdio.h in the program.
Eg: #include<stdio.h>
main()
{
charch; clrscr();
printf(“\nEnter a character :”);
ch=getch();
printf(“\nEntered character is : %c”,ch);
}
The above program may be used for the other 2 functions also by changing the function
name in the place of getch().
Working with strings:- A string is a variable length array of characters that is delimited by the
null character. Generally string characters are selected only from the printable character set.
Storing strings:-To store a string, since you don’t have a data type separately as string, we have
to use one of the available structures. Since strings are a sequence of characters, it is only natural
that the structures used to store string variables s the character array. In defining the array to
store a string, we must provide enough room for the data and the delimiter. The delimiter here
used is null character (‘\0’). The storage structure, therefore, must be one byte larger than the
maximum data size. Eg: char name [10]. In this ‘name’ variable a string of 9 characters can be
stored and one byte is used for the delimiter. The end of the string is identified with a null
character(‘\0’). After accepting a string, automatically a ‘\0’ is inserted in the location after the
last character. The ASCII value for ‘\0’ is 0.
Initializing string:- We can initialize a string the same way that we initialize any storage structure
by assigning a value to it when it is defined. In this case, the value is a string literal.
Eg: char str[10]= “Good Day”;
Since a string is stored in an array of characters, we do not need to indicate the size of the array if
we initialize it when it is defined. For example, we could define a string to store the month
January, as shown below.
char month[ ]=”January”;
In this case, the compiler will create an array of 8 bytes and initialize it with January and a null
character. We must be careful, however, because month is an array. If we now tried to store
“December” in it, we would overrun the array and destroy whatever came after the array.
Assigning the string:- Since the string is an array, the name of the string is a pointer constant. As
a pointer constant, it is an rvalue and therefore cannot be used as the left operand of the
assignment operator. This is one of the most common errors in writing a C program. Although
we could write a loop to assign characters individually, there is a better way. C provides a rich
library of functions to manipulate strings, including moving one string to another.
Reading and writing strings: C provides two basic ways to read and write strings. First we can
read and write strings with the formatted input/output functions, scanf/fscanf and printf/fprintf.
Second, we can use a special set of strings only functions, get string (gets/fgets) and put string
(puts/fputs).
Formatted string input (scanf):-We can use scanf () to read a string. While reading a string using
scanf(), it will not allow to accept the spaces in between a word. The conversion code for a string
is “s”. The scanf() skip any leading whitespace. Once they find a character, they read until they
find whitespace, putting each character in the array in order. When they find a trailing

Page 6
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

whitespace character, they end the string with a null character. The conversion specification
strings can use only three options fields, flag, maximum field size and size.
Flag:- Like all inputs, the only flag that can be used is the asterisk (*), which discards the data
read.
Maximum field size:- when present, the maximum field size specifies the maximum number of
characters that can be read.
Size:- If no size option is specified, we read normal characters. To read wide characters, we use
size 1 (ell).
Eg: scanf(“%9s”,month); The maximum characters that can be entered is only 9 and a null
character is inserted after reading the 9th character.
In addition to the string conversion code, we can also use a scan set conversion code to
read a string. The scan set conversion specification consists of the open bracket ( [ ), followed by
the edit characters, and terminated by the close bracket ( ] ). The characters in the scan set
identify the valid characters that are allowed in the string except the close bracket. The scan set
does not skip the leading white spaces instead they are placed into the string being read.
Eg:
scanf(“%10[0123456789.,-$]”, str);
Using the above scanf() we can read strings of 10 characters width containing only digits,
commas, periods, minus signs and a dollar sign.
Eg:
scanf(“%75[^\n]”, str);
Using the above statement we can read a string containing 75 characters that will not include
new line (\n) character. We use ‘^’(caret) symbol to indicate the characters that we do not want
in a string.
Formatted string output (printf):- The printf() function is used to write strings onto the screen. C
has four options that can be used with this function. They are left justify flag (-), width, precision
and size.

Eg1 :- printf(“|%-30s|\n”, “This is the string”);


Output :
|This is the string |
Eg 2:- printf(“|%30s|\n”, “This is the string”);
Output :
| This is the string|
Eg 3:- printf(“|%-15.14s|”, “12345678901234567890”);
Output:
|12345678901234 |
The precision option sets the maximum size and in the above example the maximum size is set to
one less than the width to ensure a space between the string and the next column.
/*program using printf and scanf to read and write a string*/
#include <stdio.h>
#include <conio.h>
main( )
{
char name[15]; clrscr();
printf(“\nEnter your name”);

Page 7
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

scanf(“%s”,name);
printf(“\nYour name is %s”,name);
getch(); }
String input/output:- In addition to the formatted string functions, C has two sets of string
functions that read and write strings without reformatting any data. They are gets and puts.
gets():- This function is used to accept a string along with spaces. It takes only one parameter of
char datatype which is a string pointer. Since we do not specify any size, it reads data until it
finds a newline or until the end-of-file. If a newline character is read, it is discarded and replaced
with a null character.
Syntax :- char* gets(char* strptr);
puts():- It is used to display the accepted string along with spaces. It also takes only one
parameter. It is also used to print the messages on the screen similar to printf(). The null
character is replaced with a newline in puts.
Syntax :-int puts(const char* strptr);
Eg:
#include<stdio.h>
#include<conio.h>
main()
{ char name[25]; clrscr();
printf(“\nEnter a string :”);
gets(name);
puts(“The string is :”);
puts(name);
getch();
}

String Manipulation Functions


Since string is not a standard type, we cannot use it directly with most C operators. For example,
to move one string to another, we must move the individual elements of the sending string to the
receiving string. We cannot simply assign one string to another. It we were to write the move, we
would have to put it in a loop. C has provided a rich set of string functions. Besides making it
easier for us to write programs, putting the string operations in functions provides the
opportunity to make them more efficient when the operation is supported by hardware
instructions. The following are some of the string or library functions available in ‘C’.
a) strlen():- This function is used to find the length of the given string excluding the null
character. It takes only one parameter. The parameter may be directly a string in double
quotes or a variable containing a string. It returns integer value which is the no. of characters
present in the given string.
syntax:strlen(variable);
eg: /*Program to find the length of a given string*/
#include <stdio.h>
#include <conio.h>
main()
{
int l; char name[10]; clrscr();

Page 8
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

printf(“\nEnter a string :”);


scanf(“%s”,name);
l=strlen(name);
printf(“\nNumber of charactersin the given string is %d”,l);
getch();
}
b) strcpy():- It is used to copy a string from one variable to another variable including the null
character. It takes 2 parameters. First parameter is the destination variable into which you
want to store a string and the second variable is the string that you want to copy. Here string1
is copied into string2. We should ensure that destination string array (string2) is large enough
to hold the sending string (string1).
Syntax:-
strcpy( string2, string1);
Eg:/*program to copy a string*/
#include <stdio.h>
#include<conio.h>
main()
{
char name[15],name1[15]; clrscr();
printf(“\nEnter a string :”);
scanf(“%s”,name);
strcpy(name1,name);
printf(“\nString 1 is %s”,name);
printf(“\nString 2 is %s”,name1);
getch(); }
c) Strcat():- This function is used to concatenate(join) 2 strings as a single string. It takes 2
parameters. The second parameter value will be joined to the first string.
Syntax:-
strcat(string1, string2);
In the above syntax, string2 value will be joined to the end of string1.
Eg: /*program to concatenate strings */
#include<stdio.h>
#include<conio.h>
main()
{
char name[15],name1[35];
printf(“\nEnter a string :”);
scanf(“%s”,name);
printf(“\nEnter another string :”);
scanf(“%s”,&name1);
strcat(name1,name);
printf(“\nString after concatenation is %s”,name);
getch();
}
d) Strrev():- This function reverses the given string and after reversing stores it in the same
variable. It takes only one parameter and it is the string that we want to reverse.
Syntax:-

Page 9
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

strrev(string);
Eg:
/*program to reverse a given string */
#include <stdio.h>
#include<conio.h>
main()
{
char name[15];clrscr();
printf(“\nEnter a string :”);
scanf(“%s”,name);
strrev(name);
printf(“\nReversed string is %s”,name);
getch();
}
e) Strcmp():- This function compares two strings until unequal characters are found or until the
end of the strings is reached. It returns value less than 0 when string1 is less than string2 and
greater than 0 when string 1 is greater than string2. It returns 0 when both strings are equal.
While comparing the 2 strings it will compare the ASCII codes for the characters in the string
and returns the difference between the ASCII code values.
Syntax:-
strcmp(string1, string2);
Eg:
/*program to compare 2 string*/
#include<stdio.h>
#include<conio.h>
main()
{
char name[10],name1[10];int m ; clrscr();
printf(“\nEnter a string :”);
scanf(“%s”,name);
printf(“\nEnter another string :”);
scanf(“%s”,name1);
m=strcmp(name,name1)
if(m==0)
printf(“\nBoth strings are equal”);
else if(m<0)
printf(“\nString 1 is smaller”);
else
printf(“\nString 2 is greater”);
getch();
}
The above programs can also be done without using built in functions, by using for loops and
arrays.

Two Dimensional character arrays:- To store a single string we have to use single dimension
character array. If we want to store more than one string in the same variable, we have to declare

Page 10
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

the variable as two dimensional array of char datatype. The memory for the elements of all the
strings stored will be allocated in continuous locations only.
Eg: char name[5][10];
The above statement declares a variable of name which can store 5 names of 10 characters each.
At the end of each and every string a ‘\0’ (null character) will be stored to indicate the end of the
string.

/*Program to accept 5 names and display them*/


#include<stdio.h>
#include<conio.h>
main()
{
char names[5][10];
int i;
clrscr();
printf(“\nEnter 5 names”);
for(i=0;i<5;i++)
scanf(“%s”,&names[i]);
printf(“\nThe names are \n”);
for(i=0;i<5;i++)
printf(“\n%s”,names[i]);
getch();
}

POINTERS
All personal computers have a RAM of 125MB, 256MB and 512MB. Many users now-a-days
use 1GB and 2GB RAM also. Each byte in the memory has an address which is a unique
unsigned number and starts from 0 till the end of the memory available i.e., for example for a
1KB RAM, the addresses will be from 0 to 1023. We can also retrieve values stored in the
variables if we know the address of that variable. This can be done using pointers. Pointers play
vital role. Without pointers we cannot store any files in the hard disk and also no data structures
can be used. The data structure is creating the operating system.
Advantages of pointers :-The following are the some of the advantages of pointers.
1. Execution speed increases.
2. Pointers are used in direct addressing which is most often used in assembly languages.
3. Pointers are used in dynamic memory management (i.e., dynamic memory allocation and
deallocation ).
4. A pointer is used to access a location in the memory whose storage is allocated dynamically.
This dynamically allocated storage is called a heap.
5. Variables that are dynamically allocated from the heap are called heap dynamic variables.
The heap dynamic variables do not have the associated identifiers. Hence, they can be
referenced only by pointers and reference type variables.
6. Use of pointers makes the coding process simple and easy.
7. Pointers are used to create recursive types that are important in data structures and
algorithms.

Page 11
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

A pointer stores the address of another variable or address of another pointer. It is


denoted by using a ‘*’ before it. The ‘&’ is known as the address operator and it is used to
assign a variable address to a pointer. To print the address of a variable we have to use ‘%u’
format specifier. It represents unsigned integer. To display the value through the pointer, then
also we have to use ‘*’.
Syntax for declaring a pointer:-
Datatype *ptr_var;
Datatype indicates the type of data the pointer is pointing to. That is the type of value whose
address is stored in the pointer. Ptr_var is the name of the pointer variable and * indicates
that the variable is a pointer.
/*program using pointers*/
#include<stdio.h>
#include<conio.h>
main()
{
int a, *p;
printf(“\nEnter a value :”);
scanf(“%d”,&a);
p=&a;
printf(“\nValue of a is ‘a’ : %d”,a);
printf(“\nValue of a is ‘*p’ : %d”,*p);
printf(“\nAddress of a ‘&a’ : %u”,&a);
printf(“\nAddress of a is ‘p’ : %d”,p);
printf(“\nValue of p is ‘p’ : %d”,p);
printf(“\nAddress of p is ‘&p’ : %u”,&p);
getch();
}
Pointer arithmetic:-We cannot use the arithmetic expression to assign to a pointer variable like,
p=&(a+b). We can add or subtract the addresses but cannot divide or multiply.
/*program using pointer arithmetic */
#include <stdio.h>
#include <conio.h>
main()
{
int *p,*q,*r,a,b,c;
clrscr();
p=&a;
q=&b;
r=&c;
a=10;
b=15;
*r=a+b;
printf(“\na = %d \t b= %d \t c= %d”,a,b,c);
*p=a+3;

Page 12
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

*q=b+2;
c= *p+*q;
printf(“\na = %d \t b= %d \t c= %d”,a,b,c);
*p=*p-2;
*r=*p+*q;
printf(“\na = %d \t b= %d \t c= %d”,*p,*q,*r);
getch();
}

FUNCTIONS

C supports modular programming. We can divide a large program into small modules or parts
called as modules. These modules are known as functions. A function may be defined as a self-
contained block of statements that perform a specific task. It is difficult to implement a large
program even if its algorithm is available. To implement such a large program, it should be split
into number of independent tasks, which can be easily designed, implemented and managed.
This process of splitting a large program into small manageable tasks and designing them
independently is popularly called divide and conquer technique.
A repeated group of instructions in a program can be organized as a function. A function is a
set of program statements that can be processed independently. A function can be invoked which
behaves as though it’s code is inserted at the point of the function call. The communication
between calling function and called function takes place through parameters. The function can be
designed, developed and implemented independently by different programs. The implemented
function can be formed as a software library. The following are the advantages of functions.
1) Modular programming.
2) Reduction in the amount of work.
3) Program and function debugging easier.
4) Division of work is simplified due to the use.
5) Reduction in size of the program due to the code reusability.
6) Functions can be accessed repeatedly without redevelopment, which in turn promote reuse
of code.
7) Library of functions can be implemented by combining well designed, tested and proven
functions.
Functions can be categorized in following 2 ways. They are (1) Built-in or System defined
functions and (2) User defined functions
(1) Built-in functions:- These are the default functions which are prewritten and preoccupied.
All system-defined functions are present in C library. C is divided into different groups.
Each group contains certain common functions and each group is called a header file with .h
extension such as stdlib.h, conio.h, math.h etc. These header file functions can be used
anywhere in the function and as many times as we want. Eg: scanf(), getch(), clrscr(), etc.
(2) User defined functions:-These are the functions which are defined by the user to perform his
work. While naming a function the following rules are to be followed.

Page 13
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

a) The name of the function can be any name given by the user which should be short and
meaningful.
b) It should not contain spaces.
c) We can use underscore ( _ ) in a function name.
d) Keywords and other pre-defined function names should not be given as function names.
e) Function name should start with an alphabet or an underscore.

Function Components:- Every function has the following elements associated with it.
 Function declaration or function prototype
 Function definition (function declarator and function body)
 Function call
 Function parameters
 Return statement
Function declaration or function prototype:- Functions can be defined any where in the program.
They may be defined before the main() or after the main(). The function prototype provides the
following information to the compiler.
1) The name of the function
2) Type of value returned (optional, by default it is integer)
3) The number and type of arguments that must be supplied in a call to the function.
When a function call is encountered, the compiler checks the function call with its prototype so
that correct argument types are used. The following is the syntax of function prototype.
Syntax:-
return_datatype function_name(argument list);
Eg: 1) float average(int,int,int);
2) void total(int, float, float);
Return_datatype is the type of data the function is returning back to the calling function from the
called function. By default any function, returns integer type of data. If there is no return value,
the keyword ‘void’ should be placed before the function. Function_name is the name for the
block of statements that are to be executed when called. The function name should not contain
spaces or any other special character except underscore (_). Keywords should not be used as
function names.
Argument list contains the type of values that should be passed to the function, so that the
function makes use of them for performing a particular task. These are also known as
parameters. The function declaration should end with a semi colon.
When a function returns an integer value or function takes integer parameters then there is no
need for function declaration. In other cases, function declaration is compulsory.
Function Definition:- The function itself is referred to as a function definition. The function
definition contains the code for a function. It is made up of two parts: the function header and the

Page 14
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

function body, which is a compound statement. The compound statement must have an opening
and closing brace and it has a declaration and statement sections.
The function header consists of three parts: the return type, the function name and the
formal parameter list. A semi colon is not used at the end of the function definition header. The
function body contains the local declarations and the function statements. The function
definition can be given before main() or after the main(). When the function definition is written
before main(), then there is no need of function declaration for that function.

Syntax:
return_datatype function_name(formal parameter list)
{
local declarations
executable statements
return statement.
}
Eg:
float average(int a, int b, int c)
{
float m;
m=(a+b+c)/3.0;
return m;
}
Function call:- A function is a dormant(inactive) entity which gets life only when a call to the
function is made. A function call is specified by the function name followed by the arguments
enclosed in parentheses and terminated by a semicolon. The return type is not mentioned in the
function call. Executing the call statement causes the control to be transferred to the first
statement in the function body and after execution of the function body, the control is returned to
the statement following the function call. The return value is assigned to the local variable in C
program.
Syntax:
Function_name (actual parameter list);
Eg: average(m1, m2, m3);
Function Parameters:-Parameters are the values that are passed to the function to be used in the
program. There are two types of parameters in C. They are actual parameters and formal
parameters.
Actual parameters:- The parameters that are passed in function call are called actual parameters.
These parameters are defined in the calling function. Actual parameters can be variables,
constants or expressions.
Formal parameters:- The parameters that are used in function definition are called formal
parameters. These parameters belong to the called function. These can be only variables but not
expressions or constants. Parameters that are specified in the function header section of function
definition are known as formal parameters. When a function call is made, a one-to-one
correspondence is established between the actual and formal parameters. The scope of formal

Page 15
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

parameters is limited to its function only. We can have same or different names for actual and
formal parameters.
Function return:-Function can be grouped into two categories namely functions that do not have
a return value (void function) and the function that have a return value. The calling function must
be able to receive the value returned by the function. The return statement in a function need not
be at the end of the function. It can occur anywhere in the function body and as soon as it is
encountered, execution control will be returned to the calling program. Return statement returns
a value from the called function to the calling function. The value may be directly a number,
value in a variable or an expression.

Syntax:
return (value or expression);
Eg; return 10;
return b;
return (a+b);
While using return statement, we have to follow some important points which are listed below:
1) A return statement can appear anywhere in the function. It is not necessarily to be at the end.
2) A function can have any number of return statements depending on certain conditions.
Although it is recommended that functions have a single entrance and a single exit.
3) A single return statement can return only one value at a time.
4) A return statement always returns an integer value. In order to return some other type of
values, the data type must be specified in the function prototype.
5) A return statement without any return value returns a garbage value to the calling function.
6) The functions having return type void returns nothing to the calling function.
Types of functions:-The user defined functions can be written in the following ways as
a) without parameters and without return value
b) without parameters and with return value
c) with parameters and without return value
d) with parameters and with return value
a) Without parameters and without return value:- In this type of function, we will not pass any
values to the function and also do not return any value to the main program (calling
program). The result is displayed in the function itself.
Eg:
/*program using without parameters and without return value*/
#include<stdio.h>
#include<conio.h>
void add(void);
main()
{
clrscr();
printf(“\nFirst time addition”);
add();
printf(“\nSecond time addition”);
add();

Page 16
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

printf(“\nThird time addition”);


add();
getch();
}
void add(void)
{
int a,b;
printf(“\nEnter 2 values”);
scanf(“%d%d”,&a,&b);
printf(“\nSum is %d”,a+b);
}
b) Without parameters and with return value:- In this type of function, we will not pass
parameters to the function but we will get a value from the function. The result is displayed
in the calling program.
Eg:
/*program using without parameters and with return value*/
#include<stdio.h>
#include<conio.h>
int add(void);
main()
{
int s; clrscr();
s=add();
printf(“\nThe sum of two numbers is %d”, s);
getch();
}
int add(void)
{
int t,a,b;
printf(“\nEnter 2 numbers”);
scanf(“%d%d”,&a,&b);
t=a+b;
return t;
}
c) With parameters and without return value:- In this type, we pass parameters to the function
but we will not take the return value. The output value if any is displayed in the function
itself.
Eg:
/*program using with parameters and without return value*/
#include<stdio.h>
#include<conio.h>
void add(int, int);
main()
{
int a,b; clrscr();

Page 17
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

printf(“\nEnter 2 values :”);


scanf(“%d%d”,&a,&b);
add(a,b);
getch();
}
void add(int p, int q)
{
int t;
t=p+q;
printf(“\nSum is %d”,t);
}
d) With parameters and with return value:- In this, we pass parameters to the function and also
return a value from the function.

/*program using with parameters and with return value*/


#include<stdio.h>
#include<conio.h>
float simple(float, float, float);
main()
{
float p,t,r,si; clrscr();
printf(“\nEnter amount, interest and time”);
scanf(“%f%f%f”, &p, &r, &t);
si=simple(p,r,t);
printf(“\nSimple interest is %0.2f”,si);
getch();
}
float simple(float a, float b, float c)
{
float s;
s=(a*b*c)/100;
return s;
}

Nested functions:- Calling a function inside another function is known as nested function. We
can define as many function as we want in the program and also can call a function or many
functions any number of times. The following program shows the use of nested function.
/*program using nested functions */
#include<stdio.h>
#include<conio.h>
float average(float, float, float);
int total(int,int,int);
main()
{
int a,b,c; float avg;

Page 18
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

clrscr();
printf(“\nEnter 3 numbers:”);
scanf(“%d%d%d”,&a,&b,&c);
avg=average(a,b,c);
printf(“\nThe average of 3 numbers is %f”,avg);
getch();
}
float average(int p, int q, int r)
{
int tot; float av;
tot=total(p,q,r);
av=tot/3.0;
return av;
}
int total(int x, int y, int z)
{
int sum;
sum=x+y+z;
return sum;
}

Recursive functions:- Recursion is a repetitive process in which a function calls itself. A


function call in a function definition that calls itself is known as recursive function.

/*program using recursive function to find the factorial of a given number*/


#include<stdio.h>
#include<conio.h>
long int factorial(long int);
main()
{
long int fact, n; clrscr();
printf(“\nEnter a number :”);
scanf(“%ld”,&n);
fact=factorial(n);
printf(“\nThe factorial of a given number is %ld”,fact);
getch();
}
long int factorial (long int p)
{
if(p= =1)
return 1;
else
return (p*factorial(p-1));
}

Page 19
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

Functions and arrays:-We can also pass single dimensional & double dimensional arrays as
parameters to a function. When we pass an array as parameter, the reference for the array is
passed to the called function and not the value. There is no need of returning an array from the
function to the calling program. This is because whatever changes we make in the formal
parameter array, will get reflected in the actual parameter array. While passing the array as
parameter, we have to specify the array name and no. of elements of that array in the function
call.

/*program to pass array as parameter to a function */


#include<stdio.h>
#include<conio.h>
void accept (int[], int);
void display(int [],int);
void sort(int[], int);
main()
{
int a[10],n, i; clrscr();
printf(“\nEnter the number of elements :”);
scanf(“%d”,&n);
accept(a,n);
printf(“\nArray values are :”);
display(a,n);
getch(); }
void accept(int p[10], int n)
{
printf(“\nEnter the values :”);
for(i=0;i<n;i++)
scanf(“%d”,&p[i]);
}
void display(int p[10], int m)
{
int i;
for(i=0;i<m;i++)
printf(“\n%d”,p[i]);
}

Standard functions (predefined functions):- C provides a rich collection of standard functions


whose definitions have been written and are ready to be used in our programs. To use these
functions we must include their function declarations. The function declarations for these
functions are grouped together and collected in several header files. Instead of adding the
individual declarations of each function, therefore, we simply include the headers at the top of
our programs. The ‘include’ statement causes the header files for different pre-defined functions
to be copied into out program. Then, when the program is linked, the object code for these
functions is combined with out code to build the complete program. The following are some of
the pre-defined functions:

Page 20
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

Math functions:- Many important library functions are available for mathematical calculations.
Most of the function declarations for these functions are in either the math header file (math.h) or
standard library (stdlib.h). In general, the integer functions are found in stdlib.h.

a) abs( ):- This function returns the absolute value of a number.


b) ceiling( ):- This function rounds the given float value into its nearest higher integer value.
c) floor( ):- It is used to round a given float value to its nearest lowest integer value.
d) round( ):- This function rounds the given float value to its nearest integer value depending on
the decimal digit.
e)pow( ):- It returns the value of the x raised to the power y i.e, xy.
f) sqrt( ):- It returns the non-negative square root of a number. An error occurs if the number is
negative.

/*program using predefined functions*/


#include <stdio.h>
#include <conio.h>
#include <math.h>
main()
{
int n, x, y;
clrscr();
printf(“\nEnter a number for absolute value” );
scanf( “ %d”, &n);
printf(“\nAbsolute value of %d is %d”, n , abs(n));
printf(“\nEnter a number to find the square root”);
scanf(“%d”, &n);
x= sqrt(n);
printf(“\nSquare root of %d is %d”, n, x );
printf(“\nEnter value for base and power”);
scanf(“%d%d”,&x,&y);
n=pow(x,y);
printf(“\nPower is %d”, n );
getch();
}

Parameter passing:- The term parameter passing refers to the different ways in which
parameters (arguments) are passed to or from a function. The function that makes the call is
known as the calling function and the function that is invoked is known as the called function. A
function can call any other function that is visible to it. There are two basic modes of how data
transfers take place between functions. They are pass-by-value and pass-by-reference (pass-by-
address).
Pass by value:- When an actual parameter is passed by value, the value of the actual parameter
is used to initialize the corresponding actual parameter. In other words, the formal parameter
receives a copy of the value of the actual parameter. Any changes made to the value of this

Page 21
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

formal parameter do not affect the value of actual parameter. Pass by value is the parameter
passing mechanism by default in C.
Eg: /* exchanging the values using call by value */
#include<stdio.h>
#include<conio.h>
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
}
main()
{
int a,b; clrscr();
printf(“\nEnter the 2 values :”);
scanf(“%d%d”,&a,&b);
printf(“\nBefore swapping \n a= %d \t b= %d”,a,b);
swap(a,b);
printf(“\nAfter swapping \n a= %d \t b= %d”,a,b);
getch();
}

Pass by reference:- When an actual parameter is passed to a function, the address of the actual
parameter is passed to the formal parameter. This way, the actual parameter and formal
parameter refer to the same memory location. As a consequence, any changes made to the formal
parameter affect the value of the actual parameter. This mechanism is implemented using
pointer. A pointer is a variable that can hold the address of another variable. Every location has a
unique address associated with it. The address of a variable remains constant throughout the
execution of a program, whereas the content of the variable may change many times while the
program is running.
Eg: /*Exchanging the values using call by address */
#include<stdio.h>
#include<conio.h>
void swap(int *p, int *q)
{
int t;
t=*p;
*p= *q;
*q= t;
}
main()
{
int a,b; clrscr();
printf(“\nEnter 2 values :”);

Page 22
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

scanf(“%d%d”,&a,&b);
printf(“\nBefore swapping \n a= %d \t b= %d”,a,b);
swap(&a,&b);
printf(“\nAfter swapping \n a= %d \t b= %d”,a,b);
getch();
}

STORAGE CLASSES
To fully define a variable one needs to mention not only its type, but also its ‘storage class’.
Every variable not only has a data type but also have a storage class. If we don’t specify any
storage class of a variable in its declaration, the compiler will assume a storage class depending
on the context in which the variable is used. Thus, variables have certain default storage classes.
A variable name identifies some physical location within the computer where the string of bits
representing the variable value is stored. There are basically two kinds of locations in a
computer where such a value may be kept. They are memory and CPU registers. It is the
variable’s storage class, which determines in which of these two locations the value is stored. A
variable storage class tells us
1) Where the variable would be stored.
2) What will be the initial value of the variable, if the initial value is not specifically assigned
(i.e, the default initial value).
3) What is the scope of the variable, i.e., in which functions the value of the variable would be
available.
4) What is the life of the variables; i.e., how long would the variable exist.
There are four storage classes in C.
a) Automatic storage class
b) External storage class
c) Register storage class
d) Static storage class
a) Automatic storage class:- These variables comes into existence whenever and wherever the
variable is declared. These variables are also called as local variables, because these are
available local to a function. These variables are allocated memory in RAM and it has a
default value, which is a garbage value. It is local to the block in which it has been declared
and its life is till the control remains within the block in which the variable is defined or in
the function in which it is declared. The key word used is ‘auto’.
/*program using automatic variables*/
#include<stdio.h>
#include<conio.h>
void fun1(void);
main()
{
int a=10,b;
clrscr();
printf(“\na = “%d”);
b=5;
{

Page 23
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

int c=7;
printf(“\na=%d, b=%d, c=%d”,a,b,c);
a=15;
}
printf(“\na=%d, b=%d”,a,b);
printf(“\nc=%d”,c); /*error, ‘c’ is declared in the block and not available outside the block*/
fun1();
printf(“\nm=%d”,m);/* error because ‘m’is declared in fun1() and not available outside the
function*/
getch();
}
void fun1(void)
{
int m=6;
printf(“\nm in the function is %d”,m);
}
b) Extern storage class:- This variable is allocated memory in the RAM. Default initial value is
zero. The scope of the variable is global and the extent of variable is till the end of the
program. The keyword used is ‘extern’. The variables that are declared outside the main()
are known as global variables or extern variables.
/*Program using extern variables*/
#include<stdio.h>
#include<conio.h>
void fun1(void);
int a=15;
main()
{
int b=20; clrscr();
printf(“\na= %d,b= %d”,a, b);
fun1();
printf(“\na= %d,b= %d”,a, b);
getch();
}
void fun1(void)
{
printf(“\na= %d, a);
a=25;
}
c) Register storage class:- The storage of this type of variables is in the CPU registers. It has a
garbage value initially. The scope of the variable is in the function or in the block in which it
is declared. The extent of variable is in the block or in the function in which the variable is
defined. A value stored in a CPU register can always be accessed faster than the one which is
stored in memory. Therefore, if a variable is used at many places in a program it is better to
declare its storage class as register. A good example of frequently used variables is loop
counters. The key word used is ‘register’. The advantage of this variable can be best viewed
in larger programs only.
/*program using register storage class*/

Page 24
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

#include <stdio.h>
#include <conio.h>
main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
printf(“\n%d”,i);
getch();
}

d) Static storage class:- These are allocated memory in the RAM and default initial value is
zero. It is local to the block in which it has been defined. The value of the variable persists
between different function calls. The value will not disappear once the function in which it
has been declared becomes inactive. It is unavailable only when you come out the program.
The key word used is ‘static’. The scope of the variable is in the function or in the block in
which it is declared. The extent of the variable is till the end of the program.
/*program using static variable*/
#include<stdio.h>
#include<conio.h>
void value(void);
main()
{
clrscr();
value();
value ();
value();
getch();
}
void value(void)
{
static int a=5;
a=a+2;
printf(“\n%d”,a); }

PREPROCESSOR DIRECTIVES
Any program execution needs certain steps. They are
(1) C program is written in the editor,
(2) Compilation
(3) Linking
(4) Executable code is generated
In between these stages, there also involves one more stage i.e. preprocessor. The preprocessor is
a program that processes the source program before it is passed on to the compiler. The program
typed in the editor is the source code to the preprocessor. The preprocessor then passes the
source code to the compiler. It is also nonessential to write the program with preprocessor
facility. But it is a good practice to use it preferably at the beginning.

Page 25
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

One of the most important features of C language is to offer preprocessor directives. The
preprocessor directives are always initialized at the beginning of the program. It begins with the
a symbol # (hash). It can be placed anywhere but quite often it is declared at the beginning
before the main() function or any particular function.
#define:- The syntax of #define directive is as follows.
#define identifier <substitute text>
Eg: #define PI 3.14
This statement defines macro templates. During preprocessing the processor replaces every
occurrence of PI with 3.14. Here, PI is a macro template and 3.14 is the macro expansion. The
macro templates are generally declared in upper case for quick identification. The macro
templates and its expansions must be separated with at least one blank space.
#undef :- A macro defined with #define directives can be undefined with #undef directive. It is
useful when we do not want to allow the use of macros in any portion of the program. It is used
in the middle of the program i.e. inside main() program.
Syntax: #undef identifier
Eg: #undef PI
#include:- The #include directive loads specified file in the current program. The macros and
functions of loaded file can be called in the current program. The included file is also compiled
with current program. The syntax is as given below.
(a) #include “filename”
Eg: #include “stdio.h”
The filename is included in the double quotation marks which indicates that the search for the
file is made in the current directory and in the standard directories.
(b) #include <filename>
E: #include <stdio.h>
Here the search for the file is made only in the standard directories.
#ifdef , #else, #endif :- These are the frequently used conditional compilation directives. These
directives allow the programmer to include the portions of the codes based on the conditions.
The compiler compiles selected portion of the source codes based on the conditions. The syntax
of the #ifdef directives is given below.
Syntax:
#ifdef <identifier>
{
Statement 1;
Statement 2;
}
#else
{
Statement 3;
Statement 4;
}
#endif
The #ifdef preprocessor tests whether the identifier has defined substitute text or not. If the
identifier is defined then #if block is compiled and executed. The compiler ignores #else block
even if errors are intentionally made. Error messages will not be displayed. If identifier is not
defined then #else block is compiled and executed.

Page 26
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

/*program using conditional compilation statement*/


#include <stdio.h>
#include <conio.h>
#define LINE 1
main()
{
clrscr();
#ifdef LINE
printf(“\nThis is line number One”);
#else
printf(“\nThis is line number Two” );
#endif
getch();
}

DYNAMIC MEMORY ALLOCATION


Allocating the memory during runtime (execution of the program) is known as Dynamic
Memory Allocation. This way of allocating memory avoids the wastage of memory. While
executing the program, if memory is required in the middle of the program for storing a value,
then only it will be allocated. So, there is no need to allocate memory before only. The following
are the functions involved in Dynamic Memory Allocation. While using these functions in the
program include the alloc.h header file.
(1) malloc():- This 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.
Syntax:
ptr= (cast_type *)malloc(bytesize);
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.
Eg: x=(int *) malloc(100 * size of(int));
On successful execution of this statement, a memory space equivalent to 100 times the size of an
int byte is reserved (i.e., 100 x 2 bytes=200 bytes) and the address of the first byte of the memory
allocated is assigned to the pointer x of type of int. If there is not enough space, NULL pointer is
returned.
/*program using malloc() */
#include <stdio.h>
#include<conio.h>
#include<alloc.h>
main()
{
int s=0, *p;
char ch=’y’;
clrscr();
while(ch==’y’ || ch==’Y’)

Page 27
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

{
p=(int *) malloc(sizeof(int));
printf(“\nEnter a value”);
scanf(“%d”,p);
s=s+*p;
printf(“\nDo you want to continue?”);
ch=getch();
}
printf(“\nThe sum of accepted numbers is %d”,s);
getch();
}
(2) Calloc():- It is another function which is 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 sets
all bytes to zero.
Syntax :
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.
Eg:
struct student
{
char name[15];
intrno, total;
};
struct student *p;
p=(struct student *)calloc(3, size of(struct student);

/*program using calloc()*/


#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct student
{
intrno,total;
char name[15];
}
main()
{
struct student *p;
charch='y';
clrscr();
while (ch=='y'||ch=='Y')
{
p=(struct student *) calloc(1,sizeof(struct student));
printf("\nEnterrno,name and total");

Page 28
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

scanf("%d%s%d",&p->rno,p->name,&p->total);
printf("\nRNo : %d",p->rno);
printf("\nName : %s",p->name);
printf("\nMArks : %d",p->total);
printf("\nDo you want to continue?");
ch=getche();
}
getch(); }

(3) realloc():- This function is used to change the memory size already allocated. This process is
called reallocation of memory.
Syntax:
ptr=realloc(ptr, newsize);
This function allocates a new memory space of size ‘newsize’ to the pointer variable ‘ptr’ and
returns a [pointer to the first byte of the new memory block. The new size may be larger or
smaller than the original size. The new memory block may or may not begin at the same place as
the old one. If it is unable to find additional space in the same region, it will create the same in an
entirely new region and move the contents of the old block into the new block. The function
guarantees that the old data will remain intact.
/*program using realloc*/
#include<stdio.h>
#include<alloc.h>
#include<conio.h>
main()
{
int i,*p,*t;
clrscr();
p=(int *)malloc(5*sizeof(int));
printf("\nEnter 5 values");
for(i=0;i<5;i++)
scanf("%d",(p+i));
printf("\nBefore reallocating memory values are");
for(i=0;i<5;i++)
printf("\n%d %u",*(p+i),(p+i));
p=realloc(p,20);
printf("\nEnter another 5 values");
t=p+5;
for(i=0;i<5;i++)
scanf("%d",(t+i));
printf("\nValues and memory locations for new values");
for(i=0;i<5;i++)
printf("\n%d %u",*(t+i),(t+i));
printf("\nValues are");
for(i=0;i<10;i++)
printf("\n%d",*(p+i));
getch();

Page 29
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

}
(4) free():-Compile time storage of a variable is allocated and released by the system in
accordance with its storage class. With the dynamic run-time allocation, it is our responsibility to
release the space when it is not required. The free() function is used to release the block of
memory for future use.
Syntax
free(ptr);

STRUCTURES
Arrays can create a group of data elements which are of the same data type, may be int, float or
char. An array is a homogeneous structure. To reference an element in the array the name of the
array followed by its subscript is given. The arrays do not support elements of different datatypes
to be grouped and stored with one name. C provides a means of grouping different data items
together using a concept known as structures.
A structure is a derived data type. It is a collection of one or more variables of different
datatypes grouped together under a single name for convenient handling. It is called a record in
languages such as Pascal and COBOL. Using structure, data can be organized in a more
meaningful way in the data files or databases. It is a powerful feature that is useful to improve
the design and efficiency of programs. Finally a structure is defined as a group of elements of
different data types which are logically related.
Uses of structures:-The main application of structures is maintaining the database management.
But apart from this we can use structures in a variety of applications as follows.
1. Changing the size of the cursor
2. Clearing the contents of the screen
3. Placing the cursor at the appropriate position on the screen
4. Receiving a key from the keyboard
5. Formatting a floppy
6. Hiding a file from the directory of a disk
7. Sending the output to the printer.
8. Interacting with the mouse etc.

Syntax for declaring a structure


struct <tag_name>
{
Structure member 1;
Structure member 2;
-----------
Structure member N;
};
eg:
struct student
{
int rno, marks;

Page 30
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

char name[15];
};
Here, tag_name is the name of the structure that we create. Structure members are the variable
declarations which are grouped as a single unit in a structure.
Accessing the structure members:- To access the structure elements we have to declare a variable
to the structure. Using this variable and the dot operator, we can access the values in them. We
can declare a structure variable inside the main () or during the structure declaration. The
following is the syntax to declare a variable to the structure.
struct <structure name> <variable name>;
eg: struct student st;
To access the structure members we use dot (.) operator along with the structure variable as
shown below.
<structure variable> . <structure member>
Eg:
st.rno
st.name
st.marks
Assigning values to structure members:- We can assign values to structure members through
structure variable. We cannot initialize the structure members inside the structure.
1) We can assign the values to the structure members while declaring the structure variable
as shown below. While assigning, give the values in the order which we declare the structure
members :
Eg: struct student st={10,’kiran’,345};
2) We can also assign the values after declaring the structure variable as shown below.
Eg:
struct student st;
st.rno=20;
strcpy(st.name, “laxmi”);
st.marks=545;

3) We can also assign the values to structure members while executing the program using
scanf().
Eg: /*program using structure to store student details*/
#include <stdio.h>
#incldue <conio.h>
struct student
{
int rno, marks;
char name[10];
};
main()
{

Page 31
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

struct student st; clrscr();


printf(“\nEnter the rno :”);
scanf(“%d“, &st.rno);
printf(“\nEnter the name :”);
scanf(“%s”,st.name);
printf(“\nEnter the marks:”);
scanf(“%d”,&st.marks);
printf(“\nStudent details are :”);
printf(“\nRollno.: %d \nName : %s \nMarks: %d”,st.rno,st.name,st.marks);
getch();
}
Arrays within structures:- We can also declare an array as a structure member.
Eg: /*program to accept 3 subjects marks and display the total of a student*/
#include<stdio.h>
#include<conio.h>
struct student
{
int rno;
char name[10];
int marks[3], total;
}st;
main()
{
int i;
clrscr();
st.total=0;
printf(“\nEnter the rno: “);
scanf(“%d”,&st.rno);
printf(“\nEnter the name :”);
scanf(“%s”,st.name);
printf(“\nEnter the marks:”);
for(i=0;i<3;i++)
{
printf(“\nSubject %d :”,i+1);
scanf(“%d”,&st.marks[i]);
st.total=st.total+st.marks[i]);
}
printf(“\nRollno: %d \nName: %s \nTotal: %d”,st.rno, st.name, st.total);
getch();
}
Arrays of structures :- Using a structure variable we can assign and retrieve only one record
information only. To accept details of more than one person we have to declare so many
variables. Instead of declaring so many variables we can use an array for the structure. Each and
every record is identified by the index. The following example shows an array to a structure.
Eg: struct student s[25];

Page 32
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

Here, s is the name of the structure which can hold 25 student records. Every record is identified
by its index as s[0], s[1], s[2],………,s[24].
/*Program using array of structures*/
#include<stdio.h>
#include<conio.h>
struct student
{
int rno, marks[3], total;
char name[10];
};
main()
{
int i, j, n;
struct student st[25]; clrscr();
printf(“\nEnter the no. of records :”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\nEnter the rno and name of the student : “);
scanf(“%d%s”,&st[i].rno, st[i].name);
printf(“\nEnter the marks:”);
st[i].total=0;
for(j=0;j<3;j++)
{
printf(“\nSubject %d :”,j+1);
scanf(“%d”,&st[i].marks[j]);
st[i].total=st[i].total+st[i].marks[j];
}
}
printf(“\nStudent details are :”);
printf(“\nRoll\tName\t\tTotal”);
for(i=0;i<n;i++)
printf(“\n%d\t%s\t\t%d”,s[i].rno,s[i].name,s[i].total);
}

Functions using structures:- A structure variable can also be passed as a parameter to the
function. All the members of that structure can now be accessed in the function. We can also
return a structure variable from the function to the calling program. We can also pass individual
members of the structure as parameters.

/*program passing structure as parameter to a function*/


#include<stdio.h>
#include<conio.h>
struct employee
{

Page 33
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

int eno, salary;


char ename[15];
};
void display(struct employee);
main()
{
struct employee e;
printf(“\nEnter the emp number, name and salary of a person”);
scanf(“%d%s%d”, &e.eno, e.ename, & e.salary);
display(e);
getch();
}
void display(struct employee em)
{
printf(“\nEmployee details :\n”);
printf(“\nEno : %d”,em.eno);
printf(“\nEname : %s”,em.ename);
printf(“\nEmp Salary : %d”,em.salary);
}

Pointers using structures:- We can also store the address of a structure variable to a pointer. To
access the structure members using pointer, we can use the arrow ( ->) operator or the dot (.)
operator.
/* pointers using structures */
#include<stdio.h>
#include<conio.h>
struct student
{
int no, marks;
char name[10];
};
main()
{
struct student st, *p;
clrscr();
p=&st;
printf(“\nEnter the no, name and marks:”);
scanf(“%d%s%d”,&st.no,st.name,&st.marks);
printf(“\nValues accepted are :”);
printf(“\n Roll no: %d”,p->no);
printf(“\n Name : %s”, p->name);
printf(“\n Marks : %d”,(*p).marks);
getch();
}

Page 34
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

Nested structures:- Defining a structure inside another structure definition is known as nested
structure. To access the values of the nested structure, we have to declare variables to outer as
well as inner structure.
Syntax:
struct structure1
{
Structure member 1;
Structure member 2 ;
struct structure2
{
Structure member 1;
Structure member 2 ;
--
Structure member n;
}<structure variable>;
Structure member n;
};

eg: /*program using nested structures*/


#include<stdio.h>
#include<conio.h>
struct employee
{
int eno, salary;
char ename[15];
struct address
{
char hno[10];
char street[15];
char city[15];
}ad;
};
main()
{
struct employee e;
clrscr();
printf(“\nEnter the empno, ename and salary :”);
scanf(“%d%s%d”,&e.eno,e.ename,&e.salary);
printf(“\nEnter the address :”);
scanf(“%s%s%s”,e.ad.hno,e.ad.street,e.ad.city);
printf(“\nThe employee details are \n”);
printf(“\nEmp.No: %d”,e.eno);
printf(“\nEname : %s\nSalary : %d”,e.ename, e.salary);
printf(“\nH.no: %s\nStreet : %s\nCity : %s”,e.ad.hno,e.ad.street,e.ad.city);
getch();

Page 35
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

}
We can also call a structure as a nested structure where another structure variable is used
as a member in the structure.
Syntax:
struct structure1
{
Structure member 1;
Structure member 2 ;
--
Structure member n;
}<structure variable>;

struct structure 2
{
Structure member 1;
Structure member 2 ;
Struct <strcuture1> <variable>;
Structure member n;
};
eg: /*program using nested structures*/
#include<stdio.h>
#include<conio.h>
struct address
{
char hno[10];
char street[15];
char city[15];
};
struct employee
{
int eno, salary;
char ename[15];
struct address ad;
};
main()
{
struct employee e;
clrscr();
printf(“\nEnter the empno, ename and salary :”);
scanf(“%d%s%d”,&e.eno,e.ename,&e.salary);
printf(“\nEnter the address :”);
scanf(“%s%s%s”,e.ad.hno,e.ad.street,e.ad.city);
printf(“\nThe employee details are \n”);
printf(“\nEmp.No: %d”,e.eno);
printf(“\nEname : %s\nSalary : %d”,e.ename, e.salary);
printf(“\nH.no: %s\nStreet : %s\nCity : %s”,e.ad.hno,e.ad.street,e.ad.city);
getch();

Page 36
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

UNIONS
Unions are derived data types. The unions are useful to interact with the hardware of the system.
A union is declared and used in the same way that a structure is. A union differs from a structure
in that only one of its members can be used at a time. The basis is that all members of a union
occupy the same memory area. That it, they are laid on top of one another. While declaring a
union, we use the keyword ‘union’ instead of struct.
Syntax :
union <tag name or union name>
{
member 1;
member 2;
-----------
member n;
}[<union variable>];
Unlike a structure that would hold many values, the union can hold only one value at a time. This
is shown in the program below.
/*program showing the use of unions*/
#include<stdio.h>
#include<conio.h>
union stud
{
int rno, total;
char name[15];
};
main()
{
union stud u; clrscr();
printf(“\nEnter rno, name and total”);
scanf(“%d%s%d”,&u.rno,u.name, &u.total);
printf(“\nRno : %d \n Name : %s \n Total : %d”,u.rno,u.name, u.total);
getch();
}

Memory allocation for a union:- Another important difference between a union and structure is
in its memory allocation. A structure is allocated memory which is equal to the sum of the size of
its structure members, while a union is allocated memory which is equal to the maximum size of
its member.

/*program showing the memory allocated for a structure and an union*/


#include<stdio.h>
#include<conio.h>
struct student
{

Page 37
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

int rno, total;


char name[15];
};
union stud
{
int rno, total;
char name[15];
};
main()
{
struct student s;
union stud u; clrscr();
printf(“\nMemory allocated for structure is %d”, sizeof(s));
printf(“\nMemory allocated for Union is %d”, sizeof(u);
getch();
}

FILES

We use input and output statements to read data from standard input devices and display
information on the standard output devices. This kind of information is present only a along as
the program is running on the computer. Once we switch to another program, this data gets lost.
Real life applications require that the data be written or read from secondary storage devices.
These devices are also called as auxiliary storage devices such as hard disk, compact disk (CD),
floppy and magnetic tapes. The data is present on these devices in the form of data files. Once
data is available on these devices, we can access and change it whenever required. We have a
number of file functions available.
In C, there are two types of streams. They are text streams and binary streams. A text file
is a file in which data are stored using only characters. When data are input from a text file, they
are read as a sequence of characters and converted into correct internal formats before being
stored in memory. We read and write text files using the input/output functions that connect the
characters to datatypes.
A binary file is a collection of data stored in the internal format of the computer.
Unlike text files, the data do not need to be reformatted as they are read and written. Binary files
are read and written using binary streams known as block input / output functions.
Defining and opening a file:- To reference a data file in C, we need to declare a pointer variable
of type FILE, which is nothing but a stream pointer. It is a predefined structure. The general
format for declaring variable of this type is as follows:
FILE * <variable-name>;
FILE is a special type of data structure contained in the standard header file stdio.h that contains
information about the current status of the file. The variable-name refers to the name of the
pointer variable.

Page 38
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

fopen():- To open a file in C, we use the function fopen(). It takes two parameters: filename and
access mode. It returns a pointer to the file, if the operation is successful, otherwise file cannot be
opened and fopen() returns a NULL.
Syntax:-
fopen(“filename”, “access mode”);
filename is the name of the file that we want to open and access mode indicates the type of
operations to be performed on a file. The following table shows the complete set of options for
accessing a file
r  read mode opens the file for reading if it exists
w  write mode creates a file if it is not present otherwise it overwrites the file
contents.
a  append mode adds the contents at the end of the file. It creates a new file if
it is not present.
r+  read and write
w+  write and read
a+  read and append
The address of the file structure that contains the file information is returned by fopen(). The
actual contents of FILE are hidden from our view and the address of the file structure can be
used to read or write the file. The following are the other functions used in files.

1) fclose():- This function is used to close the opened file. It takes only one parameter and it is
the file pointer.
Syntax:- fclose(file pointer);
Eg: fclose(fp);
2) fgetc():- This function is used to get a character from the file. It takes one parameter and it is
the file pointer.
Syntax: character variable=fgetc(fp);
Eg: ch=fgetc(fp);
3) fputc():- This is used to put a character into the file. It takes 2 parameters. One is the
character and the other is the file pointer.
Syntax:- fputc(character, file pointer);
Eg: fputc(ch,fp);
4) getw():- It is used to get an integer value from the file. It takes only one parameter and it is
the file pointer.
5) putw():-It is used to store the integer value into the file. When you give any digit number, it
is taken as a single value and it is stored in the value. Where as in case of fgetc, that same
number is stored as different digits.

Eg1: /*to read and write the information of a file*/


#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch; clrscr();
fp=fopen(“hello.txt”, “w”);
while((ch=getchar())!=EOF)

Page 39
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

fputc(ch, fp);
fclose(fp);
fopen(“hello.txt”,”r”);
while((ch=fgetc(fp))!=EOF)
printf(“%c”, ch);
fclose(fp);
getch();
}
You can avoid a file being overwritten by checking whether a file pointer is NULL or not. You
can also accept the file name from the keyboard during run time also. These 2 possibilities are
shown in the example below.

Eg2: /*to check a file for existence */


#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch, name[10] ; clrscr();
printf(“\nEnter a file name :”);
scanf(“%s”,name);
fp=fopen(name,”w”);
if(fp!=NULL)
{
while((ch=getchar())!=EOF)
fputc(ch, fp);
}
else
printf(“\nFile is already present “);
fclose(fp);
getch();
}

Eg: /*program using putw() and getw() */


#include<stdio.h>
main()
{
FILE *p;
int n,i;
p=fopen(“numbers.txt","w");
for(i=1;i<=10;i++)
{
printf(“\nEnter a number”);
scanf("%d",&n);
putw(n,p);
}
fclose(p);

Page 40
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

p=fopen("numbers.txt","r");
while((n=getw(p))!=EOF)
printf("\n%d",n);
fclose(p);
getch();
}

Using the above functions, we can add the text to the file. If you want to store data in the form
of records, then we have other functions.
fscanf():- This function is used to retrieve the whole record data from file at a time. It takes 3
parameters. One is the file pointer, second the “control string” and the third the variables.
Syntax:- fscanf(file pointer, “control string”, arguments);
fprintf():- This function is used to store the whole record information into a file at a time.
Syntax :- fprintf(file pointer, “control string”, arguments);

/* to create a file for storing the records */


#include<stdio.h>
#include<conio.h>
struct student
{
int no,marks;
char name[10];
};
main()
{
FILE *fp,*fr;
char ch='y'; struct student s;int n;
clrscr();
fp=fopen("stud","w");
while(ch= ='y'|| ch= ='Y')
{
scanf("%d%s%d",&s.no,s.name,&s.marks);
fprintf(fp,"\n%d %s %d", s.no,s.name,s.marks);
printf("\nDo you want to continue?");
ch=getche();
}
fclose(fp);
getch();
}

/*removing the required record from the file*/


#include<stdio.h>
#include<conio.h>
struct student
{
int no,marks;
char name[10];

Page 41
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

};

main()
{
FILE *fp; char ch='y';
struct student s;
int n; clrscr();
fp=fopen("stud","r+");
fr=fopen("stud1","w");
printf("\nEnter rno you want:");
scanf("%d",&n);
while(!feof(fp))
{
fscanf(fp,"%d%s%d",&s.no,s.name,&s.marks);
if(s.no!=n)
fprintf(fr,"\n%d %s %d", s.no,s.name,s.marks);
}
fclose(fp);
fclose(fr);
remove("stud");
rename("stud1","stud");
getch();
}

/*creating a file and count no. of lines, words space */


#include <stdio.h>
#include<conio.h>
main()
{
int cw=0,cl=0,cws=0;
char c,name[10];
FILE *fp; clrscr();
printf("\nEnter file name");
scanf("%s",name);
fp=fopen(name,"w");
while((c=getchar())!=EOF)
putc(c,fp);
fclose(fp);
fp=fopen(name,"r");
while((c=getc(fp))!=EOF)
{
if(c=='\n')
cl++;
if(c==' ')
{

Page 42
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

cw++;
cws++;
}
}
printf("\n the num of words are %d",cw); printf("\nthe num of lines are %d",cl);
printf("\n the num of white spaces are %d",cws);
fclose(fp);
getch();
}

Random Access files:-


ftell():- It is used to show the position of the file pointer in the file. It gives the no. of bytes
occupied till the file pointer position. It takes one parameter and it is the file pointer name.
Syntax: ftell(file pointer);
frewind():- It is used to position the file pointer at the starting of the file. It takes one parameter
and it is the file pointer.
Syntax:- frewind (file pointer);
fseek():-It is used to position the file pointer at the desired location in the file and to retrieve the
required number of characters from the file.
Syntax:- fseek(file pointer, offset, position)
Offset is the number of characters we want to move the file pointer from the required position.
Position indicates the position of the file pointer in the file from where the file pointer characters
has to be moved. Either 0,1 or 2 are used to indicate the position. ‘0’ indicates starting of the
file, 1 indicates the current position and 2 indicate from the end of file. When we are using 2, we
have to specify the offset in negative number. It means it will move the file pointer from the end
of file in reverse direction(from last).
/* to create a file for reading, writing and appending */
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp; char ch ; clrscr();
fp=fopen(“hello.txt”,”a+”);
while((ch=getchar())!=EOF)
fputc(ch, fp);
frewind(fp);
while((ch=fgetc(fp))!=EOF)
printf(“%c - %u”, ch, ftell(fp));
fclose(fp);
getch(); }

Eg2: /* usage of fseek */


#include<stdio.h>
#include<conio.h>
main(){
FILE *fp; char ch ; clrscr();
fp=fopen(“hello.txt”,”r”);

Page 43
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

fseek(fp,0,5);
ch=fgetc(fp);
printf(“%c”, ch);
fseek(fp,-3,1);
ch=fgetc(fp);
printf(“%c”, ch);
fseek(fp,-6,2);
ch=fgetc(fp);
printf(“%c”, ch);
fclose(fp);
getch();
}

SEARCHING AND SORTING


The related activities of sorting and searching are very important to many computer applications.
The sorting operation is most often performed in business data processing applications. This
operation has also become increasingly important in many scientific applications. Sorting alone
has been said to account for more than 30% of all computer time spent. Sorting provides us
either a means of organizing information to facilitate the fast retrieval of specific data. Searching
methods are designed to take advantage of the organization of information and thereby reduce
the amount of effort to either locate a particular item or to establish that it is not present in a data
set.
Searching:- Searching is the process used to find the location of a target among a list of objects.
In the case of an array, searching means that given a value, we want to find the location (index)
of the first element in the array that contains that value. In C language, there are two basic
searches for arrays. They are sequential search (linear search) and binary search.
Linear Search:- The simplest form of search is the linear search (sequential search). This
technique is meant for searching a particular item in an unsorted data set in a sequential manner
until the desired data item is found. Linear search is easy to write and efficient for short lists, but
a failure for long ones. To find any element in a long array (list), there are far more efficient
methods, provided that the array is sorted. An algorithm for linear search is as follows. This
search is applicable to a data set organized either as an array or as a linked list. Assume a[i] is an
integer array of n elements and key is a number to be searched in the array. Found is an integer
variable which is initially set to zero (no match) otherwise match found.
1. Initialize found =0
2. Scan the elements for array, a[i] for i=0 to n-1 and repeat step 3 until i<n
3. If a[i]=key, then a match is found: set found=1 and go to step 4
4. Check if found=0 and display match not found.
The performance of linear search methods can be measured by counting the number of
comparisons taken to find the key in the array of size n, that is, O(n).

/*program using linear search*/


#include <stdio.h>
#include <conio.h>
main()

Page 44
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

{
int a[25],n,i,key, found=0;
clrscr();
printf(“\nEnter the number of values “);
scanf(“%d”,&n);
printf(“\nEnter the values”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\nEnter the value to search”);
scanf(“%d”,&key);
for(i=0;i<n;i++)
{
if(a[i]==key)
{
found=1;
printf(“\nValue found at %d index”,i);
break;
}
}
if( found==0)
printf(“\nValue not found”);
getch();
}

Binary Search:- In this method the list should be a sorted list. This is a simple method of
accessing a particular item from a sorted list. A search for a particular item with a certain key
value resembles the search for a name in telephone directory. The approximate middle term of
the data set is located and its key value is examined. If its value is too high then the key of the
middle element of the first half of the set is examined and procedure is repeated on the first half
until the required item is found. If the value is too low then the key of the middle entry of the
second half of the data set is tried and the procedure is repeated on the second half. This process
continues until the desired key is found or search interval become empty. An algorithm for
binary search is as follows.
We assume that a[i] is an ordered (sorted in ascending order) integer array of n elements
and key is an integer number to be searched in the array. The found is an integer variable, which
is initially set to 0 (unsuccessful) otherwise successful. The variables lb, mid and ub denote the
lower, middle and upper limits of the search interval, respectively. The function returns 1, if
search is successful, otherwise it returns 0.
1. Initialize lb=0, ub=n-1 and found=0
2. Repeat steps 3 and 4 while lb<=ub
3. Obtain the index of midpoint of interval: mid=(lb+ub)/2
4. If key<a[mid], then ub=mid-1
Else if key>a[mid], then lb=mid+1
Else found=1, display the index of found value and go to step 5
5. if value in found=0, then display the message value not found.

Page 45
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

The complexity is measured by the number f(n) of comparisons to find key in the array of size n.
at each step, the size is reduced to half. Hence, we need at most f(n) comparisons to locate key
where 2f(n) >n or f(n) = log2n+1. That is, the worst case running time is approximately equal to
log2n. The running time for the average case is also approximately equal to log2n.

/*program using binary search*/


#include <stdio.h>
#include <conio.h>
main()
{
int a[25],n,i,key,lb,ub,mid,found=0;
clrscr();
printf("\nEnter the number of values ");
scanf("%d",&n);
printf("\nEnter the values");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the value to search");
scanf("%d",&key);
lb=0;
ub=n-1;
while(lb<=ub)
{
mid=(lb+ub)/2;
if(key<a[mid])
ub=mid-1;
else if(key>a[mid])
lb=mid+1;
else
{
found=1;
printf("\nValue found at %d index",mid);
break;
}
}
if( found==0)
printf("\nValue not found");
getch();
}

Sorting:- One of the most common applications in computer science is sorting. This is the
process through which data are arranged according to their values. If the data are not ordered, we
would spend hours trying to find a single piece of information. C provides a number of sorting
techniques which are listed below.
1. Bubble sort
2. Selection sort

Page 46
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

3. Insertion sort
4. Quick Sort
5. Merge sort
Bubble Sort:- This is the familiar sorting procedure. It is also known as exchange sort. This is
widely known among the beginners but it is probably the least efficient.
We consider an integer array, a i of size, n. In this approach, at most n-1 passes are
required. During the first pass, a0 and a1 are compared, and if they are out of order, then a 0 and a1
are interchanged. This process is repeated for a 1 and a2, a2 and a3, and so on. This method will
cause small elements to move or bubble up. After the first pass, the array with the largest
element will be in the (n-1)th position (last location). On each successive pass, the array with the
next largest element will be placed in position n-2, n-3,…1, respectively, thereby resulting in a
sorted array. The following table shows the tracing of bubble sort for the array
[25,40,32,35,10,72,60,62].
Pass 0 1 2 3 4 5 6 7 Process
Original
- 25 40 32 35 10 72 60 62
array
40, 32
1 25 32 40 35 10 72 60 62
interchanged
40, 35
1 25 32 35 40 10 72 60 62
interchanged
40, 10
1 25 32 35 10 40 72 60 62
interchanged
72, 60
1 25 32 35 10 40 60 72 62
interchanged
72, 62
1 25 32 35 10 40 60 62 72
interchanged
35, 10
2 25 32 10 35 40 60 62 72
interchanged
32, 10
3 25 10 32 35 40 60 62 72
interchanged
25, 10
4 10 25 32 35 40 60 62 72
interchanged

Eg: /*Program using bubble sort*/


#include<stdio.h>
#include<conio.h>
main()
{
int n, i , j, temp, a[20];
clrscr();
printf(“\n Enter the no. of elements :”);
scanf(“%d”,&n);
printf(“\nEnter the values :”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);

Page 47
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf(“\nSorted values are :”);

for(i=0;i<n;i++)
printf(“\n%d”,a[i]);
getch();
}

DATA STRUCTURES

Computer programs are made up of algorithms and data structures. An algorithm provides the
step-by-step instructions of what a program will do. The algorithms work with data and
variables. A single variable represents one memory location that can hold a variable of a simple
type such as integer or character. A data structure is a group of memory locations used to
represent the information used by the algorithm. In computer science, a data structure is a way of
storing data in a computer so that it can be used efficiently. Often a carefully chosen data
structure will allow the most efficient algorithm to be used. The choice of the data structure often
begins from the choice of an abstract data type. A well-designed data structure allows a variety
of critical operations to be performed, using as few resources, both execution time and memory
space, as possible. Data structures are implemented using the data types, references and
operations on them provided by a programming language. Data structures are of two types. They
are (1) Linear Data structures and (2) Non-Linear Data structures
1) Linear Data structures:- In this type of data structure, arranging and retrieving of data will be
done in sequential order. Eg: Stacks, Queues and Linked Lists
2) Non-Linear Data structures:- Here arranging and retrieving of data is done in random or non-
sequential order. Eg: Trees and Graphs

Stacks

A stack is a linear data structure that can be accessed only at one of its end for storing and
retrieving data. Such a stack resembles a stack of trays in a cafeteria. New trays are put on the
top of the stack and taken off the top. The last tray put on the stack is the first tray removed from
the stack, for this reason, a stack is called an LIFO (Last In First Out) structure. A tray can be
taken only if there are trays of the stack and a tray can be added to the stack only if there is
enough room i.e., if the stack is not too high. A stack can be represented using an array or linked

Page 48
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

list. The array representation technique is very simple. The major drawback of this approach is
that the maximum possible number of elements in the stack required is to be predefined. In the
linked list approach, no memory is pre-allocated to the stack members. Instead, memory is
allocated as and when required and released when it is no longer required. Thus, this involves
dynamic memory allocation.
The two major operations performed on a stack are storing an element (push operation)
and removing an element (pop operation) and a variable ‘top’ is used to show the position of the
last element in the stack.
Push Operation:- It is a user defined function which is used to insert an element into a stack.
Pop operation :- It is a user defined function which is used to remove an element from the stack.

Array implementation of a Stack:- A stack is a linear list where insertions and deletions are
performed at only one end usually at the top end. A stack is represented as follows.

Associated with the stack, there is a variable called ‘top’. It contains the position of the last
element inserted in the stack. Initially when the stack is empty, top= -1. We can perform push
and pop operations as described below.
Push():- In order to insert an element into the stack, first it is checked whether stack is full or not.
If the stack is full i.e., top = size-1, it means stack overflow and insertion is not possible.
Otherwise, we increment the ‘top’ by 1 and insert new element in that location.
Pop():- To pop or delete an element from the stack, it is checked whether, stack is empty. If the
stack is empty i.e., top = -1, it means stack under flow and we cannot delete any element from
the stack, since we do not have anything in it.

/*program showing array implementation of stack*/


#include <stdio.h>
#include <conio.h>
#define SIZE 5
void push(int);

Page 49
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

void pop(void);
void display(void);
int stack[SIZE],top=-1;
main()
{
int n,opt;
char ch='y';
clrscr();
while(ch=='y'||ch=='Y')
{
printf("\n1. Push\n2.Pop\nEnter your option");
scanf("%d",&opt);
switch (opt)
{
case 1:
printf("\nEnter a number");
scanf("%d",&n);
push(n);
display();
break;
case 2:
pop();
display();
break;
default:
printf("\nInvalid choice, try again");
}
printf("\nWant to continue?");
ch=getche();
}
getch();
}
void push(int n)
{
if(top==SIZE-1)
printf("\nStack is full");
else
{
top++;
stack[top]=n;
printf("\n%d is inserted",n);
}
}
void pop(void)
{
int n;
if(top==-1)

Page 50
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

printf("\nStack is empty");
else
{
n=stack[top];
top--;
printf("\n%d is deleted",n);
}
}
void display(void)
{
int i;
printf("\n");
for(i=0;i<=top;i++)
printf(" %d",stack[i]);
}

Applications of stacks:- A stack can be used for the following purposes:


1) It can be used in function calls. For example, suppose that function ‘a’ calls function ‘b’
and passes two variables, x and y to ‘b’. Then the function ‘a’ can store these two
variables on the stack, from where the function ‘b’ can retrieve and use them.
2) A stack can be used to implement a calculator by storing the operands and the operators
on the stack and using them as and when required.
3) A stack is useful in writing recursive calls.
4) A stack is useful for the compiler/operating system to store local variables used inside a
function block, so that they can be discarded once the control comes out of the function
block.

Queues
Queues:-- It is a collection of items where a item can be inserted at rear end and item can be
removed from front end. It works on a concept called FIFO (First In First Out) i.e., the element
which is inserted first can be deleted first. Before storing element into a queue, increment rear
value and store. While deleting element delete element from the front and increment front value.
A queue is linear list where insertions are performed from rear end and deletion is
performed form front end. Associated with queue, there are two variables ‘f’ and ‘r’ (front and
rear). Initially when the queue is empty ‘f’=-1, ‘r’=-1. After first element gets inserted ‘f’ always
points to the front element (first element) in the queue and ‘r’ always points to rear element in
the queue (i.e, last element). We can perform two operations on queues: insertion and deletion.
i) Insertion: In order to insert an element, test whether ‘r’=size-1 or not. If ‘r’=size -1, queue is
full, insertion is not possible. Otherwise, we increment ‘r’ by 1 and insert new element at q[r].
Thus insertion is nothing but incrementing ‘r’ by 1. Queue insertion is same as stack insertion.
ii) Deletion:- In order to delete an element, test whether f>r. If so, queue is empty, deletion not
possible. If queue contains one element, delete that element. If queue contains more than one
element then delete the front element by incrementing ‘f’ by 1. Thus deletion is nothing but
incrementing ‘f’ by 1. Queue deletion is not same as stack deletion.

Page 51
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

Since deletion is performed from opposite end, the first element inserted in the queue is
the first element to be deleted. Here queue is also called as FIFO list. The following example
illustrates this.

We cannot insert new value, since r=3 i.e., size-1. Although locations are empty, insertion is not
possible. Because, they are empty on the front side and insertion is from rear side. This is a
disadvantage in linear queue. To overcome this, we use circular queue.

/*program showing array implementation of Queue*/


#include <stdio.h>
#include <conio.h>
#define SIZE 5
void insert(int);
void delete(void);
void display(void);
int queue[SIZE],front=-1,rear=-1;
main()
{
int n,opt;
char ch='y';
clrscr();

Page 52
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

while(ch= ='y'||ch= ='Y')


{
printf("\n1.Insert\n2.Delete\nEnter your option");
scanf("%d",&opt);
switch (opt)
{
case 1:
printf("\nEnter a number");
scanf("%d",&n);
insert(n);
display();
break;
case 2:
delete();
display();
break;
default:
printf("\nInvalid choice, try again");
}
printf("\nWant to continue?");
ch=getche();
}
getch();
}
void insert(int n)
{
if(rear==SIZE-1)
printf("\nQueue is full");
else
{
rear++;
queue[rear]=n;
if(front==-1)
front=0;
printf("\n%d is inserted",n);
}
}
void delete(void)
{
int n;
if(front==-1 && rear==-1 || front>rear)
printf("\nQueue is empty");
else
{
n=queue[front];
front++;
printf("\n%d is deleted",n);

Page 53
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

}
}

void display(void)
{
int i;
printf("\n");
for(i=front;i<=rear;i++)
printf(" %d",queue[i]);
}
Linked Lists

A list refers to a set of items organized sequentially. An array is an example of list. In an array,
the sequential organization is provided implicitly by its index. We use index for accessing and
manipulation of array elements. One major problem with the arrays is that the size of an array
must be specified precisely at the beginning. This may be a difficult task in many practical
applications. A completely different way to represent a list is to make each item in the list part
of a structure that also contains a link to the structure containing the next item as shown below.
This type of list is called a linked list because it is a list whose order is given by links from one
item to the next.

Each structure of the list is called a node and consists of two fields, one containing the item and
the other containing the address of the next item (a pointer to the next item) in the list. A linked
list is therefore a collection of structures ordered not by their physical placement in memory (like
an array) but by logical links that are stored as part of the data in the structure itself. The link is
in the form of a pointer to another structure of the same type. Such a structure is known as a self-
referential structure and is represented as follows:
struct node
{
int item;
struct node *next;
};
The first member is an integer item for storing integer values and the second is a pointer that
stores the address of the next node.
Types of Linked lists:-The following are the different types of linked lists
1) Single linked lists

Page 54
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

2) Double linked lists


3) Circular linked lists
Advantages of Linked lists:- The following are the advantages of linked lists.
1) They are dynamic data structure and so they can grow or shrink in size during the
execution of a program.
2) It does not wastes space as the memory is allocated at and when required only.
3) They provide flexibility in allowing the items to be rearranged efficiently. It is easier to
insert or delete items by rearranging the links.
Disadvantage of linked lists- The major limitation of linked lists is that the access to any
arbitrary item is little cumbersome and time consuming, whenever, we deal with a fixed length
list, it would be better to use an array rather than a linked list. We must also note that a linked list
will use more storage than an array with the same number of items. This is because each item has
an additional link field.

Single Linked List


In a single linked list, each node contains the item and a pointer to the next node. The last node
contains the item and since it is the last node, it will not point to any other node and so the value
in the pointer will be NULL. The following figure shows the representation of single linked list.

/*program using single linked list*/


#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct node
{
int data;
struct node *link;
};
struct node *create(struct node *), *delete (struct node *),*add(struct node *);
void display(struct node *);
main()
{
int opt,no;
char ch='y';
struct node *start=NULL;
clrscr();
while(ch=='y' || ch=='Y')
{

Page 55
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

printf("\n1.Create \n2.Display \n3.Add \n4.Delete \nEnter your choice");


scanf("%d",&opt);
switch(opt)
{
case 1:
start=create(start);
break;
case 2:
display(start);
break;
case 3:
start=add(start);
break;
case 4:
start=delete(start);
break;
default:
printf("\nWrong choice");
}
printf("\n Do you want to continue main menu?");
ch=getche();
}
getch();
}
struct node *create(struct node *start)
{
char ch='y';
struct node *temp,*new;
start=(struct node *) malloc (sizeof(struct node *));
printf("\nEnter any number");
scanf("%d",&start->data);
temp=start;
while(ch=='y' || ch=='Y')
{
new = (struct node *) malloc(sizeof(struct node *));
printf("\nEnter any number");
scanf("%d",&new->data);
temp->link=new;
temp=new;
printf("\nDo you want to continue insert?");
ch=getche();
}
temp->link=NULL;
return start;
}
void display(struct node *start)
{

Page 56
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

struct node *i;


for(i=start;i->link!=NULL;i=i->link)
printf("%d->",i->data);
if(i!=NULL)
printf("%d->",i->data);
printf("NULL");
}
struct node *add(struct node *start)
{
struct node *i, *new, *x;
int c, no;
char ch='y';
while(ch=='y' || ch=='Y')
{
new = (struct node *) malloc(sizeof(struct node *));
printf("\nEnter any number");
scanf("%d",&new->data);
printf("\n1.First\n2.Last\n3.Middle\nEnter position to insert");
scanf("%d",&c);
switch(c)
{
case 1:
new->link=start;
start=new;
break;
case 2:
for(i=start;i->link!=NULL;i=i->link);
i->link=new;
new->link=NULL;
break;
case 3:
printf("\nEnter the value in the list where new value to be inserted");
scanf("%d",&no);
for(i=start;i->data!=no;i=i->link)
x=i;
x->link=new;
new->link=i;
break;
}
printf("\nDo you want to continue inserting?");
ch=getche();
}
return start;
}
struct node *delete(struct node *start)
{
int ch,no;

Page 57
V. Anitha PSCP Notes (CO3 & CO4) KL University, Hyd.

struct node *temp,*i,*x;


temp=start;
printf("\n1.First\n2.Last\n3.Middle\nEnter the position to delete");
scanf("%d",&ch);
switch(ch)
{
case 1:
start=temp->link;
break;
case 2:
for(i=temp;i->link!=NULL;i=i->link)
x=i;
if(i==start)
{
free(start);
start=NULL;
}
else
x->link=NULL;
break;
case 3:
printf("\nEnter the value to remove");
scanf("%d",&no);
for(i=start;i->data!=no;i=i->link)
x=i;
if(i==start && i->link ==NULL)
{
free(start);
start=NULL;
}
else if(i==start)
start=start->link;
else
x->link=i->link;
break;
}
return start;
}

Page 58

You might also like