balaguruswamy solved question papers 2006

73
1. (a) What is the difference between signed integer and unsigned integer in terms of memory and range? Type Memory Range 1. Signed In memory it occupies these are Integers 16 bits. Ranging from -32,678 to 32,677. 2. Unsigned In memory it occupies these are Integers 16 bits. Ranging from 0 to 65,535. For a 16 bit machine, a signed integer uses one for sign and 15 bits for the magnitude of the number. Unlike signed integer, unsigned integers use all the bits for the magnitude of the number and are always positive. Therefore, for a 16 bit machine, the range of unsigned integer numbers will be from 0 to 65,535. Signed integers are declared as signed int and unsigned integers are declared as unsigned int. Both of these two contain integer storage classes of 3 types, namely, short int, int, long int. (b) List the entire data types in ‘C’. What is the size of these data types? Storage representations and the machine instructions to handle constants differ from machine to machine. The variety of data types available allow the programmer to application as well as the machine. ‘C’ supports the following four classes of data types: 1. Primary or fundamental data types 2. Derived data types Appendix D D D Solved Question Papers C Programming and Data Structures (May/June 2006) SET 1

Upload: rajendra-acharya

Post on 04-Apr-2015

573 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Balaguruswamy Solved Question Papers 2006

1. (a) What is the difference between signed integer and unsigned integer in terms ofmemory and range?

Type Memory Range

1. Signed In memory it occupies these areIntegers 16 bits. Ranging from

-32,678 to 32,677.2. Unsigned In memory it occupies these are

Integers 16 bits. Ranging from0 to 65,535.

For a 16 bit machine, a signed integer uses one for sign and 15 bits for the magnitude of thenumber. Unlike signed integer, unsigned integers use all the bits for the magnitude of thenumber and are always positive. Therefore, for a 16 bit machine, the range of unsignedinteger numbers will be from 0 to 65,535.

Signed integers are declared as signed int and unsigned integers are declared as unsignedint. Both of these two contain integer storage classes of 3 types, namely, short int, int, longint.

(b) List the entire data types in ‘C’. What is the size of these data types?Storage representations and the machine instructions to handle constants differ frommachine to machine. The variety of data types available allow the programmer toapplication as well as the machine.‘C’ supports the following four classes of data types:1. Primary or fundamental data types2. Derived data types

����������DDDDD������������ ������

����������� ��� ��������������

������� �������

� !�"

Page 2: Balaguruswamy Solved Question Papers 2006

�#� ������������ ������

3. User-defined data types4. Empty data typesPrimary data types There are four fundamental data types, namely integer (int), character(char), floating point (float) double floating point (double).Derived data types Generally arrays, functions, structures and pointer will come underthe category of derived data types.User defined data types Type definition (type def ) enumerated data type (enum) are theuser defined data types. (Structures and unions also come under this category).Size of data types:-

Type Size (bits)

1. Char or signed char 82. Unsigned char 83. Int or signed char 164. Unsigned int 165. Short int (or) 8

Signed short int6. Long int (or) 32

Signed long int7. Float 328. Double 649. Long double 80

2. (a) Distinguish between getchar and scanf functions for reading strings.Getchar:-Reading a single character can be done by using the function getchar.

Syntax:- variable_name = getchar ( );

Variable_name is a valid ‘c’ name that has been declared as char type. When this statementis encountered, the computer waits until a key is pressed and then assigns this character asa value to getchar function. Since getchar is used on the right hand side of an assignmentstatement, the character value of getchar is in turn assigned to the variable_name on theleft. The getchar function may be called successively to read the characters contained in aline of text. Getchar accepts space character.

Scanf (“control strings”,arg1, arg2, ………… argn);

The control string specifies the field format in which the data is to be entered and thearguments arg 1, arg 2, arg n specify the address of locations where the data is stored.Scanf does not accept space character.

Page 3: Balaguruswamy Solved Question Papers 2006

������������ ������ �#$

(b) Write a program to count the number of words, lines and characters in a text.

#include<stdio.h>

main( )

{

char line[80],ctr;

int I,c,end=0,characters=0,words=0,lines=0;

printf(“\n key in text”);

printf(“give one space after each word \n”);

printf(“when completed press ‘enter’ \n\n”);

while (end==0)

{

c=0;

while((ctr=getchar())!=‘\n’)

line[c++]=ctr;

line[c]=‘\0’;

if(line[0]==‘\0’)

break;

else

{

words++;

for(i=0;line[i]!=‘\0’;i++)

if(line[i]==’ ‘ || line[i]==‘\t’)

words++;

}

Page 4: Balaguruswamy Solved Question Papers 2006

�#% ������������ ������

lines=lines+1;

characters=characters+strlen(line);

}

printf(“\n”);

printf(“\n number of lines=%d”, lines);

printf(“\n number of words=%d”,words);

printf(“\n number of characters=%d”,characters);

}

3. (a) What is a pointer? List out the reasons for using pointers.Pointer is a variable which holds the address of another variable, i.e. a pointer is, therefore,nothing but a variable that contains an address which is a location of another variable inmemory. Since a pointer is a variable, its value is also stored in the memory in anotherlocation.

Example: variable value addressquantity 179 5000

p 5000 5048

Let us assign the address of ‘quantity’ to a variable ‘p’ which is called a “pointer”.Reasons for using pointers are as follows:1. A pointer enables us to access a variable that is defined outside the function.2. Pointers are more efficient in handling the data tables.3. Pointers reduce the length and complexity of a program.4. They increase the execution speed.5. The use of a pointer array to character strings results in saving a data storage space in

memory.(b) Write a ‘C’ program to illustrate the use of indication operator “*” to access the

value pointed by a pointer.Key board in which the “Employee” structure consists of employee name, code,designation and salary. Construct an array of structures that stores ‘n’ employee’sinformation and write a program to carry out operations like inserting a new entry, deletingentry.

/*accessing variables using pointers*/

#include<stdio.h>

main( )

{

Page 5: Balaguruswamy Solved Question Papers 2006

������������ ������ �#&

int x,y;

int *ptr;

x=10 ;

ptr=&x ;

y=*ptr ;

printf(‘’ value of x is %d\n\n”,x);

printf(“%d is stored at address %u\n”,x,&x);

printf(“%d is stored at address %u\n”,*&x,&x);

printf(“%d is stored at address %u\n”,*ptr,ptr);

printf(“%d is stored at address %u\n”,y,&*ptr);

printf(“%d is stored at address %u\n”,ptr,&ptr);

printf(“%d is stored at address %u\n”,y,&y);

*ptr=25;

printf(“\n now x=%d\n”,x);

}

4. Write a C program to read the information from the keyboard in which the “Employee”structure consists of employee name, code, designation and salary. Construct an array ofstructures that stores n employees information and write a program to carry outoperations like inserting a new entry, deleting entry.

#include<stdio.h>

#include<string.h>

Struct employee

{

char ename[20];

int code;

char desi[20];

float salary;

Page 6: Balaguruswamy Solved Question Papers 2006

�#� ������������ ������

};

main()

{

int I,j,n,char n[20];

struct employee a[30],*B; /*pointer for new entry*/

printf(“enter number of employees”);

scanf(“%d”,&n);

printf(“enter employees name, code, designation,salary\n”);

for(i=0;i<n;i++)

{

scanf(“%s%d%s%f”,a[i].ename,&a[i].code],a[i].desi,&a[i].salary);

}

/*to insert a new entry*/

printf(“To insert a new entry”);

B=realloc(sizeof(struct employee));

printf(“enter employee name,code,designation and salary”);

scanf(“%s%d%s%f”,*B.enam,e,&*B.code,*B.desi,&*B.salary);

/*To delete an entry*/

printf(“enter employee name”);

scanf(“%s”,n);

for( i=0;i<n;i++)

{

if(strcmp(n,a[i].ename)=0)

{

for( j=0;j<n-1n;j++)

{

a[ j]=a[ j+1];

Page 7: Balaguruswamy Solved Question Papers 2006

������������ ������ �#'

}

}

}

a[ j]=*B;

if(strcmp(n,*B.ename)=0)

{

free(B);

}

}

5. (a) Explain the command line arguments. What are the syntactic constructs followedin ‘C’.Command line argument is the parameter supplied to a program when the program isinvoked.This parameter may represent a file name the program should process. Forexample, if we want to execute a program to copy the contents of a file named X_FILE toanother one name Y_FILE then we may use a command line like

c>program X_FILE Y_FILE

Program is the file name where the executable code of the program is stored. Thiseliminates the need for the program to request the user to enter the file names duringexecution.

