Solved Question Papers: C Programming and Data Structures May/June 2007 SET-1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Appendix

+
Solved Question Papers
C Programming and Data Structures
May/June 2007

SET- 1

1. (a) Write a program to determine and print the sum of the following harmonic series
for a given value of n:1+1/2+1/3+1/4+1/5………+1/n.
#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
float sum=0;
clrscr();
printf(“enter the value of n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
sum+=1/(float)i;
printf(“ the value of the given series is %f\n”,sum);
getch();
}
(b) What are the logical operators used in C ? Illustrate with examples.
Logical operators used in C language are
&& - logical AND
|| - logical OR
! - logical NOT

Appendix-C.p65 1 7/29/08, 5:21 PM


C.2 Solved Question Papers
Truth table for logical operators:

A B A&&B A||B !A
T T T T F
T F F T F
F T F T T
F F F F T

Logical AND is true only when all the inputs are true and logical OR is true if any one of
the inputs is true. Logical NOT is a unary operator, it is true when input is false and vice-
versa.
Sample program for logical operators:
#include<stdio.h>
main()
{
int a,b,c,nc=0,nw=0;
char ch;
FILE *fptr;
printf(“enter the values of a,b,c\n”);
scanf(“%d%d%d”,&a,&b,&c);
if((a>b)&&(b>c)) /* logical AND */
printf(“a is the largest value”);
fptr=fopen(“input.c”,”r”);
while(!foef(fptr)) /* logical NOT */
{
ch=getc(fptr);
if(ch==’ ‘||ch==’\t’) /* logical OR */
nw++;
else
nc++;
}
fclose(fptr);
printf(”number of words =%d\n”,nw);
printf(”number of characters =%d\n”,nc);
}
getch();
}
2. (a) What is a preprocessor directive?
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 to the preprocessor. The preprocessor direc-
tives are generally initialized at the beginning of the program. It begins with a symbol
#(hash).
Example : #define pi 3.14

Appendix-C.p65 2 7/29/08, 5:21 PM


Solved Question Papers C.3
(b) Distinguish between function and preprocessor directive.

Function Preprocessor Directive


Function is a block of statements enclosed Preprocessor directives are mostly
within braces. single line statements usually used to
define symbolic constants.
Compiler moves to the function where it Compiler replaces the code when it is
is located when a function is invoked. encountered.
Functions can accept and return values Preprocessor can neither accept nor
from and to the calling function. return values.
Example: sum(int a, int b) Example: #define pi 3.14
{ return a+b;}

(c) What is the significance of conditional compilation?


Conditional compilation allows the user to compile the portions of the program based on
certain conditions. The directives used for conditional compilation are #if, #else, #endif,
etc.
The syntax for #if directive is
#ifdef <identifier>
{
statement1;
statement2;
.
.
}
#else
{
statement x;
statement y;
.
.
}
#endif
( d) How is the unedifining of a pre-defined macro done?
A preprocessor directive that is defined using #define can be undefined using #undef direc-
tive.
Syntax : #undef identifier
It is useful when we do not want to allow the use of macros in any portion of the program.
Example:
#include<stdio.h>
#define wait getch()
main()
{
int a;
clrscr();
#undef wait getch()

Appendix-C.p65 3 7/29/08, 5:21 PM


C.4 Solved Question Papers
for(a=1;a<=10;a++)
{
printf(“%d\t”,a);
wait;/* returns an error message since wait is undefined */
}
}
3. (a) What is a pointer? How is a pointer initiated? Give an example.
A pointer is a variable which stores the address of another variable. The syntax for declar-
ing a pointer is data type * pointer_name;
Example:
int *ptr;
char *cptr;
float *p;
Once a pointer variable is declared, it can be assigned the address of a variable using as-
signment statement.
Example: int a, *ptr;
ptr=&a; ‘&’ is called address of operator. ptr is assigned the address of a.
The pointer and variable must be of the same data type.
(b) State whether each of the following statements is true or false. Give reasons.
(i) An integer can be added to a pointer.
True.
Example: ptr=ptr+1; here the pointer is incremented depending on its data type. If it is
an integer then the scale factor is 2 bytes, character 1 byte, and so on.
(ii) A pointer can never be subtracted from another pointer.
False.
Because C supports pointer arithmetic, by which a pointer can be subtracted or added
to another pointer.
(iii) When an array is passed as an argument to a function, a pointer is passed.
True. Because the array name is itself a constant pointer to that array.
(iv) Pointers cannot be used as formal parameters in headers to function
definitions.
False. C supports call by reference in which the formal parameters are pointers.
(c) If m and n have been declared as integers and p1 and p2 as pointers to integers, then
find out the errors, if any, in the following statements.
(i) p1=&m;
The given statement is correct.
(ii) p2 = n;
The given statement is an error as the compiler cannot convert int to int *.
(iii) m=p2-p1;
The given statement is correct as C supports pointer arithmetic.
(iv) *p1=&n;
The given statement is not correct as the compiler cannot convert int* to int.

Appendix-C.p65 4 7/29/08, 5:21 PM


Solved Question Papers C.5
4. (a) What are bit fields? What are its advantages? What is its syntax?
Bit fields are the special features provided in C to change the order of allocation of memory
from bytes to bits. Using bit fields we can specify the exact number of bits required for the
storage of values. The number of bits required for a variable is specified by a non-negative
integer preceded by a colon.
Advantages:
· Changes order of allocation of memory storage.
· Minimizes the memory wastage.
· Memory can be used more effectively and efficiently.
Syntax for using bit fields:
unsigned variable : size;
Example:
unsigned pass:1;
unsigned fail:0;
(b) Write a C program to store the information of vehicles, use bit fields to store the
status information. Assume the vehicle object consists of type, fuel and model mem-
ber fields. Assume appropriate number of bits for each field.
#include<stdio.h>
#include<conio.h>
#define petrol 1
#define diesel 2
#define two_wheeler 3
#define four_wheeler 4
#define old 5
#define new 6

main()
{
struct vehicle
{
unsigned type:3;
unsigned fuel:2;
unsigned model:3;
}v;
v.type=four_wheeler;
v.fuel=diesel;
v.model=new;
printf(“Type of vehicle :%d\n,v.type);
printf(“Fuel :%d\n”);
printf(“Model :%d\n”);
getch();
}
OUTPUT:
Type of vehicle :4
Fuel :2
Model :6

Appendix-C.p65 5 7/29/08, 5:21 PM


