You are on page 1of 42

)FFA@EN

+
SoIvcd Qucstion Fapcrs
C Frogramming and Data Structurcs
May/)unc 2007
SfT- 1
1. (a) Write a program to determine and print the sum of the following harmonic series
for a given value of :1+1/2+1/3+1/4+1/5...+1/.
#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.
LogicaI operators used in C Ianguage are
&& - IogicaI AND
,, - IogicaI OR
! - IogicaI NOT
Appendix-C.p65 7/29/08, 5:21 PM 1
To get more please visit: http://www.creativeworld9.blogspot.com
C.2 Soved ueston lnpers
Truth tabIe Ior IogicaI 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
LogicaI AND is true onIy when aII the inputs are true and IogicaI OR is true iI any one oI
the inputs is true. LogicaI NOT is a unary operator, it is true when input is IaIse and vice-
versa.
SampIe program Ior IogicaI 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 beIore it is passed on to
the compiIer.
The program typed in the editor is the source to the preprocessor. The preprocessor direc-
tives are generaIIy initiaIized at the beginning oI the program. It begins with a symboI
#(hash).
ExampIe : #deIine pi 3.14
Appendix-C.p65 7/29/08, 5:21 PM 2
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers 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?
ConditionaI compiIation aIIows the user to compiIe the portions oI the program based on
certain conditions. The directives used Ior conditionaI compiIation are #iI, #eIse, #endiI,
etc.
The syntax Ior #iI 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 deIined using #deIine can be undeIined using #undeI direc-
tive.
Syntax : #undeI identiIier
It is useIuI when we do not want to aIIow the use oI macros in any portion oI the program.
ExampIe:
#include<stdio.h>
#define wait getch()
main()
{
int a;
clrscr();
#undef wait getch()
Appendix-C.p65 7/29/08, 5:21 PM 3
To get more please visit: http://www.creativeworld9.blogspot.com
C.4 Soved ueston lnpers
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 variabIe which stores the address oI another variabIe. The syntax Ior decIar-
ing a pointer is data type * pointername;
ExampIe:
int *ptr;
char *cptr;
float *p;
Once a pointer variabIe is decIared, it can be assigned the address oI a variabIe using as-
signment statement.
ExampIe: int a, *ptr;
ptr&a; &` is caIIed address oI operator. ptr is assigned the address oI a.
The pointer and variabIe must be oI 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.
ExampIe: ptrptr1; here the pointer is incremented depending on its data type. II it is
an integer then the scaIe Iactor 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 itseII a constant pointer to that array.
(iv) Pointers cannot be used as formal parameters in headers to function
definitions.
False. C supports caII by reIerence in which the IormaI 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 compiIer cannot convert int to int *.
(iii) mp2-p1;
The given statement is correct as C supports pointer arithmetic.
(iv) *p1&n;
The given statement is not correct as the compiIer cannot convert int* to int.
Appendix-C.p65 7/29/08, 5:21 PM 4
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers C.S
4. (a) What are bit fields? What are its advantages? What is its syntax?
Bit IieIds are the speciaI Ieatures provided in C to change the order oI aIIocation oI memory
Irom bytes to bits. Using bit IieIds we can speciIy the exact number oI bits required Ior the
storage oI vaIues. The number oI bits required Ior a variabIe is speciIied by a non-negative
integer preceded by a coIon.
Advantages:
Changes order oI aIIocation oI memory storage.
Minimizes the memory wastage.
Memory can be used more eIIectiveIy and eIIicientIy.
Syntax Ior using bit IieIds:
unsigned variabIe : size;
ExampIe:
unsigned pass:1;
unsigned IaiI: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 7/29/08, 5:21 PM 5
To get more please visit: http://www.creativeworld9.blogspot.com
C.6 Soved ueston lnpers
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 7/29/08, 5:21 PM 6
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers 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/29/08, 5:21 PM 7
To get more please visit: http://www.creativeworld9.blogspot.com
C.8 Soved ueston lnpers
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 7/29/08, 5:21 PM 8
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers C.9
ptr3=first3;
while(ptr3->next!=NULL)
ptr3=ptr3->next;
fresh=(node *)malloc(sizeof(node));
Iresh-~dataptr1-~data;
ptr3-~nextIresh;
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 aIso caIIed 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 7/29/08, 5:21 PM 9
To get more please visit: http://www.creativeworld9.blogspot.com
C.10 Soved ueston lnpers
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.
C
A
(n)1/n
K 1
n

C
A
(k1) C
A
(nk)}(n1)
nC
A
(n)n(n1)

K 1
n

C
A
(k1) C
A
(nk)}
n(n1)C
A
(0) C
A
(n1) C
A
(1) C
A
(n2) .. C
A
(n1) C
A
(0)}
nC
A
(n)n(n1)2C
A
(0) C
A
(1).... C
A
(n1)}..(1)
repIace n with (n1)
(n1)C
A
(n1)n(n1)2C
A
(0) C
A
(1).... C
A
(n2)}..(2)
Subtract (2) Irom (1)
nC
A
(n) (n1)C
A
(n1)n
2
nn
2
n2 C
A
(n1)
nC
A
(n)2n2 C
A
(n1) (n1)C
A
(n1)
nC
A
(n)2n C
A
(n1)|n12|
nC
A
(n)2n C
A
(n1)|n1|
divide on both sides by n(n1)
(C
A
(n)/(n1))(2/(n1)) (C
A
(n1)/n)
(C
A
(n)/(n1))(2/(n1)) 2/n(C
A
(n2)/(n1))
2/(n1)2/n2/(n1)2/(n2)..2/4 C
A
(2)/32/3 C
A
(1)/2

1
K 3
2
n

(1/k)
Appendix-C.p65 7/29/08, 5:21 PM 10
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers C.11

1
3
2
n

1/kdk
2|Iogk|
1
3
n
(C
A
(n)/(n1))2|Iog(n1)Iog3|
C
A
(n)2(n1)Iog(n1)2(n1)Iog3
C
A
(n)2nIog(n1)2 Iog(n1)2nIog32 Iog3
C
A
(n) 2nIog(n1)
C
A
(n)O(nIogn)
Appendix-C.p65 7/29/08, 5:21 PM 11
To get more please visit: http://www.creativeworld9.blogspot.com
C Frogramming and Data Structurcs
May/)unc 2007
SfT- 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 oI characters encIosed in doubIe quotes. The characters
may be Ietters, numbers, speciaI characters and bIank spaces.
ExampIe: 'hai , '1982, etc;
A character constant is not equivaIent to the singIe character constant. A singIe character
string constant does not have an equivaIent integer whereas a character constant has an
integer vaIue (ASCII vaIue). String constants do not represent equivaIent numericaI
vaIues.
(b) Summarize the standard escape sequences in C. Describe them.
BIack sIash characters are aIso caIIed escape sequences.
Constant Meaning
\a` AudibIe aIert(beII)
\b` Back space
\I` Form Ieed
\n` New Iine
\r` Carriage return
\t` Tab space
\v` VerticaI tab
\ SingIe quote
\` DoubIe quote
\?` Question mark
\\` Back sIash
\0` NuII
(c) What is a variable? How can variables be characterized? Give the rules for variable
declaration.
A variabIe is a data name that may be used to store a data vaIue. A variabIe may take
diIIerent vaIues at diIIerent times during execution. VariabIes are characterized based on
the vaIue they hoId. Depending on that they are cIassiIied into int, IIoat, char, doubIe, and so on.
RuIes Ior variabIe decIaration:
They must begin with a Ietter. Some compiIers permit underscore as the Iirst
character.
ANSI standard recognizes a Iength oI 31 characters. However, the Iength shouId
not be normaIIy more than eight characters.
Appendix-C.p65 7/29/08, 5:21 PM 12
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers C.13
Uppercase and Iowercase are signiIicant. That is, variabIe SUM is not the same
as sum or Sum.
The variabIe name shouId not be a keyword.
A bIank space is not aIIowed.
(d) What is the purpose of type declarations? What are the components of type declara-
tion?
Type decIarations are used to decIare variabIes, which store the vaIue oI any data type. The
syntax Ior decIaring a variabIe is
data-type v1, v2, v3,..vn;
The components oI type decIaration are data type and variabIe Iist. Data types speciIy the
type oI data that a variabIe wiII hoId.
ExampIe: int a;
IIoat b;
char ch;
a is a variabIe that hoIds an integer-type vaIue. SimiIarIy, b and ch are variabIes oI IIoat
and character data type respectiveIy.
2. (a) Write a program to demonstrate passing an array argument to a function. Con-
sider the problem of finding the largest of 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 7/29/08, 5:21 PM 13
To get more please visit: http://www.creativeworld9.blogspot.com
C.14 Soved ueston lnpers
(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,e1));
}
3. (a) What is a pointer? How is a pointer initiated? Give an example.
A pointer is a variabIe which stores the address oI another variabIe. The syntax Ior
decIaring a pointer is data type * pointername;
ExampIe: int *ptr;
char *cptr;
IIoat *p;
Once a pointer variabIe is decIared, it can be assigned the address oI a variabIe using
assignment statement.
ExampIe: int a, *ptr;
ptr&a; &` is caIIed address oI operator. ptr is assigned the address oI a.
The pointer and variabIe must be oI 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.
ExampIe: ptrptr1; here, the pointer is incremented depending on its data type. II it
is an integer then the scaIe Iactor 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 itseII a constant pointer to that array.
(iv) Pointers cannot be used as formal parameters in headers to function defini-
tions.
Appendix-C.p65 7/29/08, 5:22 PM 14
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers C.1S
False. C supports caII by reIerence in which the IormaI parameters are pointers.
(c) If m and n have been declared as integers and p1 and p2 as pointers to i n t e -
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 compiIer cannot convert int to int *.
(iii) mp2-p1;
The given statement is correct as C supports pointer arithmetic.
(iv) *p1&n;
The given statement is not correct as the compiIer 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 IiIe is opened, reading out oI or writing to it is accompIished using the standard
I/O routines.
Appendix-C.p65 7/29/08, 5:22 PM 15
To get more please visit: http://www.creativeworld9.blogspot.com
C.16 Soved ueston lnpers
The getc and putc functions
The simpIest IiIe I/O Iunctions are getc and putc. These are anaIogous to getchar and
putchar Iunctions and handIe one character at a time. Assume that a IiIe is opened with
mode w and IiIe pointer Ip. Then, the statement
putc(c,fp) ;
writes the character contained in the character variabIe c to the IiIe associated with FILE
pointer fp. SimiIarIy, getc is used to read a character Irom a IiIe that has been opened in
read mode. For exampIe, the statement
cget(fp1);
wouId read a character Irom the IiIe whose IiIe pointer is fp1.
The IiIe pointer moves by one character position Ior every operation oI getc or putc. The
getc wiII return an end-oI-IiIe marker EOF, when or end oI the IiIe has been reached.
The fprintf and fscanf functions
These Iunctions are anaIogous to printI and scanI. The syntax Ior IprintI is
fprintf(file pointer, control string, variable list);
ExampIe: IprintI(Iptr, ' ds,a, str);
IprintI is used to write muItipIe data types to the IiIe at a time.
The syntax Ior IscanI is
fscanf(file pointer, control string, variable list);
ExampIe: IscanI(Iptr, ' ds,a, str);
IscanI is used to read muItipIe data types Irom the IiIe.
(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 7/29/08, 5:22 PM 16
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers 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 7/29/08, 5:22 PM 17
To get more please visit: http://www.creativeworld9.blogspot.com
C.18 Soved ueston lnpers
/* 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 poIynomiaI can be represented with a Iinked Iist in the same way as we represent a poIyno-
miaI with a singIe variabIe.
COEFFICIENT X- POWER Y- POWER Z- POWER NEXT Addr
Consider a simpIe poIynomiaI P(x,y,z)5x
2
y
3
z
4
10x
3
y
2
z
5
. 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 7/29/08, 5:22 PM 18
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers 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=n1;
while(lb<=ub)
{
mid=(lb+ub)/2;
Appendix-C.p65 7/29/08, 5:22 PM 19
To get more please visit: http://www.creativeworld9.blogspot.com
C.20 Soved ueston lnpers
if(x>*(b+mid))
lb=mid+1;
else if(x<*(b+mid))
ub=mid1;
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,i1);
}
}
void heap(int elements[],int root, int leaf)
{
int flag, max, temp;
Appendix-C.p65 7/29/08, 5:22 PM 20
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers 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 7/29/08, 5:22 PM 21
To get more please visit: http://www.creativeworld9.blogspot.com
C Frogramming and Data Structurcs
May/)unc 2007
SfT- 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 vaIue oI the variabIe. For exampIe, a is equivaIent to aa1.
Increment operator is oI two types. They are
Pre increment a
Post increment a. There is no diIIerence between the two when
they are used individuaIIy. But when they are used in an expression they have diIIerent
meanings. Consider the IoIIowing exampIe.
Let the vaIue oI A be 5.
A5;
BA; in this statement both the vaIues oI A and B are 6.
BA; in this statement the vaIue oI B is 5 and A is 6.
In pre-increment the vaIue oI the variabIe is incremented and then it is assigned to B. In
post-increment the vaIue oI A is assigned to B and then the vaIue oI A is incremented.
Decrement operator is to subtract 1 Irom the vaIue oI the variabIe. For exampIe,
a is equivaIent to aa1. Decrement operator is oI two types. They are
Pre-decrement a
Post-decrement a . There is no diIIerence between the two when they are
used individuaIIy. But when they are used in an expression they have diIIerent meanings.
Consider the IoIIowing exampIe.
Let the vaIue oI A be 5.
A5;
B A; in this statement both the vaIues oI A and B are 4.
BA ; in this statement the vaIue oI B is 5 and A is 4.
In pre-decrement the vaIue oI the variabIe is decremented and then it is assigned to B.
In post-decrement the vaIue oI A is assigned to B and then the vaIue oI A is decremented.
(ii) Conditional operator
A ternary operator pair '?: is avaiIabIe in C to construct conditionaI expressions oI the
Iorm: exp1?exp2:exp3;
Here, exp1 is evaIuated Iirst. II it is nonzero (or true), then exp2 is evaIuated and this
becomes the resuIt oI the expression. However, iI exp1 is IaIse, exp3 is evaIuated and it
becomes the vaIue oI the expression. Consider the given exampIe:
Appendix-C.p65 7/29/08, 5:22 PM 22
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers C.23
A10;
B15;
C(A~B)?A:B;
In this, A~B is evaIuated. II it is true, C is assigned the vaIue oI A, otherwise it is assigned
the vaIue oI B.
(iii) Bitwise operator
These are speciaI types oI operators used Ior manipuIation oI data at bit IeveI. These
operators are used Ior testing the bits, or shiIting them IeIt or right. They can be appIied
onIy 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 resuIt oI an expression to a variabIe. The assignment operator
used is '. The statement a20, means the vaIue 20 is stored in a. the syntax Ior this
operator is
VariabIeexpression;
Another Iorm oI assignment operator is
VariabIe op expression; op stands Ior operator.
ExampIe:
A1; is same as A A1;
In the same way we have /,*,-,.
(b) State the rules that are applied while evaluating an expression in automatic type
conversion.
(I) II one oI the operands is Iong doubIe, the other wiII be converted to Iong doubIe and the
resuIt wiII be Iong doubIe
(II) eIse iI one oI the operands is doubIe, the other wiII be converted to doubIe and the
resuIt wiII be doubIe
(III) eIse iI one oI the operands is IIoat, the other wiII be converted to IIoat and the resuIt
wiII be IIoat
(IV) eIse iI one oI the operands is unsigned Iong int, the other wiII be converted to unsigned
Iong int and the resuIt wiII be unsigned Iong int
(V) eIse iI one oI the operands is Iong int, the other wiII be converted to Iong int and the
resuIt wiII be Iong int
(VI) eIse iI one oI the operands is unsigned int, the other wiII be converted to unsigned int
and the resuIt wiII be unsigned int
Appendix-C.p65 7/29/08, 5:22 PM 23
To get more please visit: http://www.creativeworld9.blogspot.com
C.24 Soved ueston lnpers
(VII) AII short and char are automaticaIIy 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 aIways a main moduIe (caIIed main) where the execution oI the program
begins. II a program is very big and iI we write aII the statements oI that program in the
main itseII then it may become compIex and Iarge. As a resuIt, the task oI debugging and
maintaining may become diIIicuIt. On the other hand, iI we spIit the program into severaI
IunctionaI portions, these are easier. These subprograms are caIIed Iunctions. The structure
oI the Iunction is
function_name(argument list)
declaration of argument list;
{
local variable declaration;
executable statements;
return value;
}
Argument list The arguments are vaIid variabIe names separated by commas. The
argument variabIes receive vaIues Irom a caIIing Iunction. Thus, they provide us the Iink
between the main program and the Iunction.
Return values A Iunction may or may not send a vaIue back to the caIIing Iunction. This
vaIue which is sent to the caIIing Iunction is the return vaIue oI the Iunction. It is achieved
through the return keyword. There can be onIy one vaIue 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 7/29/08, 5:22 PM 24
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers C.2S
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 variabIe can be accessed by a pointer by using the operators & and *.
& gives the address oI the variabIe where it is stored and * gives the vaIue present at that
address. & is caIIed address oI operator.
* is caIIed vaIue at that address operator.
Every variabIe wiII have three components.
int a10,b;
Name
a
10
100
VaIue
Address
The address oI the variabIe a can be assigned to any pointer as shown beIow.
int *ptr;
ptr&a; /* this statement assigns the address oI a to ptr */
b*ptr;/* this statement assigns the vaIue at the address contained in ptr to b */
ExampIe 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 7/29/08, 5:22 PM 25
To get more please visit: http://www.creativeworld9.blogspot.com
C.26 Soved ueston lnpers
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=n1;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 coIIection oI items oI simiIar or dissimiIar data types, which share a
common name.
Uses of structures
A structure heIps us to organize compIex data in a meaningIuI manner.
The concept oI derived data types is reaIized using structures.
We can create variabIes oI structure type.
Structures are used to impIement Iinked Iists, binary trees and other data structures.
Structure with initiaIized vaIues:
#include<stdio.h>
struct record
{
int day;
Appendix-C.p65 7/29/08, 5:22 PM 26
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers 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 7/29/08, 5:22 PM 27
To get more please visit: http://www.creativeworld9.blogspot.com
C.28 Soved ueston lnpers
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 7/29/08, 5:22 PM 28
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers 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 traversaIs are oI three types. They are
(1) Inorder traversaIs
(2) Preorder traversaIs
(3) Post order traversaIs
/* 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 7/29/08, 5:22 PM 29
To get more please visit: http://www.creativeworld9.blogspot.com
C.30 Soved ueston lnpers
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 7/29/08, 5:22 PM 30
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers 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,n1);
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,j1);
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 7/29/08, 5:22 PM 31
To get more please visit: http://www.creativeworld9.blogspot.com
C.32 Soved ueston lnpers
ExampIe : Consider the eIements 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 eIements aIter 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 compIexity oI the above program in the worst and best case is O(n2) and
O(nIogn) respectiveIy.
Appendix-C.p65 7/29/08, 5:22 PM 32
To get more please visit: http://www.creativeworld9.blogspot.com
C Frogramming and Data Structurcs
May/)unc 2007
SfT- 4
1. Write about space requirements for variables of different data types.
SI 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.4E38 to 3.4E38
10 Double 8 1.7E308 to 1.7E+308
11 Long double 10 3.4E4932 to 1.1E+432
2. (a) Distinguish between the following:
(i) Actual and formal arguments
ActuaI Parameters FormaI 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
GIobaI VariabIes LocaI VariabIes
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()
(+J@.)
Appendix-C.p65 7/29/08, 5:22 PM 33
To get more please visit: http://www.creativeworld9.blogspot.com
C.34 Soved ueston lnpers
GIobaI VariabIes LocaI VariabIes
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 VariabIes Static VariabIes
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 vaIue the actuaI vaIues are passed as arguments to the caIIed
Iunction. These actuaI vaIues are copied into the arguments oI the caIIed Iunction. The
changes that are made in the Iunction do not aIIect the actuaI vaIues.
#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 7/29/08, 5:22 PM 34
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers C.3S
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 caII by reIerence the address oI the actuaI parameters are passed as
arguments to the caIIed Iunction. The IormaI parameters are decIared as pointers. The
changes that are made to the IormaI parameters aIIect the actuaI 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 7/29/08, 5:22 PM 35
To get more please visit: http://www.creativeworld9.blogspot.com
C.36 Soved ueston lnpers
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 7/29/08, 5:22 PM 36
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers 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 itseII can be a member oI another structure.
A structure object can be a member oI another structure.
The syntax Ior a nested structure is as IoIIows:
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 7/29/08, 5:22 PM 37
To get more please visit: http://www.creativeworld9.blogspot.com
C.38 Soved ueston lnpers
(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 Iseek Iunction is used to move the IiIe pointer to the desired position in the IiIe.
This means random access to IiIes is made possibIe by the Iseek Iunction. This Iunction has
three arguments in its syntax. The syntax oI this Iunction is
Iseek (IiIepointer, oIIset, position);
The Iirst argument is the IiIe type pointer which points to the IiIe that we are currentIy
operating with.
The second argument oIIset speciIies the number oI bytes the IiIe pointer has to move.
The IiIe pointer can move either Iorward or backward, depending on the vaIue oI oII-
set. II the oIIset vaIue is positive it moves Iorward and iI it is negative it moves back-
ward. The vaIue oI the oIIset is oI Iong type.
The third argument position takes one oI the three integer vaIues. These vaIues have
speciIic meaning.
VaIue Meaning
0 Beginning oI the IiIe
1 Current position
2 End oI IiIe
ExampIes:
Iseek(Ip,m,0) -Ip moves m bytes Irom the starting oI the IiIe and points to (m1)th byte.
Iseek(Ip,-m,1) -Irom the current position move m bytes in backward direction.
Appendix-C.p65 7/29/08, 5:22 PM 38
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers C.39
Iseek(Ip,0,0) -go to the beginning oI the IiIe.
Iseek(Ip,-m.2) -move backward by m bytes Irom the end oI the IiIe.
OIIset cannot take negative vaIues when the position vaIue is 0 and the IiIe pointer
cannot take positive vaIues when the position vaIue is 2, as the IiIe pointer cannot go
beyond the end oI IiIe.
(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 7/29/08, 5:22 PM 39
To get more please visit: http://www.creativeworld9.blogspot.com
C.40 Soved ueston lnpers
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) {
PRmove 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 7/29/08, 5:22 PM 40
To get more please visit: http://www.creativeworld9.blogspot.com
Soved ueston lnpers 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 aIso caIIed partition exchange sort. This method is based on divide-and-
conquer technique, i.e., the entire Iist is divided into various partitions and sorting is again
and again appIied on the partitions.
In this method, the Iist is divided into two, based on an eIement caIIed the pivot eIement.
UsuaIIy, the Iirst eIement is considered to be the pivot eIement. Now, move the pivot eIe-
ment into its correct position in the Iist. The eIements to the IeIt oI the pivot are Iess than the
pivot whiIe the eIements to the right oI the pivot are greater than the pivot. The process is
repeated in each oI these partitions. This process proceeds tiII we get the sorted Iist oI
eIements. Let us understand this by an exampIe. Consider the Iist 74, 39, 35, 32, 97, 84.
1. We wiII take 74 as the pivot and move it to a position so that the new Iist becomes
39, 35, 32, 74, 97, 84.
2. Now take the partitioned Iist39, 35, 32. Let us take 39 as the pivot. Moving it to the
correct position gives35, 32, 39. ReappIying the process to the IeIt partition 35, 32,
we get 32, 35.
3. AppIy the process to the right partition oI 74. Taking 97 as the pivot and positioning it,
we get 84, 97.
4. AssembIing aII the eIements Irom each partition, we get the sorted Iist.
ALGORITHM FOR QUICK SORT
1. Start.
2. SeIect the Iirst eIement oI the array as pivot.
3. Position the pivot such that the eIements to the IeIt oI the pivot are Iess then the pivot and the
eIements to the right oI the pivot are greater than the pivot.
4. Consider the IeIt and right partition and repeat the steps 2 and 3.
5. Merge aII the partitions to get the sorted Iist oI eIements.
6. Stop.
(b) Analyze the worst case performance of Quick sort and compare with Selection sort.
The seIection oI the pivot pIays a vitaI roIe in determining the eIIiciency oI the quick sort.
The main reasons Ior this are the pivot may partition the Iist into two so that one partition
is much bigger than the other and the partition may be in an unsorted manner.
Appendix-C.p65 7/29/08, 5:22 PM 41
To get more please visit: http://www.creativeworld9.blogspot.com
C.42 Soved ueston lnpers
We wiII assume that the pivot partitions the Iist into two so that one oI the partitions has
no eIements whiIe the other has aII the other eIements. This is the worst case possibIe. Here,
the totaI number oI comparisons at the end oI the sort wouId have been:
(n1) (n2) (n3) ..211/2(n1)*n /(n2)1/2(n). This is equaI to O (n2).
Thus the eIIiciency oI the quick sort in its worst case is O (n2).
Efficiency of selection sort
You can easiIy understand Irom the aIgorithm that the Iirst pass oI the program does (n1)
comparisons. The next pass does (n2) comparisons, and so on. Thus, the totaI number oI
comparisons at the end oI the sort wouId be:
(n1) (n2) (n3) ..211/2(n1)*n /(n2)1/2(n). This is equaI to O (n2).
Thus the eIIiciency oI the seIection sort is O (n2).
Appendix-C.p65 7/29/08, 5:22 PM 42
To get more please visit: http://www.creativeworld9.blogspot.com

You might also like