The ‘main’ function can take two arguments called argc, argv and information containedin the command line is passed on to the program to these arguments, when ‘main’ is calledup by the system. The variable argv is an argument vector and represents an array ofcharacters pointers that point to the command line arguments. argc is an argument counterthat counts the number of arguments on the command line. The size of this array is equal tothe value of argc. In order to access the command line arguments, we must declare the‘main’ function and its parameters as follows:

main(argc,argv)

int argc;

char *arg[ ];

{

……….

……….

}

Generally arg[0] represents the program name.

Page 8: Balaguruswamy Solved Question Papers 2006

�#( ������������ ������

(b) Write a ‘C’ program to read the input file from command prompt, using commandline arguments.

#include<stdio.h>

main(int arg,char *argv[])

{

FILE *fp;

int I;

char word[15];

fp=fopen(arg[1],‘‘w”); /*to open file with name agr[1]*/

printf(“\n number of lines in command line = %d\n\n”,argc);

for(i=2;i<argc;i++)

fprintf(fp,””%s”,argv[i]); /*write to file argv[1]*/

fclose(fp);

/*writing contents of the file to screen*/

printf(“contents of %s file \n\n”,argv[1]);

fp=fopen(argv[1],‘‘r”);

for(i=2;i<argc;i++)

{

fscanf(fp,”%s”,word);

printf(“%s”,word);

}

fclose(fp);

printf(“\n\n”);

/*writing the arguments from memory*/

for(i=0;i<argc;i++)

printf(“%*s\n”,i*5,argv[i]);

}

Page 9: Balaguruswamy Solved Question Papers 2006

������������ ������ �#)

6. Define a data structure. What are the different types of data structures? Explain each ofthem with suitable example.Data structure is the Mathematical or logical organization of dataData structure operations are

1. Insertion2. Deletion3. Search4. Sorting5. Traversing

There are two types of data structures:

1. Linear data structure:

If there exists a linear relationship between elements present in data structure, then the data structure isknown as linear data structure.

These are mainly arrays, stacks, and queues.

ARRAYS: An array is a group of related data items that share a common name.

ex:-salary[10];

In this example ‘salary’ represent a set of salaries of a group of employees. A particular number isindicated by writing a number called Index number of subscript in brackets after the array name.The example salary[10] represent the salary of the tenth employee.

STACKS: It is a linear data structure in which insertion and deletion takes place from only oneend called top of the stack.

Example: Insert 10, 2, 15, 9, 6 with size = 4.

Fig. Set 1.6.(a)

In Fig. Set 1.6(a) the “arrow” mark indicates the current element that is inserted. If we try toinsert ‘6’ we come across overflow condition, i.e, overflow = size–1.

Delete the elements from above stack will be

Fig. Set 1.6 (b)

Page 10: Balaguruswamy Solved Question Papers 2006

�#"� ������������ ������

If we try to delete after top Fig. set 1.6 (b) = –1, we come across under flow.Stack is also known an LIFO (LAST-IN-FIRST-OUT) or pile or push down list.

QUEUES: It is a non linear data structure in which insertion takes place at the rear end and thedeletion takes place at the front end.

Example: Insert 10, 33 with size = 5.

Fig. set 1.6 (c)

Here the first arrow on the right side in queue I represents the front and the arrow on the downrepresents the rear side.If we want to insert elements more than the given size, then the condition is called overflowcondition, i.e. rear = size–1.Deletion of elements from above queue will be:

Fig. Set 1.6 (d)

After deleting 10, if we try to delete another element it will come across under flow condition, i.e. rear= –1 and front = 0.

2. NON LINEAR DATA STRUCTURES:

If there exists random relationship between the elements of a data structure, then that data structure iscalled non-linear data structure.

Trees and Graphs are known as non-linear data structures.

Page 11: Balaguruswamy Solved Question Papers 2006

������������ ������ �#""

TREE: A tree is either empty or it may have a special node or a set of branches. Each branch inturn represents a tree.

Example: Fig. set 1.6 (e)

5

2

4

3

9

7

6

8

Fig. set 1.6(e)

GRAPHS: Set of vertices and set of edges combined together is known as graph. It is denoted by(G (V, E)).

Example: Fig. set 1.6(f)

1

4

3 2

Fig. set 1.6(f)

V = {1, 2, 3, 4}

E = {(1,2), (1,3), (3,4), (2,4), (2,3)}

7. Write a ‘C’ program to insert and delete the elements from circular doubly linked list.

/* Circular linked list */

#include<stdio.h>

#include<alloc.h>

#define null 0

struct linked_list

{

Page 12: Balaguruswamy Solved Question Papers 2006

�#"� ������������ ������

struct linked_list *pre;

int data;

struct linked_list *next;

}*first,*fresh,*ptr,*last;

typedef struct linked_list node;

main()

{

int ch,a;

clrscr();

while(1)

{

printf(“\n MIAN MENU \n”);

printf(“1.insert element\n2.delete element\n3.viewcontents\n”);

printf(“4.exit\n”);

printf(“enter your choice\n”);

scanf(“%d”,&ch);

switch(ch)

{

case 1:fresh=malloc(sizeof(node));

printf(“enter the element to be inserted\n”);

scanf(“%d”,&fresh->data);

printf(“where do you want to insert\n”);

printf(“1.begining\n2.end\n3.middle\n”);

scanf(“%d”,&ch);

switch(ch)

{

Page 13: Balaguruswamy Solved Question Papers 2006

������������ ������ �#"$

case 1:

Ibegin(); break;

case 2:

Iend();break;

case 3:

printf(“enter position\n”);

scanf(“%d”,&a);

Imiddle(a);

break;

}

break;

case 2:

printf(“where do you want to delete\n”);

printf(“1.begining\n2.end\n3.required position\n”);

scanf(“%d”,&ch);

switch(ch)

{

case 1:

Dbegin();

break;

case 2:

Dend();

break;

case 3:

printf(“enter position\n”);

scanf(“%d”,&a);

Dmiddle(a);

break;

}

break;

case 3:

view();break;

Page 14: Balaguruswamy Solved Question Papers 2006

�#"% ������������ ������

case 4:

exit(1); break;

default:

printf(“wrong choice\n”); break;

}

}

getch();

}

/* Insertion function*/

Ibegin()

{

if(first==null)

{

first=fresh;

first->pre=first;

first->next=first;

last=first;

}

else

{

fresh->next=first;

first->pre=fresh;

first=fresh;

last->next=first;

}

}

Iend()

{

if(first==null)

{

first=fresh;

first->pre=first;

first->next=first;

last=first;

Page 15: Balaguruswamy Solved Question Papers 2006

������������ ������ �#"&

}

else

{

fresh->next=first;

last->next=fresh;

fresh->pre=last;

last=fresh;

first->pre=last;

}

}

Imiddle(int n)

{

int i=1;

if(first==null)

{

first=fresh;

first->pre=first;

first->next=first;

last=first;

}

else

{

ptr=first;

while(ptr->next!=first)

i++,ptr=ptr->next;

if(i<=n)

Iend();

else if(i>n)

{

for(i=1;i<n;i++)

ptr=ptr->next;

fresh->next=ptr->next;

ptr->next=fresh;

fresh->pre=ptr;

fresh->next->pre=fresh;

Page 16: Balaguruswamy Solved Question Papers 2006

�#"� ������������ ������

}

}

}

/* Deletion function */

Dbegin()

{

ptr=first;

if(ptr->next==first)

{

if(first==null)

{

puts(“list is empty,deletion not possible”);

return;

}

else

{

printf(“\nthe deleted element is %d\n”,ptr->data);

first=null;

last=null;

free(first);

}

}

else

{

printf(“\nthe deleted element is %d\n”,ptr->data);

first=ptr->next;

last->next=first;

first->pre=last;

free(ptr);

}

}

Dend()

{

Page 17: Balaguruswamy Solved Question Papers 2006

������������ ������ �#"'

ptr=first;

if(ptr->next==first)

{

if(first==null)

{

puts(“list is empty,deletion not possible”);

return;

}

else

{

printf(“deleted element is %d\n”,ptr->data);

first=null;

last=null;

free(first);

}

}

else

{

while(ptr->next!=last)

ptr=ptr->next;

printf(“\n deleted element is %d\n”,last->data);

free(last);

ptr->next=first;

first->pre=ptr;

last=ptr;

}

}

Dmiddle(int n)