C.6 Solved Question Papers
5. Write a C program to read a text file and to count
(a) number of characters
(b) number of words
(c) number of sentences and write in an output file
#include<stdio.h>
#include<conio.h>
main ()
{
FILE *fptr;
int nl=0,nw=0,nc=0;
char ch;
clrscr();
fptr=fopen(“input.c”,”r”);
if (fptr!=NULL)
{
while (!foef(fptr))
{
ch=getc (fptr);
if (ch==’ ‘||ch==’\t’)
nw++;
else if(ch==’\n’)
nl++;
else
nc++;
}
fclose (fptr);
fptr=fopen (“output.c” , ”w”);
fprintf (fptr,”number of lines =%d\n” , nl);
fprintf (fptr,”number of words =%d\n” , nw);
fprintf (fptr,”number of characters =%d\n” , nc);
}
else
printf(“the input file does not exist\n”);
getch();
}
6. Declare a circular queue of integers such that F points to the front and R points to the
rear. Write functions
(a) to insert an element into the queue
(b) to delete an element from the queue
#include<stdio.h>
#define size 20
int cq[size],F=0,R=0,count=0;
main()
{
int a,ch;
clrscr();

Appendix-C.p65 6 7/29/08, 5:21 PM


Solved Question Papers C.7
while(1)
{
printf(“main menu\n”);
printf(“1.insertion\t2.deletion\t3.display\t4.exit\n”);
printf(“enter your choice\n”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“enter the value to be inserted\n”);
scanf(“%d”,&a);
insert(a);
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf(“wrong choice\n”);
}
getch(); }

/* insertion function */
insert(int x)
{
if(F==R&&count==size-1)
{
printf(“circular queue is full\n”);
return;
}
cq[R]=x;
R=(R+1)%size;
}

/* deletion function */
delete()
{
if(F==R&&count==0)
{
printf(“circular queue is empty\n”);
return;
}
printf(“the deleted element is %d\n”,cq[F]);

Appendix-C.p65 7 7/29/08, 5:21 PM


C.8 Solved Question Papers

F=(F+1)%size;
}

/* display function */
display()
{
int i;
if(F==R&&count==0)
{
printf(“circular queue is empty\n”);
return;
}
for(i=F;i!=R;i=(i+1)%size)
printf(“%d”,cq[i]);
}
7. Write a function in C to form a list containing the intersection of the elements of two lists.
Intersection()
{
if(first1==NULL)
{
printf(“list is empty. So no elements in common\n”);
return;
}
else if(first2==NULL)
{
printf(“list is empty. So no elements in common\n”);
return;
}
else
{
ptr1=first1;
ptr2=first2;
while(ptr1->next!=NULL)
{
ptr2=first2;
while(ptr2->next!=NULL)
{
if(ptr1->data==ptr2->data)
{
if(first3==NULL)
{
first3=(node *)malloc(sizeof(node));
first3->data=ptr1->data;
first3->next=NULL;
}
else
{

Appendix-C.p65 8 7/29/08, 5:21 PM


Solved Question Papers C.9

ptr3=first3;
while(ptr3->next!=NULL)
ptr3=ptr3->next;
fresh=(node *)malloc(sizeof(node));
fresh->data=ptr1->data;
ptr3->next=fresh;
fresh->next=NULL;
}/* close of else */
}/* close of if */
}/* close of inner while loop */
}/* close of outer while loop */
}/* close of function intersection */
8. (a) Write a C program to sort given integers using partition exchange sort.
Partition exchange sort is also called quick sort.
/* main function */
#include<stdio.h>
#include<conio.h>
main()
{
int i,n,a[20];
clrscr();
printf(“enter the size of array\n”);
scanf(“%d”,&n);
printf(“enter the elements into array\n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i);
quicksort(a,0,n-1);
prints(“elements after sorting are\n”);
for(i=0;i<n;i++)
printf(“%d\t”,*(a+i));
getch();
}
/* QUICK SORT FUNCTION */
quicksort(int *k,int lb,in tub)
{
int pivot,i,j;
if(lb<ub)
{
i=lb;
j=ub;
pivot=i;
while(i<j)
{
while((*(k+i)<=*(k+pivot))&&(i<ub))
i++;
while(*(k+j)>*(k+pivot))
j– – ;

Appendix-C.p65 9 7/29/08, 5:21 PM


C.10 Solved Question Papers
if(i<j)
swap(k+i,k+j);
}
swap(k+j,k+pivot);
quicksort(k,lb,j-1);
quicksort(k,j+1,ub);
}
return;
}

/* Function for swapping */


swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
(b) Derive the time complexity of the following partition exchange sort.

n
CA(n)=1/n å K = 1 {CA(k–1)+ CA(n–k)}+(n+1)
n
nCA(n)=n(n+1)+ å K = 1 {CA(k–1)+ CA(n–k)}
=n(n+1)+{CA(0)+ CA(n–1)+ CA(1)+ CA(n–2) +……+ CA(n–1) + CA(0)}
nCA(n)=n(n+1)+2{CA(0)+ CA(1)+……..+ CA(n–1)}……(1)
replace n with (n–1)
(n–1)CA(n–1)=n(n–1)+2{CA(0)+ CA(1)+……..+ CA(n–2)}….(2)

Subtract (2) from (1)

nCA(n)– (n–1)CA(n–1)=n2+n–n2+n+2 CA(n–1)


nCA(n)=2n+2 CA(n–1)+ (n–1)CA(n–1)
nCA(n)=2n+ CA(n–1)[n–1+2]
nCA(n)=2n+ CA(n–1)[n+1]
divide on both sides by n(n+1)
(CA(n)/(n+1))=(2/(n+1))+ (CA(n–1)/n)
(CA(n)/(n+1))=(2/(n+1))+ 2/n+(CA(n–2)/(n–1))
=2/(n+1)+2/n+2/(n–1)+2/(n–2)+..+2/4+ CA(2)/3+2/3+ CA(1)/2
n +1
=2å (1/k)
K =3

Appendix-C.p65 10 7/29/08, 5:21 PM


Solved Question Papers C.11

n +1
=2ò 1/kdk
3
n +1
=2[logk] 3
(CA(n)/(n+1))=2[log(n+1)–log3]
CA(n)=2(n+1)log(n+1)–2(n+1)log3
CA(n)=2nlog(n+1)+2 log(n+1)–2nlog3–2 log3
CA(n) »2nlog(n+1)
CA(n)=O(nlogn)

Appendix-C.p65 11 7/29/08, 5:21 PM


C Programming and Data Structures
May/June 2007

SET- 2

1. (a) What is a string constant? How do string constants differ from character constants?
Do string constants represent numerical values?
A string constant is a sequence of characters enclosed in double quotes. The characters
may be letters, numbers, special characters and blank spaces.
Example: “hai” , “1982”, etc;
A character constant is not equivalent to the single character constant. A single character
string constant does not have an equivalent integer whereas a character constant has an
integer value (ASCII value). String constants do not represent equivalent numerical
values.
(b) Summarize the standard escape sequences in C. Describe them.
Black slash characters are also called escape sequences.
Constant Meaning
‘\a’ Audible alert(bell)
‘\b’ Back space
‘\f’ Form feed
‘\n’ New line
‘\r’ Carriage return
‘\t’ Tab space
‘\v’ Vertical tab
‘\” Single quote
‘\”’ Double quote
‘\?’ Question mark
‘\\’ Back slash
‘\0’ Null
(c) What is a variable? How can variables be characterized? Give the rules for variable
declaration.
A variable is a data name that may be used to store a data value. A variable may take
different values at different times during execution. Variables are characterized based on
the value they hold. Depending on that they are classified into int, float, char, double, and so on.
Rules for variable declaration:
· They must begin with a letter. Some compilers permit underscore as the first
character.
· ANSI standard recognizes a length of 31 characters. However, the length should
not be normally more than eight characters.

Appendix-C.p65 12 7/29/08, 5:21 PM


Solved Question Papers C.13

· Uppercase and lowercase are significant. That is, variable SUM is not the same
as sum or Sum.
· The variable name should not be a keyword.
· A blank space is not allowed.
(d) What is the purpose of type declarations? What are the components of type declara-
tion?
Type declarations are used to declare variables, which store the value of any data type. The
syntax for declaring a variable is
data-type v1, v2, v3,……vn;
The components of type declaration are data type and variable list. Data types specify the
type of data that a variable will hold.
Example: int a;
float b;
char ch;
a is a variable that holds an integer-type value. Similarly, b and ch are variables of float
and character data type respectively.
2. (a) Write a program to demonstrate passing an array argument to a function. Con-
sider the problem of finding the largest of N numbers defined in an array.
#include<stdio.h>
main()
{
int a[20],n,i;
clrscr();
printf(“enter the size of an array\n”);
scanf(“%d”,&n);
printf(“enter elements into array\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
largest(a,n);
getch();
}

largest(x,p)
int x[],p;
{
int large,i;
large=x[0];
for(i=0;i<p;i++)
{
if(large<x[i])
large=x[i];
}
printf(“the largest element is %d\n”,large);
}

Appendix-C.p65 13 7/29/08, 5:21 PM


C.14 Solved Question Papers

(b) Write a recursive function power ( base , exponent) that when invoked returns a base
exponent.
#include<stdio.h>
main()
{
int res=0,base,exponent;
clrscr();
printf(“enter the values of base and exponent\n”);
scanf(“%d%d”,&base,&exponent);
res=power(base,exponent);
printf(“the result is %d\n”,res);
getch();
}

int power(b,e)
int b,e;
{
if(e==0)
return 1;
return(b*power(b,e–1));
}
3. (a) What is a pointer? How is a pointer initiated? Give an example.
A pointer is a variable which stores the address of another variable. The syntax for
declaring a pointer is data type * pointer_name;
Example: int *ptr;
char *cptr;
float *p;
Once a pointer variable is declared, it can be assigned the address of a variable using
assignment statement.
Example: int a, *ptr;
ptr=&a; ‘&’ is called address of operator. ptr is assigned the address of a.
The pointer and variable must be of the same data type.
(b) State whether each of the following statements is true or false. Give reasons.
(i) An integer can be added to a pointer.
True.
Example: ptr=ptr+1; here, the pointer is incremented depending on its data type. If it
is an integer then the scale factor is 2 bytes, character 1 byte, and so on.
(ii) A pointer can never be subtracted from another pointer.
False.
Because C supports pointer arithmetic, by which a pointer can be subtracted or
added to another pointer.
(iii) When an array is passed as an argument to a function, a pointer is passed.
True. Because the array name is itself a constant pointer to that array.
(iv) Pointers cannot be used as formal parameters in headers to function defini-
tions.

Appendix-C.p65 14 7/29/08, 5:22 PM


Solved Question Papers C.15

False. C supports call by reference in which the formal parameters are pointers.
(c) If m and n have been declared as integers and p1 and p2 as pointers to inte-
gers, then find out the errors, if any, in the following statements.
(i) p1=&m;
The given statement is correct.
(ii) p2 = n;
The given statement is an error as the compiler cannot convert int to int *.
(iii) m=p2-p1;
The given statement is correct as C supports pointer arithmetic.
(iv) *p1=&n;
The given statement is not correct as the compiler cannot convert int* to int.
4. Write a C program to compute the monthly pay of 100 employees using each employee’s
name and basic pay. The DA is computed as 52% of the basic pay. Gross-salary (Basic-
pay+DA).Print the employee’s name and gross salary.
#include<stdio.h>
struct employee
{
char name[20];
float basic_pay;
float DA;
float Gross_salary;
}E[100];
main()
{
int i;
clrscr();
for(i=0;i<100;i++)
{
printf(“enter the name and basic pay for %d employee\n”,i+1);
scanf(“%s%f”,E[i].name,&E[i].basic_pay);
}
for(i=0;i<100;i++)
{
E[i].DA=52*E[i].basic_pay/100;
E[i].Gross_salary=E[i].DA+E[i].basic_pay;
printf(“employee name is %s, gross
salary=%f\n”,E[i].name,E[i].Gross_salary);
}
getch();
}

5. (a) What are the file I/O functions in C? Give a brief note about the task performed
by each function.
Once a file is opened, reading out of or writing to it is accomplished using the standard
I/O routines.

Appendix-C.p65 15 7/29/08, 5:22 PM


C.16 Solved Question Papers

The getc and putc functions


The simplest file I/O functions are getc and putc. These are analogous to getchar and
putchar functions and handle one character at a time. Assume that a file is opened with
mode w and file pointer fp. Then, the statement
putc(c,fp) ;
writes the character contained in the character variable c to the file associated with FILE
pointer fp. Similarly, getc is used to read a character from a file that has been opened in
read mode. For example, the statement
c=get(fp1);
would read a character from the file whose file pointer is fp1.
The file pointer moves by one character position for every operation of getc or putc. The
getc will return an end-of-file marker EOF, when or end of the file has been reached.
The fprintf and fscanf functions
These functions are analogous to printf and scanf. The syntax for fprintf is
fprintf(file pointer, ”control string”, variable list);
Example: fprintf(fptr, “ %d%s”,a, str);
fprintf is used to write multiple data types to the file at a time.
The syntax for fscanf is
fscanf(file pointer, ”control string”, variable list);
Example: fscanf(fptr, “ %d%s”,a, str);
fscanf is used to read multiple data types from the file.
(b) Write a program to read an input file and count the number of characters in the input
file.
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fptr;
int nc=0;
char ch;
clrscr();
fptr=fopen(“input.c”,”r”);
if(fptr!=NULL)
{
while((ch=getc(fptr))!=EOF)
{
nc++;
}
fclose(fptr);
printf(”number of characters =%d\n”,nc);
}
else
printf(“the input file does not exist\n”);
getch();
}

Appendix-C.p65 16 7/29/08, 5:22 PM


Solved Question Papers C.17

6. Write a C program for implementation of various operations on circular queue.


#include<stdio.h>
#define size 20
int cq[size],F=0,R=0,count=0;
main()
{
int a,ch;
clrscr();
while(1)
{
printf(“main menu\n”);
printf(“1.insertion\t2.deletion\t3.display\t4.exit\n”);
printf(“enter your choice\n”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“enter the value to be inserted\n”);
scanf(“%d”,&a);
insert(a);
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf(“wrong choice\n”);
}
getch();
}

/* insertion function */
insert(int x)
{
if(F==R&&count==size-1)
{
printf(“circular queue is full\n”);
return;
}
cq[R]=x;
R=(R+1)%size;
}

Appendix-C.p65 17 7/29/08, 5:22 PM


C.18 Solved Question Papers

/* deletion function */
delete()
{
if(F==R&&count==0)
{
printf(“circular queue is empty\n”);
return;
}
printf(“the deleted element is %d\n”,cq[F]);
F=(F+1)%size;
}

/* display function */
display()
{
int i;
if(F==R&&count==0)
{
printf(“circular queue is empty\n”);
return;
}
for(i=F;i!=R;i=(i+1)%size)
printf(“%d”,cq[i]);
}
7. How can a polynomial in three variables (x ,y and z) be represented by a singly linked list?
Each node should represent a term and should contain the powers of x, y and z as well as
the coefficient of that term. Write a routine to evaluate this polynomial for given values of
x, y and z.
A polynomial can be represented with a linked list in the same way as we represent a polyno-
mial with a single variable.
COEFFICIENT X- POWER Y- POWER Z- POWER NEXT Addr
2 3 4 3 2 5
Consider a simple polynomial P(x,y,z)=5x y z +10x y z . This can be represented as
5 2 3 4 ¾¾¾¾¾¾¾¾ 10 3 2 5 NULL

Routine to evaluate the given polynomial


struct poly
{
int coef, xpow, ypow, zpow;
};
evaluate()
{
int x, y, z;
long int sum=0;
if(first==NULL)
{

Appendix-C.p65 18 7/29/08, 5:22 PM


Solved Question Papers C.19

printf(“list is empty\n”);
return;
}
printf(“enter the values of x, y, Z”);
scanf(“%d%d%d”,&x,&y,&z);
ptr=first;
while(ptr->next!=NULL)
{
sum+=pow(x,ptr->xpow)*pow(y, ptr->ypow)*pow(z, ptr-
>zpow)*ptr->coef;
ptr=ptr->next;
}
printf(“SUM=%ld\n”,sum);
}
8. (a) Write a C program to search for a given element in the integer array using binary
search.

#include<stdio.h>
main()
{
int a[10],n,i,pos=0,key;
clrscr();
printf(“enter the size of array\n”);
scanf(“%d”,&n);
printf(“enter the elements into array\n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i);
printf(“enter the element to be searched\n”);
scanf(“%d”,&key);
pos=bin_search(a,n,key);
if(pos!=0)
printf(“element is found at %d place”,pos);
else
printf(“element not found\n”);
getch();
}

/* Binary search function */


bin_search(b,n,x)
int *b,n,x;
{
int lb,ub,mid;
lb=0;
ub=n–1;
while(lb<=ub)
{
mid=(lb+ub)/2;

Appendix-C.p65 19 7/29/08, 5:22 PM


C.20 Solved Question Papers
if(x>*(b+mid))
lb=mid+1;
else if(x<*(b+mid))
ub=mid–1;
else
return mid+1;
}
}
(b) Write a C program to sort the elements of an array using tree sort method with a
suitable example.
#include<stdio.h>
#include define MAXSIZE 50
void heapsort(int elements[ ],int maxsize);
void heap(int elements[ ], int root, int leaf);
int elements[MAXSIZE],maxsize;
main()
{
int i;
printf(“\n enter no of elements:”);
scanf(“%d”,&maxsize);
printf(“enter the elements to be sorted\n”);
for(i=0;i<maxsize;i++)
{
scanf(“%d”,&elements[i]);
}
printf(“array before sorting is \n”);
for(i=0;i<maxsize;i++)
printf(“%d”,elements[i]);
heapsort(elements,maxsize);
printf(“\narray after sorting is \n”);
for(i=0;i<maxsize;i++)
printf(“%d”,elements[i]);
}
void heapsort(int elements[],int maxsize)
{
int i,temp;
for(i=(maxsize%2)–1;i>0;i–)
{
temp=elements[0];
elements[0]=elements[i];
elements[i]=temp;
heap(elements,0,i–1);
}
}
void heap(int elements[],int root, int leaf)
{
int flag, max, temp;

Appendix-C.p65 20 7/29/08, 5:22 PM


Solved Question Papers C.21

flag=0;
while((root*2<=leaf)&&(!flag))
{
if(root*2==leaf)
max=root*2;
else if(elements[root*2]>elements[(root*2)+1])
max=root*2+1;
if(element[root]<element[max])
{
temp=elements[root];
elements[root]=elements[max];
elements[max]=temp;
root=max;
}
else
flag=1;
}
}

Appendix-C.p65 21 7/29/08, 5:22 PM


C Programming and Data Structures
May/June 2007

SET- 3

1. (a) Explain the following and illustrate it with an example each.


(i) Increment and Decrement operator
The increment operator is represented by ++ and decrement operator by– – . Increment
operator is to add 1 to the value of the variable. For example, ++a is equivalent to a=a+1.
Increment operator is of two types. They are
Pre increment ++a
Post increment a++. There is no difference between the two when
they are used individually. But when they are used in an expression they have different
meanings. Consider the following example.
Let the value of A be 5.
A=5;
B=++A; in this statement both the values of A and B are 6.
B=A++; in this statement the value of B is 5 and A is 6.
In pre-increment the value of the variable is incremented and then it is assigned to B. In
post-increment the value of A is assigned to B and then the value of A is incremented.
Decrement operator is to subtract 1 from the value of the variable. For example,
– –a is equivalent to a=a–1. Decrement operator is of two types. They are
Pre-decrement – –a
Post-decrement a– –. There is no difference between the two when they are
used individually. But when they are used in an expression they have different meanings.
Consider the following example.
Let the value of A be 5.
A=5;
B= – –A; in this statement both the values of A and B are 4.
B=A– –; in this statement the value of B is 5 and A is 4.
In pre-decrement the value of the variable is decremented and then it is assigned to B.
In post-decrement the value of A is assigned to B and then the value of A is decremented.
(ii) Conditional operator
A ternary operator pair “?:” is available in C to construct conditional expressions of the
form: exp1?exp2:exp3;
Here, exp1 is evaluated first. If it is nonzero (or true), then exp2 is evaluated and this
becomes the result of the expression. However, if exp1 is false, exp3 is evaluated and it
becomes the value of the expression. Consider the given example:

Appendix-C.p65 22 7/29/08, 5:22 PM


Solved Question Papers C.23

A=10;
B=15;
C=(A>B)?A:B;
In this, A>B is evaluated. If it is true, C is assigned the value of A, otherwise it is assigned
the value of B.
(iii) Bitwise operator
These are special types of operators used for manipulation of data at bit level. These
operators are used for testing the bits, or shifting them left or right. They can be applied
only on integers. The various bitwise operators are:
Operator Meaning
& Bitwise AND
| Bitwise OR
! Bitwise NOT
^ Exclusive OR
<< Left shift
>> Right shift
~ One’s complement

(iv) Assignment operator


They are used to assign the result of an expression to a variable. The assignment operator
used is “=”. The statement a=20, means the value 20 is stored in a. the syntax for this
operator is
Variable=expression;
Another form of assignment operator is
Variable op= expression; op stands for operator.
Example:
A+=1; is same as A= A+1;
In the same way we have /=,*=,-=,%=.
(b) State the rules that are applied while evaluating an expression in automatic type
conversion.

(I) If one of the operands is long double, the other will be converted to long double and the
result will be long double
(II) else if one of the operands is double, the other will be converted to double and the
result will be double
(III) else if one of the operands is float, the other will be converted to float and the result
will be float
(IV) else if one of the operands is unsigned long int, the other will be converted to unsigned
long int and the result will be unsigned long int
(V) else if one of the operands is long int, the other will be converted to long int and the
result will be long int
(VI) else if one of the operands is unsigned int, the other will be converted to unsigned int
and the result will be unsigned int

Appendix-C.p65 23 7/29/08, 5:22 PM


C.24 Solved Question Papers

(VII) All short and char are automatically converted to int.


2. (a) What do you mean by functions? Give the structure of the functions and explain
about the arguments and their return values.
A C program has always a main module (called main) where the execution of the program
begins. If a program is very big and if we write all the statements of that program in the
main itself then it may become complex and large. As a result, the task of debugging and
maintaining may become difficult. On the other hand, if we split the program into several
functional portions, these are easier. These subprograms are called functions. The structure
of the function is

function_name(argument list)
declaration of argument list;
{
local variable declaration;
executable statements;
return value;
}
Argument list — The arguments are valid variable names separated by commas. The
argument variables receive values from a calling function. Thus, they provide us the link
between the main program and the function.
Return values — A function may or may not send a value back to the calling function. This
value which is sent to the calling function is the return value of the function. It is achieved
through the return keyword. There can be only one value in a return statement.
(b) Write a C program that uses function to sort an array of integers.
#include<stdio.h>
main()
{
int a[20],i,n;
clrscr();
printf(“enter the value of n\n”);
scanf(“%d”,&n);
printf(“enter the elements into array\n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i);
sort(a,n);
printf(“elements after sorting are \n”);
for(i=0;i<n;i++);
printf(“%d\t”,*(a+i));
getch();
}
sort(x,n)
int *x,n;
{
int i,j,temp;
for(i=0;i<n;i++)
{

Appendix-C.p65 24 7/29/08, 5:22 PM


Solved Question Papers C.25

for(j=0;j<n;j++)
if(*(x+j)>*(x+j+1))
{
temp=*(x+j);
*(x+j)=*(x+j+1);
*(x+j+1)=temp;
}
}
}

3. (a) Explain the process of accessing a variable through its pointer. Give an example.
The variable can be accessed by a pointer by using the operators & and *.
& gives the address of the variable where it is stored and * gives the value present at that
address. & is called address of operator.
* is called value at that address operator.
Every variable will have three components.
int a=10,b;
a Name
10 Value
100 Address
The address of the variable a can be assigned to any pointer as shown below.
int *ptr;
ptr=&a; /* this statement assigns the address of a to ptr */
b=*ptr;/* this statement assigns the value at the address contained in ptr to b */
Example program:
#include<stdio.h>
main()
{
int x,y,*p;
x=20;
p=&x;
y=*p;
printf(“%d is the value stored at address %u\n”,x,&x);
printf(“%d is the value stored at address %u\n”,*p,p);
printf(“%d is the value stored at address %u\n”,y,&y);
getch();
}
(b) Write a C program using pointers to read in an array of integers and print its
elements in reverse order.
#include<stdio.h>
main()
{
int a[20,n,I;
clrscr();
printf(“enter the value of n\n”);

Appendix-C.p65 25 7/29/08, 5:22 PM


C.26 Solved Question Papers

scanf(“%d”,&n);
/* reading values into the array */
printf(“enter the elements into array\n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i);
/* printing the elements in reverse order */
printf(“elements in reverse order are\n”);
for(i=n–1;i>=0;i– –)
printf(“%d\t”,*(a+i));
getch();
}
4. (a) Write a C program to illustrate the comparison of structure variables.

#include<stdio.h>
struct student
{
int number;
char name[20];
int marks;
} s1= {111,”Rao”, 725};

main ()
{
struct student s2= {222,”Reddy”, 670};
clrscr ();
/* comparison of structures */
if (s1==s2)
printf (“s1 and s2 are same student records\n”);
else
printf (“s1 and s2 are records of two different students\n”);
getch ();
}
(b) What is the use of a structure? Given an example for a structure with initialized
values.
A structure is a collection of items of similar or dissimilar data types, which share a
common name.
Uses of structures
· A structure helps us to organize complex data in a meaningful manner.
· The concept of derived data types is realized using structures.
· We can create variables of structure type.
· Structures are used to implement linked lists, binary trees and other data structures.
Structure with initialized values:
#include<stdio.h>
struct record
{
int day;

Appendix-C.p65 26 7/29/08, 5:22 PM


Solved Question Papers C.27

char month[20];
int year;
}a={21,”May”,2007};
main()
{
struct record b;
clrscr();
b.day=28;
strcpy(b.month,”May”);
b.year=2007;
printf(“details of exam held\n”);
printf(“DATE-%d\tMonth-%s\tYear-
%d\n”,a.day,a.month,a.year);
printf(“DATE-%d\tMonth-%s\tYear-
%d\n”,b.day,b.month,b.year);
getch();
}
5. (a) Distinguish between text mode and binary mode operation of a file.
Text Mode Binary Mode
The different modes of operations The different modes of operations
used in text mode are a, r, w used in binary mode are ab, rb, wb
a- append, r- read, w- write ab- append, rb- read, wb- write
a+, r+, w+ are the additional modes a+b, r+b, w+b are additional modes
used in text mode. used in binary mode.
a+ - read and write and the contents are a+b - read and write and the contents
safe when the file is opened. are safe when the file is opened.
r+ - read and write and the contents are r+b - read and write and the contents
safe when the file is opened. are safe when the file is opened.
w+ - read and write, a file will be created w+b - read and write , a file will be
if it does not exist created if it does not exist

(b) Write a C program to open a pre-existing file and add information at the end of the
file. Display the contents of the file before and after appending.
#include<stdio.h>
main()
{
FILE *fptr;
char ch;
clrscr();
fptr=fopen(“input.txt”,”r+”);
printf(“the contents of the file before appending
data\n”);
while((ch=getc(fptr))!=EOF)
printf(“%c”,ch);
printf(“enter the data to be appended\n”);
while((ch=getchar())!=EOF)

Appendix-C.p65 27 7/29/08, 5:22 PM


C.28 Solved Question Papers

putc(ch,fptr);
printf(“the contents of the file after appending data:\n”);
while((ch=getc(fptr))!=EOF)
printf(“%c”,ch);
getch();
}
6. Write a program to convert a given prefix expression to postfix expression using stacks.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
char stack[30],str[30];
int tos=0;

void push(char c)
{
if(tos>=29)
{
printf(“stack is full\n”);
return;
}
else
stack[tos++]=c;
}

char pop()
{
tos– –;
if(tos<0)
{
printf(“stack is empty\n”);
return 0;
}
else
return(stack[tos]);
}

main()
{
int i,check_stack=0;
char x;
clrscr();
printf(“enter the prefix expression\n”);
gets(str);
for(i=0;str[i]!=’\0’;i++)
{
if(!isalpha(str[i]))

Appendix-C.p65 28 7/29/08, 5:22 PM


Solved Question Papers C.29

{
if(check_stack>1)
printf(“%c”,pop());
push(str[i]);
check_stack=0;
}
else
{
printf(“%c”,str[i]);
check_stack++;
if(check_stack==2)
{
printf(“%c”,pop());
check_stack=0;
}
}
}
while(tos!=0)
printf(“%c”,pop());
getch();
}
7. (a) Write a C program to implement binary tree traversals.
Binary tree traversals are of three types. They are
(1) Inorder traversals
(2) Preorder traversals
(3) Post order traversals
/* IN ORDER TRAVERSAL */
inorder(node * root)
{
if(root!=NULL)
{
inorder (root->left);
printf(“%d”, root->data);
inorder(root->right);
}
else
return;
}

/* PRE ORDER TRAVERSAL */

preorder(node * root)
{
if(root!=NULL)
{
preorder (root->left);

Appendix-C.p65 29 7/29/08, 5:22 PM


C.30 Solved Question Papers

printf(“%d”, root->data);
preorder(root->right);
}
else
return;
}

/* POST ORDER TRAVERSAL */

postorder(node * root)
{
if(root!=NULL)
{
postorder (root->left);
printf(“%d”, root->data);
postorder(root->right);
}
else
return;
}
(b) Write an algorithm to count the number of leaf nodes in a binary tree. What is its
computing time?
tree( struct node * root)
{
static int count=0;
if(root!=NULL)
{
if(root->left!=NULL||root->right!=NULL)
{
tree(root->left);
count++;
tree(root->right);
}
else
return;
}
else
return;
}
8. (a) Write a C program to sort the elements of an array using Quick sort with a suitable
example.

/* main function */
#include<stdio.h>
#include<conio.h>
main()
{

Appendix-C.p65 30 7/29/08, 5:22 PM


Solved Question Papers C.31

int i,n,a[20];
clrscr();
printf(“enter the size of array\n”);
scanf(“%d”,&n);
printf(“enter the elements into array\n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i);
quicksort(a,0,n–1);
prints(“elements after sorting are\n”);
for(i=0;i<n;i++)
printf(“%d\t”,*(a+i));
getch();
}
/* QUICK SORT FUNCTION */
quicksort(int *k,int lb,in tub)
{
int pivot,i,j;
if(lb<ub)
{
i=lb;
j=ub;
pivot=i;
while(i<j)
{
while((*(k+i)<=*(k+pivot))&&(i<ub))
i++;
while(*(k+j)>*(k+pivot))
j– –;
if(i<j)
swap(k+i,k+j);
}
swap(k+j,k+pivot);
quicksort(k,lb,j–1);
quicksort(k,j+1,ub);
}
return;
}

/* Function for swapping */


swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

Appendix-C.p65 31 7/29/08, 5:22 PM


C.32 Solved Question Papers

Example : Consider the elements to be sorted


42 23 74 11 65 58 94 36 99 87
Pass 1: 11 23 36 42 65 58 94 74 99 87
Pass 2: 11 23 36 42 65 58 94 74 99 87
Pass 3: 11 23 36 42 58 65 94 74 99 87
Pass 4: 11 23 36 42 58 65 87 74 94 99
Pass 5: 11 23 36 42 58 65 74 87 94 99
The elements after sorting are
11 23 36 42 58 65 74 87 94 99
(b) What is the worst case and best case time complexity of the above program?
The time complexity of the above program in the worst and best case is O(n2) and
O(nlogn) respectively.

Appendix-C.p65 32 7/29/08, 5:22 PM


C Programming and Data Structures
May/June 2007

SET- 4

1. Write about space requirements for variables of different data types.


Sl no Type Size (bytes) Range
1 Char or signed char 1 –128 to 127
2 Unsigned char 1 0 to 25
3 Int or signed int 2 –32769 to 32767
4 Unsigned int 2 0 to 65535
5 Short int or signed short int 1 –128 to 127
6 Unsigned short int 1 0 to 255
7 Long int or signed long int 4 –2147483648 to 2147483647
8 Unsigned long int 4 0 to 4294967295
9 Float 4 3.4E–38 to 3.4E38
10 Double 8 1.7E–308 to 1.7E+308
11 Long double 10 3.4E–4932 to 1.1E+432

2. (a) Distinguish between the following:


(i) Actual and formal arguments
Actual Parameters Formal Parameters
Actual parameters are the arguments Formal parameters are the arguments
passed when the function is called. specified during function definition.
Eg: sum(x,y); Eg: sum(int a,int b)
x,y here are called actual parameters. {
…….. }
Here a, b are called formal parameters.

(ii) Global and local variables


Global Variables Local Variables
The variables that are declared The variables that are declared inside a
outside the function are called global function definition are called local variables.
variables.
Eg: int a,b,c; Eg: main()

(Contd.)

Appendix-C.p65 33 7/29/08, 5:22 PM


C.34 Solved Question Papers

Global Variables Local Variables


main() {
{ int x,y;
…….. ……..
} }
Here a, b, c are global variables. Here x, y are called local variables.
A global variable’s scope and lifetime A local variable’s scope and lifetime is
is throughout the program confined to the function in which it is
declared.

(iii) Automatic and static variables


Automatic Variables Static Variables
The default storage class for local Static variables are to be declared explicitly.
variables is auto.
Eg: main() Eg: main()
{ {
auto int a,b,c; static int x,y;
…….. ……..
} }
Here a, b, c are global variables. Here x, y are called local variables.
Keyword used is auto Keyword used is static
Default value of automatic variables is Default value of static variables is a zero.
a garbage value.
Automatic variables can be initialized Static variables can be initialized only once.
any number of times.
(b) Explain in detail about pass by values and pass by reference. Explain with a sample
program.
Pass by value: In pass by value the actual values are passed as arguments to the called
function. These actual values are copied into the arguments of the called function. The
changes that are made in the function do not affect the actual values.
#include<stdio.h>
main()
{
int a=10,b=20;
clrscr();
printf(“The values of a and b before swapping are %d and
%d\n”,a,b);
swap(a,b);
printf(“The values of a and b after swapping are %d and
%d\n”,a,b);
getch();
}
swap(int x, int y)
{

Appendix-C.p65 34 7/29/08, 5:22 PM


Solved Question Papers C.35

int temp;
temp=x;
x=y;
y=temp;
}
Output:
The values of a and b before swapping are 10 and 20.
The values of a and b after swapping are 10 and 20.
Pass by reference: In call by reference the address of the actual parameters are passed as
arguments to the called function. The formal parameters are declared as pointers. The
changes that are made to the formal parameters affect the actual parameters.
#include<stdio.h>
main()
{
int a=10,b=20;
clrscr();
printf(“The values of a and b before swapping are %d and
%d\n”,a,b);
swap(&a,&b);
printf(“The values of a and b after swapping are %d and
%d\n”,a,b);
getch();
}
swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Output:
The values of a and b before swapping are 10 and 20.
The values of a and b after swapping are 20 and 10.
3. (a) Write a C program using pointer for string comparison.
#include<stdio.h>
#include<string.h>
main()
{
char str1[20],str2[20];
char *ptr1=str1,*ptr2=str2;
int res=0;
clrscr();
printf(“enter string one\n”);
gets(str1);
printf(“enter string two\n”);

Appendix-C.p65 35 7/29/08, 5:22 PM


C.36 Solved Question Papers

gets(str2);
while(*ptr1!=’\0’)
{
if(*ptr1==*ptr2)
{
ptr1++;
ptr2++;
}
else
{
res=1;
break;
}
}
if(res!=0)
printf(“strings are different\n”);
else
printf(“strings are identical\n”);
getch();
}
(b) Write a C program to arrange the given numbers in ascending order using pointers.
#include<stdio.h>
main()
{
int a[20],i,n;
clrscr();
printf(“enter the value of n\n”);
scanf(“%d”,&n);
printf(“enter the elements into array\n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i);
sort(a,n);
printf(“elements after sorting are \n”);
for(i=0;i<n;i++);
printf(“%d\t”,*(a+i));
getch();
}
sort(x,n)
int *x,n;
{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
if(*(x+j)>*(x+j+1))
{

Appendix-C.p65 36 7/29/08, 5:22 PM


Solved Question Papers C.37
temp=*(x+j);
*(x+j)=*(x+j+1);
*(x+j+1)=temp;
}
}
}
4. (a) Describe nested structures. Draw diagrams to explain a nested structure.
A nested structure means a structure within a structure. This can be done in two ways.
· A structure itself can be a member of another structure.
· A structure object can be a member of another structure.
The syntax for a nested structure is as follows:
struct tagname1 struct tagname1
{ {
datatype member1; datatype member1;
datatype member2; datatype member2;
datatype member3; .
. .
struct tagname2 struct tagname2 x;
{ };
datatype member4; struct tagname2
datatype member5; {
. datatype memberN1;
. datatype memberN2;
}a; .
}b; };
The inner member4 is accessed as b.a.member4.
The syntax for accessing the innermost members is tagname1object.
tagname name2 object. member.
Diagram for nested structures

Appendix-C.p65 37 7/29/08, 5:22 PM


C.38 Solved Question Papers
(b) Write a program to declare pointers as members of a structure and display the
contents of the structure. Define a structure object, boy, with three fields: name,
age and height.
#include<stdio.h>
struct boy
{
char *name;
int *age;
float *height;
}*sp;
main()
{
char name[10]=”latha”;
int age=18;
float height=167.64;
sp->name=name;
sp->age=&age;
sp->height=&height;
clrscr();
printf(“\n NAME=%s”,sp->name);
printf(“\nAGE=%d\nHEIGHT=%f”,*sp->age,*sp->height);
getch();
}

5. (a) What is the task performed by fseek() function? What is its syntax? Explain each
parameter in it.
The fseek function is used to move the file pointer to the desired position in the file.
This means random access to files is made possible by the fseek function. This function has
three arguments in its syntax. The syntax of this function is
fseek (filepointer, offset, position);
· The first argument is the file type pointer which points to the file that we are currently
operating with.
· The second argument offset specifies the number of bytes the file pointer has to move.
The file pointer can move either forward or backward, depending on the value of off-
set. If the offset value is positive it moves forward and if it is negative it moves back-
ward. The value of the offset is of long type.
· The third argument position takes one of the three integer values. These values have
specific meaning.
Value Meaning
0 Beginning of the file
1 Current position
2 End of file
Examples:
fseek(fp,m,0) -fp moves m bytes from the starting of the file and points to (m+1)th byte.
fseek(fp,-m,1) -from the current position move m bytes in backward direction.

Appendix-C.p65 38 7/29/08, 5:22 PM


Solved Question Papers C.39

fseek(fp,0,0) -go to the beginning of the file.


fseek(fp,-m.2) -move backward by m bytes from the end of the file.
Offset cannot take negative values when the position value is 0 and the file pointer
cannot take positive values when the position value is 2, as the file pointer cannot go
beyond the end of file.
(b) Write a C program to read the text file containing some paragraph. Use fseek() and
read the text after skipping n characters from the beginning of the file.
#include<stdio.h>
main()
{
int n;
FILE *fptr;
char ch;
clrscr();
fptr=fopen(“input.txt”,”r”);
printf(“enter the value of n\n”);
scanf(“%d”,&n);
printf(“the contents of the file are:\n);
while((ch=getc(fptr))!=EOF)
printf(“%c”,ch);
fseek(fptr,0,0);
printf(“the contents of the file after skipping n Charac-
ters are:\n);
fseek(fptr,n,0);
while((ch=getc(fptr))!=EOF)
printf(“%c”,ch);
fclose(fptr);
getch();
}

6. Write a non-recursive simulation of Towers of Hanoi problem.


#include <stdio.h>
#include <stdlib.h>

#define PR (void)printf(
#define PE (void)fprintf(stderr,

#define ALLO(x) { if((x = (int *)malloc((n+3) * sizeof(int))) == NULL) {\


PE #x “ allocation failed!\n”); exit(1); }}

main(int argc, char *argv[])


/* ========================*/
{
int i, *a, *b, *c, *p, *fr, *to, *sp, n, n1, n2;

Appendix-C.p65 39 7/29/08, 5:22 PM


C.40 Solved Question Papers

n = atoi(argv[1]);
n1 = n+1;
n2 = n+2;
ALLO(a)
ALLO(b)
ALLO(c)

a[0] = 1; b[0] = c[0] = n1;


a[n1] = b[n1] = c[n1] = n1;
a[n2] = 1; b[n2] = 2; c[n2] = 3;
for(i=1; i<n1; i++) {
a[i] = i; b[i] = c[i] = 0;
}

fr = a;
if(n&1) { to = c; sp = b; }
else { to = b; sp = c; }

while(c[0]>1) {
PR”move disc %d from %d to %d\n”, i=fr[fr[0]++], fr[n2], to[n2]);
p=sp;
if ( ( to[– –to[0]] = i)&1) {
sp=to;
if(fr[fr[0]] > p[p[0]]) { to=fr; fr=p; }
else to=p;
} else { sp=fr; fr=p; }
}
}
7. Write a routine to reverse elements of a doubly linked list by traversing the list only once.
struct DLL
{
struct DLL *pre;
int data;
struct DLL *next;
}*first,*ptr,*ptr1,*fresh;