{

int i;

ptr=first;

if(ptr->next==first)

{

if(first==null)

{

Page 18: Balaguruswamy Solved Question Papers 2006

�#"( ������������ ������

puts(“list is empty,deletion not possible”);

return;

}

else

{

printf(“\ndeleted element is %d\n”,ptr->data);

first=null;

free(first);

}

}

else

{

for (i=1;i<n-1;i++)

ptr=ptr->next;

fresh=ptr->next;

ptr->next=ptr->next->next;

ptr->next->pre=ptr;

printf(“\ndeleted element is %d\n”,fresh->data);

fresh->pre=null;

fresh->next=null;

free(fresh);

}

}

8. (a) Write a C program to search a tree for a given element in the integer array usingbinary search?

#include<stdio.h>

main()

{

int a[10],n,I,s,m,1,u,f=o;

printf(“enter the value of n”);

scanf(“%d”,&n);

printf(“enter n sorted elements”);

for(i=0;i<n;i++)

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

printf(“enter the searching element”):

Page 19: Balaguruswamy Solved Question Papers 2006

������������ ������ �#")

scanf(“%d”,&s);

1=0;

u=n-1;

while(1<=u)

{

m=(1+u)/2;

if(a[m]==s)

{

printf(“%d is found at %d position”,s,m+1);

f=1;

break;

}

else

if(s<a[m])

u=m-1;

else

1=m+1;

}

if(f=0)

printf(“element is not found”);

}

(b) Derivation of Time complexity of Binary Search-Analysis:

To analyze the time complexity of Binary Search, first we have to compute the number ofcomparisons expected for successful Binary search.

So, consider I, such that2i>= (N+1)

Thus, 2i-1-1 is the maximum number of comparisons that are left with first comparison.Similarly 2i-2-1 is maximum number of comparisons left with second comparison.

In general we say that 2i-k-1 is the maximum number of comparisons that are left after‘k’ comparisons. If the number of elements are left then the desired data item is obtainedby ith comparisons.

Thus, the maximum number of comparisons required for successful search is:

Cms= i

or Cms= log2 (N +1)

Page 20: Balaguruswamy Solved Question Papers 2006

�#�� ������������ ������

For unsuccessful search, the maximum number of comparisons:

Cms = Cmv

for, computing average number of comparisons ‘Cs’ indicates successful search.

Cs = C/N

C = i*2i - (20 + 21 + 22 +……..2(i-1))

= i + 2i (i-1)

Now, consider that the probability for searching a requested data item is 1/n, then,

Cs = (1 + 2i (1- i)/n)

Cs = [1+ (N +1)(log 2 (N +1)-1)]/n

Cs = log2 N (for large N)

It can be easily observed that for successful and unsuccessful search the expected numberof cases is given by:

Cs = C4 = O (log2 N)

It should be noted that Binary Search provides to be more efficient than the sequentialsearch. But when implemented with linked lists it would not be efficient.

On the basis of the above analysis the time complexity of Binary Search is:E(n) = [log2 n] +1, it is actually 2E(a) >n, that is O(log2 n).

Page 21: Balaguruswamy Solved Question Papers 2006

����������������� ��� ��� ����

���������������

�����

1. Write about space requirements for variables of different data types.1. C language is rich in its data types. The variety of data types available allows the

programmer to select the type appropriate to the needs to the application as well as themachine.ANSI C supports four classes of data types:

1. Primary data type. Example, Integral type, Floating point type.2. User-defined data type. Example, Main.3. Derived data type. Example, arrays, structures, functions.4. Empty data set.

All C compilers support four primary data types, namely (int), character (char), floating point(float) and double-precision floating point double. The primary data types in C are tabulated as follows:

PRIMARY DATA TYPES

INTEGRAL TYPEINTEGER CHARACTER

SIGNED TYPE UNSIGNED TYPE Signed char

int Unsigned int Unsigned char

Short int Unsigned short int

Long int Unsigned long int

FLOATIING DATA TYPE

Float Double Long Double

Page 22: Balaguruswamy Solved Question Papers 2006

���� ������������ ������

Size and Range of Basic Data Types

DATA TYPE RANGE OF VALUES

char –128 to 127

int –32,768 to 32,767

float 3.4 e –38 to 3.4 e +38

double 1.7 e –308 to 1.7 e +308

INTEGER TYPES: Integers are whole numbers with a range of values supported by a particular machine.Generally, integers occupy one word of storage, and word size of machines vary (typically, 16 or32 bits) the size of an integer that can be stored depends on the computer. A signed integer uses one bitfor sign (usually MSB) and 15 bits for magnitude of the number.

C has three classes of integer storage, namely short, int, long int, in both signed and unsigned forms.Usually the range of unsigned integer numbers will be from 0 to 65,535.

We declare long and unsigned integers to increase the range of values.

Size and Range of Data Types on a 16-Bit Machine.

Type Size(bits) Range

Char or signed char 8 –128 to 127

Unsigned char 8 0 to 255

Int or signed int 16 –32,768 to 32,767

Unsigned int 16 0 to 65,535

Short int or 8 –128 to 127

Signed short int

Signed short int

Unsigned short 8 0 to 255int

Long int or signed 32 –2,147,483,648 toShort int 2,147,483,647

Unsigned long int 32 0 to 4,294,967,295

Float 32 3.4E–38 to 3.4E+38

Double 64 1.7E–308 to1.7E+308 to

Long double 80 3.4E–4932 to1.1E+4932

Page 23: Balaguruswamy Solved Question Papers 2006

������������ ������ ����

FLOATING POINT TYPE: Floating point type numbers are defined in C by the keyword ‘float’. Whenthe accuracy provided by a float number is not sufficient the type double can be used to define thenumber.

CHARACTER TYPES: A single character can be defined as a character type data. Characters areusually stored in 8 bits. The qualifier signed or unsigned may be explicitly applied to character datatype.

2. The annual examination is conducted for 50 students for three subjects. Write a programto read the data and determine the following:(a) Total marks obtained by each student.(b) The highest marks in each subject and the Roll No. of the student who secured it.(c) The student who obtained the highest total marks.

#include<stdio.h>

Void main ()