Reverse()
{
if(first==NULL)
{
printf(“the list is empty so no need to reverse\n”);
return;
}
ptr=first;
ptr->pre=ptr->next;
ptr->next=NULL;
ptr1=ptr->pre;

Appendix-C.p65 40 7/29/08, 5:22 PM


Solved Question Papers C.41

while(ptr1->next!=NULL)
{
ptr1->pre=ptr1->next;
ptr1->next=ptr;
ptr1=ptr1->pre;
ptr=ptr->pre;
}
ptr1->next=ptr;
ptr1->pre=NULL;
first=ptr1;
}
8. (a) Explain Quick sort with algorithm.
This method is also called partition exchange sort. This method is based on divide-and-
conquer technique, i.e., the entire list is divided into various partitions and sorting is again
and again applied on the partitions.
In this method, the list is divided into two, based on an element called the pivot element.
Usually, the first element is considered to be the pivot element. Now, move the pivot ele-
ment into its correct position in the list. The elements to the left of the pivot are less than the
pivot while the elements to the right of the pivot are greater than the pivot. The process is
repeated in each of these partitions. This process proceeds till we get the sorted list of
elements. Let us understand this by an example. Consider the list— 74, 39, 35, 32, 97, 84.
1. We will take 74 as the pivot and move it to a position so that the new list becomes—
39, 35, 32, 74, 97, 84.
2. Now take the partitioned list—39, 35, 32. Let us take 39 as the pivot. Moving it to the
correct position gives—35, 32, 39. Reapplying the process to the left partition 35, 32,
we get 32, 35.
3. Apply the process to the right partition of 74. Taking 97 as the pivot and positioning it,
we get 84, 97.
4. Assembling all the elements from each partition, we get the sorted list.