{

Int i, j, n, m, rollno [4];

Float marks [50][4];

Printf (“number of students”);

Scanf (“%d”, &n);

For (i=0; i<n;i++)

{

Marks [3][4]=0;

Printf(“\n enter three scores of students%d\n”,i+1);

For(j=0; j<3; j++)

{

Scanf(“%f”, & marks[i] [ j]);

Marks[i][3]=marks[i][3]+marks[i] [ j];

}

//To find highest marks in each subject.

For(i=0; i<4; i++)

{

Marks[n][i]=marks[0] [ i];

For( j=1;j<n;j++)

{

If(marks[n][i]<marks[ j] [ i])

Page 24: Balaguruswamy Solved Question Papers 2006

��� ������������ ������

{

Marks[n][i]=marks[ j] [ i];

Roll no[i]=j;

}

}

}

For( i=0;i<n;i++)

{

Printf(“total marks obtained by %d student is%f\n”,i+1,marks[i][3]);

}

For( i=0; i<3; i++)

{

Printf(“the highest marks is %d subject is%f\n”, i+1,marks[n][i]);

Printf(“rollno\n”, rollno[ j]);

}

Printf(“the student %d secured highest marks are % f”,rollno[3],marks[n][3]);

Getch();

}

3. (a) Explain the way of defining, opening and closing a file. Also explain the differentmodes of operation.File is a data structure provided by C to handle input or output to a program through disks.Files are used to keep information safe for a long period.They are organized by giving each file a unique name.

The operations on files include: 1. Opening the file (to put or get information).

2. Reading information from the file.3. Writing information on to the file.4. Closing the file.

In order to do all the above operations we need the following handling functions:

Page 25: Balaguruswamy Solved Question Papers 2006

������������ ������ ���!

Function Name Operation

fopen () to open an existing file or to create a new one.

fclose() To close a file which is open.

Getch(), fscanf(), getw() To read the data from the file.

Putch(), fprintf(), putw() To write data to files.

Fseek() To position the file pointer to a desired place in thefile.

Ftell() To give (tell) the current position of the file.

Rewind() To position the file at the beginning.

FILE OPENING MODES AND THEIR MEANINGS:

File opening mode: Meaning

“w” create a file, if doesn’t exist delete the contents, ifthe file already exists.

“a” append (add) data to a file at the end, if the file doesnot exist, create the file.

“r” read data from the file if it exists. An error messagewill be produced, if the file doesn’t exist.

“r+” Read and write on the files.

“w+” Same as r+.

“a+” Adds read permission to a file which was openedin the “a" for working.

(b) Write a C program to read data from the keyboard, write it to a file called INPUT,again read the same data from the INPUT file, and display it on the screen.

#include<stdio.h>

main()

{

Char ch;

FILE *fp;

clrscr();

Fp=fopen[(“Input”,‘‘w”);

If(fp==NULL)

{

Printf(“file is not opened”);

exit(0);

Page 26: Balaguruswamy Solved Question Papers 2006

���� ������������ ������

}

While((ch=getchar())!=EOF)

{

putc(ch,fp);

}

fclose(fp);

fp=fopen(“Input”,‘‘r”);

while((ch=getc(fp)!=EOF)

printf(“%c”,ch)

}

4. (a). Distinguish between an array of structures and array within a structure. Give anexample of each.Array of structures is nothing but many structures with the same fields. It is a

collection of similar data types.Grouping structure variables into one array is referred to as an array of structures.

Examples: struct student

{

int marks 1;

int marks 2;

int marks 3;

}st;

If we declare a structure such that the fields has an array type declaration then array within astructure is defined. It enables the user to have decreased number of variables.

Example: struct student

{

int marks[3];

}st;

Example for array of structures

struct student

{

int rno;

char name[30];

float marks;

} s[10];

Page 27: Balaguruswamy Solved Question Papers 2006

������������ ������ ���"

Here s[10] represents array of structures. It consists of 10 student structures. The elements inthe structure can be accessed as

s[i]. rno

s[i].name

s[i].marks

Array index starts from 0 and ends at size–1.

(b). Write a C program using structure to create a library catalogue with the followingfields: Access number, Author’s name, Title of book, Year of publication,Publisher’s name, Price.

#include<stdio.h>

Struct library

{

Int acno;

Char aname[20];

Char tbook[40];

Int year;

Char pname[40];

Float price;

};

main()

{

Struct library s[50];

Int n;

Printf(“enter the number of entries”);

Scanf(“%d”,&n);

Printf(“enter the book details”);

For(I=0; I<=n; i++)

{

Scanf(“%d%s%s%d%s%f”,&s[i].acno,s[i].aname,s[i].tboo

k,&s[i].year,&s[i].pname,s[i].price);

}

Printf(“\n Library catalogue\n”);

Printf(“Access number\t author number\t title of book\t

Page 28: Balaguruswamy Solved Question Papers 2006

���# ������������ ������

year of put\t pub name \t price \n”);

For(i=1; i<=n; i++)

{

Printf(“%d\t%s\t%s\t%d\t%s\t%f\n”,s[i].acno,s[i].aname,s[i].

tbook,s[i].year,s[i].pname,s[i].price);

}

}

5. Write a C program to read information about the student record containing student’sname, student’s age and student’s total marks. Write the marks of each student in anoutput file.

#include<stdio.h>

main()

{

FILE *f,*p;

Char sname[20];

Int age,n;

Float tot;

Printf(“enter the number of students”);

Scanf(“%d”,&n);

F=fopen(“record”,‘‘w”);

For(i=0; i<=n; i++)

{

Printf(“enter student”s name, age and total”);

Scanf(“%s%d%f”,&sname,&age,&total);

Fprintf(f,”%s%d%f”,sname,&age,&tot);

}

Fclose(f);

F=fopen(“record”,”r”);

P=fopen(“total”,‘‘r”);

For(i=0; i<n;i++)

{

Fscanf(f,”%f”,&tot);

Fprintf(p,”%f”,tot);

}

Page 29: Balaguruswamy Solved Question Papers 2006

������������ ������ ���$

Fclose(f);

Fclose(p);

P=fopen(“total”,“r”);

For(i=0;i<=n;i++)

{

Fscanf(p,“%f”,& tot);

Printf(“% f”,tot);

}

}

6. Write a C program for implementation of various operations on circular queue.The operations that can be performed on circular queue are enq(), deq(), traverse().

#define size 3

Int rear=–1,front=0, n=0, a[size];

Enq(e)

Int e;

{

If((rear+1)%size==front&&n=size)

{

Printf(“overflow\n”);

}

Else

{

Rear=rear+1;

A[rear]=e;

N++;

}

}

Deq()

{

Int x;

If((rear+1)%size=front&&n==0)

{

Page 30: Balaguruswamy Solved Question Papers 2006

���� ������������ ������

Printf(“underflow\n”)’;

}

Else

{

X=a[front];

Front++;

N––;

Return(x);

}

}

Traverse()

{

Int I;

If(n!=0)

{

printf(“elements of circular queue:”);

for(i=front; i!=rear; i=(i+1)% size)

{

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

}

else

printf(“empty\n”);

main()

{

Int op,x,v;

Do

Printf(“menu”);

Printf(“1.enq”);

Printf(“2.deq”);

Printf(“3.traverse”);

Printf(“4.exit);

Printf(“enter your choice”);

Scanf(“%d,&op);

Switch(op)

{

Page 31: Balaguruswamy Solved Question Papers 2006

������������ ������ ���%

Case 1: printf(“enter data element”);

Scanf(“%d”,&x);

Enq(x);

Break;

Case 2: v=deq();

If(v!=0)

{

Printf(“deleted item=%d”,v);

}

Else

Printf(“empty\n”);

Break;

Case 3: Traverse();

Break;

Case 4: Exit(0);

}

While(1);

Getch();

}

7. Circular linked lists are usually setup with so called list header. What is the reason forintroducing such a header? Write functions to insert and delete elements for thisimplementation.A header in a linked list serves as the starting point to begin traversing the nodes of the list. Incase of circular list, the last node is linked back to the first node, thus forming a loop. In this case,if we begin traversing from the first node, after we search the end node, we will again come backto the first node. However, in a program there is no identification, which is the first node, whichis the last node, and so on. Thus, our program will go in an indefinite loop. To prevent this, aheader is introduced in such lists. The header will point to the first node of the list.With this, wecan know when we have to stop traversing.

Struct linkedlist *get_node()

{

Struct linkedlist *tempnode;

Tempnode=(struct linkedlist *)malloc(size of(structlinkedlist));

If(tempnode==NULL)

Page 32: Balaguruswamy Solved Question Papers 2006

���� ������������ ������

{

Printf(“\n memory allocation failed”);

Exit(1);

}

Return tempnode;

}

Struct linkedlist *insert_node(struct linkedlist *mynode, intelement)

{

Struct linkedlist *myheadernode,*tempnode,*thisnode,*lastnode;

Myheadernode=mynode;

Tempnode=get_node();

Tempnode� data=element;

If(mynode==NULL)

{

Myheadernode=tempnode;

Tempnode�next=myheadernode;

}

Else

{

Last node=thisnode=myheadernode;

While(thisnode�data<=element&&thisnode�next!=myheadernode)

{

Last node=thisnode;

Thisnode=thisnode�next;

}

If(thisnode�next==myhedernode && thisnode�data<=element)

{

Tmpnode�next=thisnode�next;thisnode�next=tempnode;

}

Else if(thisnode!=myheadernode)

{

Tempnode�next=thisnode;

Lastnode�next=tempnode;

}

Else

Page 33: Balaguruswamy Solved Question Papers 2006

������������ ������ ����

{

While(thisnode�next!=myheadernode)

Thisnode=thisnode�neat)

Tempnode�next=lastnode;

Thisnode�next=tempnode;

Return tempnode;

}} return myheadernode;

}

Struct linkedlist *delete_node(struct linkedlist *mynode, intelement)

{

Struct linkedlist *myheadernode, *tempnode, *thisnode,*lastnode;

Myheadernode=thisnode=lastnode=mynode)

{

Lastnode=thisnode;

Thisnode=thisnode�next;

}

If(lastnode==mynode && lastnode�data==element)

{

While(thisnode�next!=mynode)

Thisnode=thisnode�next;

Thisnode�next=lastnode�next;

Tempnode=lastnode�next;

Free(lastnode);

Return tempnode;

}

If(thisnode�data==element)

{

Tempnode=thisnode;

Lastnode�next= thisnode�next;

Free(tempnode);

Return myheadernode;

}

Printf(“\n no such element”);

Return my headernode;

}

Page 34: Balaguruswamy Solved Question Papers 2006

��� ������������ ������

8. (a) Explain the algorithm for exchange sort with a suitable example.We can also call exchange sort as bubble sort.

Algorithm Bubble (Arr, n)Arr is an array of n elements

1. Repeat for i = 0, 1, 2, 3,……n–1.2. Repeat for j = i+1 to n–1.3. if(Arr[i]>Arr[j]) then interchange Arr[i] and Arr[j] end if4. increment j by 1.5. end for6. end for7. print the sorted array Arr end bubble.

The idea of bubble sort is to repeat by moving the smallest element to the lowest index position inthe list. The process is clearly explained in the above algorithm.Example:-

15 18 3 9 12The first pass takes i = 1 and j = 2, 3, 4, 5. The value 15 is compared with 18 and net changed15>3, now values interchanged 3, 18,15, 9, 12.Since 3<9 and 3<12, so elements are not changedAfter the first pass, list is 3, 18, 15, 9 ,12In the second pass i = 2 and j = 3, 4, 5Values 18>15, so interchanged 3, 15, 18, 9,12Since 15>9, so interchanged 3, 9, 18, 15, 12Since 9<12, no change is required 3, 9, 18, 15, 12In the third pass i = 3 and j = 4, 5.Since 18>15, so interchanged 3, 9, 15, 18, 12Since 15>12, so interchanged 3, 9, 12, 18, 15In the fourth pass, i = 4 and j = 5Since 18>15, so interchanged 3, 9, 12, 15, 18Efficiency of bubble sort:No. of comparison in first pass = n–1No. of comparisons in second pass = n-2 and so on.

The total no. of comparisons(n-1)+(n-2)+(n-3)+………….+2+1=n(n+1)/2 = O(n2)

(b) Compare sort and exchange sort.Sorting refers to the operation of arranging records in some given order. Sorting can eitherbe internal or external. When sorting is done keeping the records in the main memory, it iscalled internal sorting. When sorting is done by keeping the records in external files onstorage devices like disks, tapes, etc., it is called external sorting.

We have different sorting algorithms to sort the data They are:Bubble sort(or) Exchange sort

Page 35: Balaguruswamy Solved Question Papers 2006

������������ ������ ���!

Insertion sort

Selection sort

Quick sort

Heap sort

Internal sorts

UV||

W||

Merge sort ¨ External sortsSorting time summary

Work case Average caseBubble sort O(n ^2) O(n^2)

Quick sort O(n ^ 2) O(n log n)

Insertion sort O(n ^2) O(n^2)

Selection sort O(n^2) O(n^2)

Merge sort O(n log n) O(n log n)

Heap sort O(n log n) O(n log n)

SELECTING A SORT:-

Bubble sort Good for small n (n<=100)

Quick sort Excellent for virtual memoryenvironment

Insertion sort Good for almost sorted data

Selection sort Good for partially stored dataand small n

Merge sort Good for external file sorting

Heap sort As efficient as quick sort in an averagecase and far superior to quick sort inwork case.

Page 36: Balaguruswamy Solved Question Papers 2006

����������������� ��� ��� ����

���������������

�����

1. (a) What is the purpose of break statement?Some times it is convenient to be able to exit from a loop other than by testing at the top orbottom. The ‘break’ statement provides an early exit from ‘for’, ‘while’ and ‘do-while’loops. This can be explained as follows.

Generally, looping job is executed until the given condition of loop statement is false.When the condition is false the loop is terminated. If we give ‘‘break’’ statement, the jobwill be terminated in the middle, irrespective to the given condition in looping.For Example,

Void main ( )

{

Int i;

For (i=1; i<=20; i++)

{

Printf ("%d", i);

If (i==5)

Break;

}

}

This will print the numbers from 1 to 5 but not 1 to 20. (b) Suppose a break statement is included within the innermost of several nested control

statements. What happens when break statement is executed?If a ‘‘break’’ statement included within the innermost of several nested control statements,are executed, the ‘‘break’’ would only exit from the loop counting it.

That is ‘‘break’’ will exit only a single loop and the statements which are in the nextouter loops of the program are executed. But it does not come to the end of program.This can be seen with following example.

For (------------)

{

Statement(s);

Page 37: Balaguruswamy Solved Question Papers 2006

������������� ���� ���

For (------------)

{

Statement (s);

If (condition)

Break;

}

Statement(s);

}

Here, the break is in the inner ‘‘for’’ loop. When it is executed, it comes to outer ‘‘for’’loop.

(c) Write a program to print the multiplication table up to with proper format.

/* program to print multiplication table */

#include<stdio.h>

#include<conio. h>

Void main()

{

Int I, m, n;

printf(‘‘enter no for which you want to print

Multiplication table and also enter upto how many

Values do you want to print it’’);

scanf(‘‘%d%d’’,&n,&m);

for(i=1; i<=m;; i++)

{

printf(‘‘%d*%d=%d’’,n,i,n*i);

printf(‘‘\n’’);

}

}

2. (a ) Write a program to demonstrate passing an array argument to a function. Considerthe problem of finding the largest of N numbers defined in an array.

#include<stdio.h>

#include<conio.h>

int largest(int x[], int m)

Page 38: Balaguruswamy Solved Question Papers 2006

���! ������������� ����

{

int i, max = x[0];

for(i=0; i<m; i++)

if(x[i]>max)

max = x[i];

return(max);

}

void main()

{

int A[20], n, 1;

printf(‘‘Enter no. Of values’’);

scanf(‘‘%d’’, &n);

printf(‘‘Enter values’’);

for(i = 0;i<n; i++)

scanf(‘‘%d’’, &A[i]);

1 = largest(A, n);

printf(‘‘largest value in array is %d’’, 1);

}

(b) Write a recursive function power (base, exponents) that when invoked returns baseexponent.

#include<stdio.h>

int power(int base, int exp)

{

int i = 0, p = 1;

while(exp>0)

{

p = p*base;

}

return(p);

}

void main()

Page 39: Balaguruswamy Solved Question Papers 2006

������������� ���� ���"

{

int b, e, 1;

printf(‘‘Enter base & exponent’’);

scanf(‘‘%d%d’’, &b, &e);

1=power(b, e);

printf(‘‘%d^%d = %d’’, b, e, 1);

}

3. The roots of a quadratic equation of the form ax2+bx+c = 0 are given by the followingequations:

X1 = – b + b2 -4ac

X2 = – b – b2 -4ac

The roots of a quadratic equation of the form ax2+bx+c = 0 are given by the followingequations:

X1 = –b+ b2 –4ac /2a

X2 = –b– b2 –4ac/2a

Write a function to calculate the roots. The function must use two pointer parameters, oneto receive the coefficients a, b and c and the other to send roots to calling function.

#include<stdio.h>

#include<math.h>

Roots(p,q)

float *p,*q;

{

*q=(–(*(p+1)+sqrt((*(p+1))*(*(p+1))–4*(*p)*(*(p+2))))/

(2*(*p));

*(q+1)=(–(*(p+1)-sqrt((*(p+1))*(*(p+1))–4*(*p)*(*(p+2))))/(2*(*p));

}

void main()

{

float A[3], R[2];

int i;

printf(‘‘Enter values for a, b, c’’);

Page 40: Balaguruswamy Solved Question Papers 2006

��#� ������������� ����

for(i=0; i< = 2; i++)

scanf(‘‘%f ’’,A+i);

Roots(A, R);

printf(‘‘root1 = %f’’, *(R+0));

printf(‘‘root2=%f ’’, *(R+1));

}

4. (a) Write a program to create an array of student structure objects and to find thehighest marks scorer. The fields in the student structure are: name, age and marks.

#include<stdio.h>

struct student

{

char name[15];

int age;

float marks;

}X[15];

void main()

{

int m, n;

float max;

printf(‘‘Enter no. of students’’);

scanf(‘‘%d’’,&n);

printf( ‘‘Enter student name, age,marks’’);

for(i = 0;i <m; i++)

scanf(‘‘%s%d%f’’,X[i].name, &X[i]. age, &X[i]. marks);

max=X[0].marks; n = 0;

for(i = 0; i<m; i++)

{

if(max<X[i].marks)

n = i;

}

printf(‘‘highest marks scorer is %s’’, X[n].name);

}

Page 41: Balaguruswamy Solved Question Papers 2006

������������� ���� ��#$

(b) How are structure elements stored in memory?1. Members of structure themselves are not variables. So, they do not occupy any memory

until they are associated with structure objects.2. When an object is created, a memory is created equal to the total memory occupied by

all its members individually.3. The elements are stored in consecutive memory blocks in main memory.

5. Write a program to read a ‘C’ program file and count the following in the complete‘C’ program.(a) Total number of statements(b) Total number of opening brackets.

#include<stdio.h>

void main()

{

FILE *f1;

int n = 0;

char c;

/*To count total number of statements*/

f1=fopen(‘‘file1’’,‘‘r’’);

while((c = getc(f1))! = EOF)

{

if(c ==‘;’)

n++;

}

printf("No. of statements = %d",n);

fclose(f1);

/*To count total number of opening brackets"*/

n = 0;

f1 = fopen(‘‘file1’’,‘‘r’’);

while((c = getc(f1))! = EOF)

{

if(c = =’{ ’)

n++;

}

printf(‘‘No. of opening brackets = %d’’, n);

Page 42: Balaguruswamy Solved Question Papers 2006

��#� ������������� ����

fclose(f1);

}

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

#include<stdio.h>

#define size 4

int A[10], n=0, front = 0, rear = -1;

Enque(e)

int e;

{

if((rear+1)%size==front&&n==size)

printf(‘‘Overflow......’’);

else

{

rear = (rear+1)%size;

A[rear] = e;

n++;

}

}

int dequeue()

{

int a;

if(front==(rear+1)%szie&&n==0)

{

printf("Underflow");

return(0);

}

else

{

a=A[front];

printf(‘‘Deleted item is %d’’,a);

n--;

Page 43: Balaguruswamy Solved Question Papers 2006

������������� ���� ��#�

front = (front+1)%size;

return(a);

}

}

Traversal()

{

int i;

if((rear+1)%size==front&&n==0)

printf("Circular queue is empty");

else

{

printf(‘‘elements in circular queue are..’’);

for(i = front;i! = rear;i = (i+1)%size)

printf(‘‘%d’’,A[i]);

printf(‘‘%d’’,A[i]);

}

}

main()

{

int i, n, ch;

do

{

printf(‘‘\t1.Enqueue\t2.Dequeue\t3.Traversal\t4.Exit’’);

printf(‘‘Enter ur choice’’);

scanf(‘‘%d’’,&ch);

switch(ch)

{

case 1:

printf(‘‘Enter element to enqueue’’);

scanf(‘‘%d’’,&n);

Enqueue(n);

Page 44: Balaguruswamy Solved Question Papers 2006

��## ������������� ����

break;

case 2:

dequeue();

break;

case 3:

Traversal();

break;

case 4:

exit(0);

default:

puts(‘‘Invalid choice’’);

}

}while(1);

}

7. Represent a doubly linked list using an array. Write routines to insert and delete elementsfor this representation.

/* Double linked list using array*/

#include<stdio.h>

#include<alloc.h>

struct node

{

int data;

struct node *next, *prev;

}*1, *new, *start;

Insert(x)

int x;

{ int loc, ch;

if(start==NULL)

{

start = malloc(sizeof(struct node));

start -> data = x;

start -> next = NULL;

Page 45: Balaguruswamy Solved Question Papers 2006

������������� ���� ��#%

start -> prev = NULL;

}

else

{

new = malloc(sizeof(struct node));

new -> data = x;

printf(‘‘enter your choice 1.insertion at starting 2.ending3.middle’’);

scanf(‘‘%d’’,&ch);

if(ch==1)

{

new - >prev = NULL;

new -> next = NULL;

start -> prev = new;

start = new;

}

else if(ch==2)

{

for(l = start; l-> next! = NULL;l = l->next;);

l -> next = new;

new -> prev = NULL;

new -> next = NULL;

}

else

{

printf(‘‘enter location to insert:’’);

scanf(‘‘%d’’,&loc);

for(1 = start,i = 1;i < loc–1; i++)

l = l - >next;

if(l==NULL)

{

puts(‘‘\a invalid location’’);

Page 46: Balaguruswamy Solved Question Papers 2006

��#� ������������� ����

break;

}

else

{

new -> next = 1 - > next;

new -> prev = 1;

1 -> next = new;

}

}

}

}

Delete()

{

int ch, i = 1, loc;

if(start == NULL)

{

printf(‘‘empty’’);

return;

}

if(start -> next = NULL&&start -> prev == NULL)

{

printf(‘‘deleted item %d’’, start -> data);

start = NULL;

return;

}

printf(‘‘1.deletion at starting 2.ending 3.req postion’’);

printf(‘‘enter your choice’’);

scanf("%d", &ch);

if(ch == 1)

{

p = start;

Page 47: Balaguruswamy Solved Question Papers 2006

������������� ���� ��#

start = start -> next;

start -> prev = NULL;

printf(‘‘deleted item id %d’’, p -> data);

free(p);

}

else if (ch == 2)

{

for(1 = start; 1 -> next -> next! = NULL; 1=1 -> next)

{

p = 1- > next;

1 -> next = NULL;

printf(‘‘deleted item is %d’’, p -> data);

free(p);

}

else

{

printf(‘‘enter location to delete:’’);

scanf(‘‘%d’’, & 1oc);

for(1 = start; i< 1oc –1; 1 = 1 -> next)

i++;

if(1 == NULL)

{

puts (‘‘invalid location’’):

return;

}

p = 1 -> next;

1 -> next = 1 -> next -> next;

1 -> next -> prev = 1;

printf(‘‘deleted item is%d’’,p->data);

free(p);

}

Page 48: Balaguruswamy Solved Question Papers 2006

��#! ������������� ����

}

main()

{

int ch, n;

do

{

printf(‘‘\n1.Insert 2.Delete 3.Exit’’);

printf(‘‘Enter ur choice’’);

scanf(‘‘%d’’,&ch);

switch(ch)

{

case 1:

printf(‘‘Enter element to insert’’);

scanf(‘‘%d’’,&n);

Insert(n);

break;

case 2:

Delete();

break;

case 3:

exit(0);}

}while(1);

}

8. Write an algorithm for two-way merge sort. Analyze its time complexity.

#include<stdio.h>

#define max 20

int a[max], b[max];

main( )

{

int i, n;

printf(‘‘enter the value of n’’);

Page 49: Balaguruswamy Solved Question Papers 2006

������������� ���� ��#"

scanf(‘‘%d’’, &n);

for(i = 0;i < n; i++)

scanf(‘‘%d’’, &a[i]);

mergesort(0, n);

printf(‘‘sorted list is’’);

for(i = 0;i < n; i++)

printf(‘‘%d’’, a[i]);

}

/* merge sort function */

mergesort(low,high)

int low, high;

{

int mid;

if(low < high)

{

mid = (low+high)/2

merge sort(low, mid);

mergesort(mid+1, high);

merge(low, mid, high);

}

}

merge(low, mid, high)

int low, mid, high;

{

int i, h, j;

h = low, i = low, j = mid+1;

while((h < = mid)&&( j < = high))

{

if(a[h]<=a[j])

{

b [i] = a[h];

Page 50: Balaguruswamy Solved Question Papers 2006

��%� ������������� ����

h = h+1;

}

else

{

b[i] = a[j ];

j = j+1;

}

i = i+1;

}

if(h > mid)

for(k = j;k < high; k++)

{

b[i] = a[k];

i++;

}

else

for(k = h; h < mid; h++)

{

b[i] = a[k];

i++;

}

for(k = low; k < high; k++)

a[k] = b[k];

}TIME COMPLEXITY: If the time for the merging operation is proportional to n, then the computing timefor merge sort is described by the recurrence relation.

T (n) = { a n = 1, a a constant

aT (n /2)+cn n > 1 , c a constant

Page 51: Balaguruswamy Solved Question Papers 2006

������������� ���� ��%$

When n is a power of 2 , n = 2^k, we can solve this equation by successive substitutions:

T (n) = 2(2T(n /4)+cn /2)+cn

= 4T(n/4)+2cn

= 4(2T (n / 8)+cn /4)+2cn

::

= 2^kT (1)+kcn

= an + cnlog n

It is easy to see that if 2^k < n < = 2^(k+1), then T(n) < = T (2^k+1).Therefore,

T (n) = O(nlogn).

Page 52: Balaguruswamy Solved Question Papers 2006

1. (a) What is meant by operator precedence? What are the relative Precedence of thearithmetic operators ?Each operator in ‘C’ has a precedence associated with it. This Precedence is used todetermine how an expression involving more than one operator is evaluated. There aredistinct levels of precedence and an operator may belong to one of these levels. Therelative precedence of arithmetic operators can be given from two distinct levels, they are

HIGH PRIORITY: * , / , %LOW PRIORITY: +, –

The basic evaluation procedure includes two left to right passes during the first pass , thehigh priority operators are applied as they are Encountered during the second pass, the lowpriority operators are applied as they are encountered.

(b) What is the associativity of the arithmetic operators?

Arithmetic operators are *, /, +, –, %.

Operator Description Associativity

+ Addition Left to right

– Subtraction Left to right

* Multiplication Left to right

/ Division Left to right

% Modulus Left to right

(c) How can the value of an expression be converted to a different data Types?

The conversion of data from one form to another form is called type conversion.Automatic type conversion:

����������������� ��� ��� �������������������

�����

Page 53: Balaguruswamy Solved Question Papers 2006

������������� ���� �� !

If the operands are different types, the ‘lower’ type is automatically converted to the‘higher’ type . The result is of the higher type.

Ex:int female;float male, ratio;ratio= female/male;

Casting of values:

The values of an expression can be converted into different data types by casting the value.Consider the following example:Since female and male are declared as integers in program the decimal part of the result ofthe division would be lost and the ratio would represent a wrong figure. This problem cansolved by converting one of the variables locally to floating point.

int female, male;float ratio;ratio=(float)female/male;

The result will be converted into float. The process of such a local conversion is known ascasting of value. The general form is:

(data type name) expression.(d) What are unary operator? Explain example for each.

The unary operators are the operators which require only one operand to perform theoperation. The unary operators are

(1) ! –logical not Eg: a !a

T FF T

(2) Short hand assignment operators:Eg: a+ = works as a = a+1

a– =1 works as a = a-1a*=1 works as a = a*1

a/=1 works as a = a/1

(3) Increment and decreament operators:Eg: let m = 5 and result be stored in y.

m = 5m++; //m = m+1//

resultant m = 6m = 5;–m; //m=m–1//

Resultant m = 4.

(4) Bitwise left shift operator, bitwise right shift operator(a) suppose a =4

A<<2 . if left shifts the binary bits twice.

Page 54: Balaguruswamy Solved Question Papers 2006

�� � ������������� ����

So a = 00010000

(b) suppose a>>2 . if right shifts the binary bits twice. so a = 00000001

(5) size of operator.Eg: suppose a is declared as integer. The size of a is

Int a;x = size of (a);x = 2.

2. (a) In what way array is different from an ordinary variable?An array is a collective name given to a group of similar elements whereas a variable isany entity that may change during program execution. An array is a variable that is capable of holding many values where as an ordinary variablecan hold a single value at a time. For example, an array initialization would be

Int number [8];for which there are 8 storage locations reserved where 8 different values can be storedbelonging to the same type.An ordinary variable initialization would beInt number; & only one storage location is reserved and can hold only one value at a time.

(b) What conditions must be satisfied by the entire elements of any given Array?Elements of an array can be initialized at the time & place of their declaration. Consider an

array with it’s elements.Int a [4] = {1,2,3,4};

In the above example, 4 elements are stored in array ‘a’ The array elements are storedin continuous memory locations.The array elements are read from ‘0’ i.e a [0], is assigned the value ‘1’, similarily a [1] isarranged the value ‘2’,a [2] is assigned ‘3’.

The condition that needs to be satisfied is that, all the elements of the array must be ofthe same data type under which the array is declared

(c) What are subscripts? How are they written? What restrictions apply to the Valuesthat can be assigned to subscripts?Subscript of an array is an integer expression, integer constant or integer variable like ‘i’,‘n’ etc that refers to different elements inthe array. Consider a statement

int a[5];here, array subscripts start at 0 in c-language. Therefore the elements are a [0], a [1],………a [4].

The values that can be assigned to the subscripts always must start from ‘0’ and it endsat “size of array-1” for example consider the array

int a[5]here the range of subscripts starts from ‘0’ and it ends at ‘4’.

Page 55: Balaguruswamy Solved Question Papers 2006

������������� ���� ��

(d) What advantages is there in defining an array size in terms of a symbolic constantrather than a fixed integer quantity?The advantage of defining the size of an array using symbolic constant instead of fixednumbers is that, by defining the symbolic constant at the beginning of the program, itallows us to know the maximum size of the array and in future if we want to change thesize of the array, it can be easily done by modifying the definition of the symbolic constantwhich gets reflected throughout the program.

(e) Write a program to find the largest element in an array./*program to find largest element in an array */

#include<stdio.h>

#include<conio.h>

main()

{

int l,a[10],I,n;

printf(“enter number of elements in the array”);

scanf(“%d”,&n);

printf(“enter the array elements”);

for(i=0;i<n;i++)

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

l=a[0];

for (i=o;i<n;i++)

{

if (l<a[i])

l=a[i];

}

printf(“the largest element is %d”,l);

getch();

}

Page 56: Balaguruswamy Solved Question Papers 2006

�� � ������������� ����

3. (a) Write a ‘C’ program to compute the sum of all element stored in an arrayUsing pointers.

/*program to compute sum of all elements stored in anarray */

#include<stdio.h>

#include<conio.h>

main()

{

int a[10],I,sum=0,*p;

printf(“enter 10 elements \n”);

for(i=0; i<10;i++)

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

p = a;

for(i = 0; i<10; i++)

{

sum = sum*p;

p++;

}

printf(“the sum is % d”,sum);

getch();

}

(b) Write a ‘C’ program using pointers to determine the length of a character String.

/*program to find the length of a char string */

#include<stdio.h>

#include<conio.h>

#include<string.h>

main()

{

Char str [20].*p;

Int l=0;

printf(“enter a string \n”);

scanf (“ % s”,str);

p=str;

while(*p!=’\0’)

{

Page 57: Balaguruswamy Solved Question Papers 2006

������������� ���� �� "

l++;

p++;

}

printf(“the length of the given string is %d”,l);

getch();

}

4. (a) Explain the different ways of passing structure as arguments in functions .There are different ways of passing structure as an argument to functions.They are

1. Passing structure members individually: each member of the structure can be passedindividually as arguments in the function call and retained through return statement.

Ex: #include<stdio.h>

struct x

{

int a;

char b;

} P;

main()

{

struct x,m;

printf(“enter a,b values”);

scanf(“%d%c”,&n.a,&m.b) ;

fun(i,c)

int i ;

char c ;

{

printf(“a = % d\t b=% d ‘’, I,c);

}

2. A copy of complete structure can be passed as argument using this method, a copy of entirestructure is passed to function but any modifications made to it will not reflected in thecalled function.eg: consider a structure x,which has two members, one integer type and the other charactertype. We can pass the entire structure to a function as follows.

Page 58: Balaguruswamy Solved Question Papers 2006

�� # ������������� ����

#include<stdio.h>

struct x

{

int a;

char b;

}

main()

{

struct x,m;

printf(“enter values of a & b”);

scanf(“%d%c”,&m.a,&m.b);

fun(m);

}

fun(y)

struct x y ;

{

printf(“a=%d b=%c”,y.a,y.b) ;

}3. By passing the address of the structure to the called function. This method is more efficient

than the above method because the structure need not be returned to called function. In thisapproach, the address location of the structure is passed to called function.

ex:

#include<stdio.h>

struct marks

{

float avg;

int m[3],tot;

}*p

main()

{

struct marks student;

printf(“enter 3 subject marks”);

for(“i=0;i<2;i++)

scanf(“%d”,&student.m[i]);

total(&student,3);

Page 59: Balaguruswamy Solved Question Papers 2006

������������� ���� �� $

printf(“%d is total and %f is avg”,student.total ,student.avg);

}

total(student ,n)

struct marks *student;

int n;

{

int I,t=0;

for(i=0;i<n;i++)

t=t+m[i];

student—tot=t;

student—avg=t/n;

}

(b) Write a ‘C’ program using pointers to determine the length of a characterString./*program to illustrate the method of sending the entire structure as a parameter to function*/

#include<stdio.h>

struct marks

{

int m[3],tot;

float avg;

}

main()

{

struct marks mk1;

void total(struct marks,int);

mk1.m[0]=50;

mk1.m[1]=70;

mk1.m[2]=80;

mk1.tot=0;

mk1.avg=0;

mk1=total(mk1,3);

printf(“total=%d,average=%f”,mk1.tot,mk1.avg);

Page 60: Balaguruswamy Solved Question Papers 2006

���� ������������� ����

}

struct marks total(struct marks mk2,intn)

{

int t=0;

for (i=0;i<n;i++)

t = t+m[i];

mk2.to t= t;

mk2.avg=t/n;

return(mk2);

}

5. (a) Distinguish text mode and binary mode operation of file.

Text Mode Binary Mode

1. In this mode file is opened 1. We can perform binary Operations byFor one purpose. opening a file in this mode.

2. “r” opens the file for reading 2. “r+” opens the existing File for both readingOnly. and writing.

3. “w” opens the file for writing 3. “w+” is same as write mode but for both readOnly. and writing .

4. “a” opens the file for appending 4. “a+” same as ‘a’ except for both reading anddata to it. writing.

(b) Write a program to open a pre-existing file and add information at the End of a file.Display the contents of the file before and after appending.

#include<stdio.h>

#include<conio.h>

main()

{

char x;

fILE *f;

f=fopen(“data”,‘‘r”);

while(x=getc(f)!=EOF)

printf(“%c”,x);

fclose(f);

Page 61: Balaguruswamy Solved Question Papers 2006

������������� ���� ���%

f = fopen(“data”,‘‘a”);

while((x=getchar())!=EOF)

putc(x,f);

fclose(f);

f = fopen(“data”,‘‘r”);

while((x=getc(f))!=EOF)

printf(“%c”,x);

getch();

}

6. Write a ‘C’ program using pointers to implement a stack with all the operations.

#include<stdio.h>

#include<conio.h>

Int size;

struct stack

{

Int a[max];

Int top;

};

void stk(struct stack *st)

{

st->top = –1;

}

void push(struct stack *st,int num)

{

If(st->top == size–1)

{

printf(“\n over flow\n”);

return;

}

st->top++;

st->a[st->top]=num;

}

Int pop(stuct stack *st)

{

Int num;

Page 62: Balaguruswamy Solved Question Papers 2006

���� ������������� ����

If(st->top==-1)

{ printf(“stack is under folw\n”);

return NULL;

}

num=st->a[st->top];

st->top—;

return num;

}

void display(struct stack *st)

{

Int i;

for(i=st->top;i>=0;i—)

printf(“\n %d\t”,st->a[i]);

}

void main()

{

Int d,i,n;

struct stack *ptr;

do

{

printf(“\n menu items\n1.push \t 2.pop\t3.display\t4.exit\n”);

printf(“enter your choice:”);

scanf(“%d”,&i);

switch(i)

{

case 1: printf(“enter an element:”);

scanf(“%d”,&n);

push(&ptr,n);

break;

case 2: d=pop(&ptr);

printf(“\n deleted item %d”,d);

break;

case 3: printf(“elements of the stack are \n”);

display(&ptr);

Page 63: Balaguruswamy Solved Question Papers 2006

������������� ���� ���!

break;

case 4: exit (0);

default: printf(“invalid choice”);

}

}

getch();

}7. Write a routine SPLIT() to split a singly linked list into two lists so that all elements in

odd position are in one list and those in even position are in another list.

/* Implementation of linked list including split operation*/

#include<stdio.h>

#include<alloc.h>

#define null 0

struct linked_list

{

int data;

struct linked_list *next;

}*first,*fresh,*ptr,start1,ptr1,start2,ptr2;

typedef struct linked_list node;

main()

{

int ch,a;

clrscr();

while(1)

{

printf(“\n MAIN MENU \n”);

printf(“1.insert element\n”);

printf(“2.delete element\n”);

printf(“3.view contents\n”);

printf(“4.split\n”);

printf(“5.exit from program\n”);

printf(“enter your choice\n”);

scanf(“%d”,&ch);

switch(ch)

{

Page 64: Balaguruswamy Solved Question Papers 2006

���� ������������� ����

case 1:

fresh=malloc(sizeof(node));

printf(“enter the element to be inserted\n”);

scanf(“%d”,&fresh->data);

printf(“where do you want to insert\n”);

printf(“1.begining\n2.end\n3.middle\n”);

scanf(“%d”,&ch);

switch(ch)

{

case 1:

Ibegin();

break;

case 2:

Iend();

break;

case 3:

printf(“enter position\n”);

scanf(“%d”,&a);

Imiddle(a);

break;

}

break;

case 2:

printf(“where do you want to delete\n”);

printf(“1.begining\n2.end\n3.required position\n”);

scanf(“%d”,&ch);

switch(ch)

{

Page 65: Balaguruswamy Solved Question Papers 2006

������������� ���� ���

case 1:

Dbegin();

break;

case 2:

Dend();

break;

case 3:

printf(“enter position\n”);

scanf(“%d”,&a);

Dmiddle(a);

break;

}

break;

case 3:

clrscr();

break;

case 4:

split();

break;

case 5:

exit(0);

default:

printf(“wrong choice\n”);

break;

}

}

getch();

}

/* Insertion function */

Ibegin()

{

if(first==null)

Page 66: Balaguruswamy Solved Question Papers 2006

���� ������������� ����

{

first=fresh;

first->next=null;

}

else

{

fresh->next=first;

first=fresh;

}

}

Iend()

{

if(first==null)

{

printf(“list is empty, inserted element is the last/first\n”);

first=fresh;

first->next=null;

}

else

{

ptr=first;

while(ptr->next!=null)

ptr=ptr->next;

ptr->next=fresh;

fresh->next=null;

}

}

Imiddle(int n)

{

int i;

if(first==null)

{

printf(“list is empty, inserted element is the last/first\n”);

first=fresh;

first->next=null;

Page 67: Balaguruswamy Solved Question Papers 2006

������������� ���� ���"

}

else

{

ptr=first;

for(i=1;i<n;i++)

ptr=ptr->next;

fresh->next=ptr->next;

ptr->next=fresh;

}

}

/* Deletion function */

Dbegin()

{

ptr=first;

if(ptr->next==null)

{

if(first==null)

{

puts(“list is empty,deletion not possible”);

return;

}

else

{

printf(“list contains only one element and now it is emptydue to deletion\n”);

first=null;

free(first);

}

}

else

first=ptr->next;

free(ptr);

}

Dend()

{

ptr=first;

Page 68: Balaguruswamy Solved Question Papers 2006

���# ������������� ����

if(ptr->next==null)

{

if(first==null)

{

puts(“list is empty,deletion not possible”);

return;

}

else

{

printf(“list contains only one element and now it is emptydue to deletion\n”);

first=null;

free(first);

}

}

else

{

while(ptr->next->next!=null)

ptr=ptr->next;

free(ptr->next->next);

ptr->next=null;

}

}

Dmiddle(int n)

{

int i;

ptr=first;

if(ptr->next==null)

{

if(first==null)

{

puts(“list is empty,deletion not possible”);

return;

}

else

Page 69: Balaguruswamy Solved Question Papers 2006

������������� ���� ���$

{

printf(“list contains only one element and now it is emptydue to deletion\n”);

first=null;

free(first);

}

}

else

{

for(i=1;i<n-1;i++)

ptr=ptr->next;

fresh=ptr->next;

ptr->next=ptr->next->next;

fresh->next=null;

free(fresh);

}

}

view()

{

ptr=first;

if(ptr->next==null)

{

if(first==null)

{

puts(“list is empty”);

return;

}

else

{

printf(“%d”,first->data);

}

}

else

{

for(ptr=first;ptr->next!=null;ptr=ptr->next)

Page 70: Balaguruswamy Solved Question Papers 2006

��"� ������������� ����

printf(“%d->”,ptr->data);

printf(“%d”,ptr->data);

}

}

/* split function */

split()

{

ptr=first;

ptr1=start1;

ptr2=start2;

while(ptr->next!=null)

{

if(start1==null)

{

start1=ptr;

ptr=ptr->next;

start1->next=null;

}

else

{

ptr1->next=ptr;

ptr1=ptr;

ptr=ptr->next;

ptr1->next=null;

}

if(start2==null)

{

start2=ptr;

ptr=ptr->next;

start2->next=null;

}

else

{

ptr2->next=ptr;

ptr2=ptr;

Page 71: Balaguruswamy Solved Question Papers 2006

������������� ���� ��"%

ptr=ptr->next;

ptr2->next=null;

}

}

/* printing the two lists */

ptr1=start1;

ptr2=start2;

printf(“EVEN LIST IS\n”);

while(ptr1->next!=null)

{

printf(“%d\t”,ptr1->data);

ptr1=ptr1->next;

}

printf(“ODD LIST IS\n”);

while(ptr2->next!=null)

{

printf(“%d\t”,ptr2->data);

ptr2=ptr2->next;

}

}

8 . Write a ‘C’ program to sort a given list of elements using tree sort and discuss itstime complexity.

#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++)

{

Page 72: Balaguruswamy Solved Question Papers 2006

��"� ������������� ����

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;

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;

Page 73: Balaguruswamy Solved Question Papers 2006

������������� ���� ��"!

Root=max;

}

Else

Flag=1;

}}

TIME COMPLEXITY:-

A complete binary tree which is a heap with ‘m’ nodes will have ‘log(m+1)’ levels. Thus we may havean efficiency of O(mlogm). So, for heapsort both the average case and worst case time complexity are ofthe order of ‘mlogm’.