ALGORITHM FOR QUICK SORT

1. Start.
2. Select the first element of the array as pivot.
3. Position the pivot such that the elements to the left of the pivot are less then the pivot and the
elements to the right of the pivot are greater than the pivot.
4. Consider the left and right partition and repeat the steps 2 and 3.
5. Merge all the partitions to get the sorted list of elements.
6. Stop.
(b) Analyze the worst case performance of Quick sort and compare with Selection sort.
The selection of the pivot plays a vital role in determining the efficiency of the quick sort.
The main reasons for this are— the pivot may partition the list into two so that one partition
is much bigger than the other and the partition may be in an unsorted manner.

Appendix-C.p65 41 7/29/08, 5:22 PM


C.42 Solved Question Papers

We will assume that the pivot partitions the list into two so that one of the partitions has
no elements while the other has all the other elements. This is the worst case possible. Here,
the total number of comparisons at the end of the sort would have been:
(n–1)+ (n–2) + (n–3) +……+2+1=1/2(n–1)*n = ½(n2)–1/2(n). This is equal to O (n2).
Thus the efficiency of the quick sort in its worst case is O (n2).
Efficiency of selection sort
You can easily understand from the algorithm that the first pass of the program does (n–1)
comparisons. The next pass does (n–2) comparisons, and so on. Thus, the total number of
comparisons at the end of the sort would be:
(n–1)+ (n–2) + (n–3) +……+2+1=1/2(n–1)*n = ½(n2)–1/2(n). This is equal to O (n2).
Thus the efficiency of the selection sort is O (n2).

Appendix-C.p65 42 7/29/08, 5:22 PM

You might also like