You are on page 1of 73

Appendix

D
Solved Question Papers
C Programming and Data Structures
(May/June 2006)

SET 1
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
D.2 Solved Question Papers

3. User-defined data types


4. Empty data types
Primary 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 under
the category of derived data types.
User defined data types Type definition (type def ) enumerated data type (enum) are the
user defined data types. (Structures and unions also come under this category).
Size of data types:-

Type Size (bits)


1. Char or signed char 8
2. Unsigned char 8
3. Int or signed char 16
4. Unsigned int 16
5. Short int (or) 8
Signed short int
6. Long int (or) 32
Signed long int
7. Float 32
8. Double 64
9. 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 statement
is encountered, the computer waits until a key is pressed and then assigns this character as
a value to getchar function. Since getchar is used on the right hand side of an assignment
statement, the character value of getchar is in turn assigned to the variable_name on the
left. The getchar function may be called successively to read the characters contained in a
line 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 the
arguments arg 1, arg 2, arg n specify the address of locations where the data is stored.
Scanf does not accept space character.
Solved Question Papers D.3

(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++;

}
D.4 Solved Question Papers

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 in
memory. Since a pointer is a variable, its value is also stored in the memory in another
location.
Example: variable value address
quantity 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’s
information and write a program to carry out operations like inserting a new entry, deleting
entry.
/*accessing variables using pointers*/

#include<stdio.h>

main( )

{
Solved Question Papers D.5

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 of
structures that stores n employees information and write a program to carry out
operations 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;
D.6 Solved Question Papers
};

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];
Solved Question Papers D.7
}

}
}
a[ j]=*B;
if(strcmp(n,*B.ename)=0)
{
free(B);
}
}
5. (a) Explain the command line arguments. What are the syntactic constructs followed
in ‘C’.
Command line argument is the parameter supplied to a program when the program is
invoked.This parameter may represent a file name the program should process. For
example, if we want to execute a program to copy the contents of a file named X_FILE to
another 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. This
eliminates the need for the program to request the user to enter the file names during
execution.
The ‘main’ function can take two arguments called argc, argv and information contained
in the command line is passed on to the program to these arguments, when ‘main’ is called
up by the system. The variable argv is an argument vector and represents an array of
characters pointers that point to the command line arguments. argc is an argument counter
that counts the number of arguments on the command line. The size of this array is equal to
the 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.
D.8 Solved Question Papers

(b) Write a ‘C’ program to read the input file from command prompt, using command
line 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]);
}
Solved Question Papers D.9

6. Define a data structure. What are the different types of data structures? Explain each of
them with suitable example.
Data structure is the Mathematical or logical organization of data
Data structure operations are
1. Insertion
2. Deletion
3. Search
4. Sorting
5. 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 is
known 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 is
indicated 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 one
end 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 to
insert ‘6’ we come across overflow condition, i.e, overflow = size–1.
Delete the elements from above stack will be

Fig. Set 1.6 (b)


D.10 Solved Question Papers

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 the
deletion 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 down
represents the rear side.
If we want to insert elements more than the given size, then the condition is called overflow
condition, 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 is
called non-linear data structure.
Trees and Graphs are known as non-linear data structures.
Solved Question Papers D.11

TREE: A tree is either empty or it may have a special node or a set of branches. Each branch in
turn represents a tree.
Example: Fig. set 1.6 (e)

5 4 7

2 3 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)

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

{
D.12 Solved Question Papers
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.view
contents\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)
{
Solved Question Papers D.13
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;
D.14 Solved Question Papers
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;
Solved Question Papers D.15

}
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;
D.16 Solved Question Papers

}
}
}

/* 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()
{
Solved Question Papers D.17

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)
{
D.18 Solved Question Papers

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 using
binary 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”):
Solved Question Papers D.19

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 of
comparisons expected for successful Binary search.
So, consider I, such that
2i>= (N+1)
i-1
Thus, 2 -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 obtained
by ith comparisons.
Thus, the maximum number of comparisons required for successful search is:
Cms= i
or Cms= log2 (N +1)
D.20 Solved Question Papers

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 number
of cases is given by:
Cs = C4 = O (log2 N)
It should be noted that Binary Search provides to be more efficient than the sequential
search. 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).
C Programming and Data Structures
(May/June 2006)

SET 2

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 the
machine.
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 TYPE
INTEGER 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


D.22 Solved Question Papers

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 or
32 bits) the size of an integer that can be stored depends on the computer. A signed integer uses one bit
for 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 255
int
Long int or signed 32 –2,147,483,648 to
Short 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 to
1.7E+308 to
Long double 80 3.4E–4932 to
1.1E+4932
Solved Question Papers D.23
FLOATING POINT TYPE: Floating point type numbers are defined in C by the keyword ‘float’. When
the accuracy provided by a float number is not sufficient the type double can be used to define the
number.

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

2. The annual examination is conducted for 50 students for three subjects. Write a program
to 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])
D.24 Solved Question Papers

{
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 different
modes 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:
Solved Question Papers D.25

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 the
file.
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, if
the file already exists.
“a” append (add) data to a file at the end, if the file does
not exist, create the file.
“r” read data from the file if it exists. An error message
will 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 opened
in 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);
D.26 Solved Question Papers

}
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 an
example 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 a
structure 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];
Solved Question Papers D.27

Here s[10] represents array of structures. It consists of 10 student structures. The elements in
the 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 following
fields: 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
D.28 Solved Question Papers

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’s
name, student’s age and student’s total marks. Write the marks of each student in an
output 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);
}
Solved Question Papers D.29

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)

{
D.30 Solved Question Papers

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)
{
Solved Question Papers D.31

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 for
introducing such a header? Write functions to insert and delete elements for this
implementation.
A header in a linked list serves as the starting point to begin traversing the nodes of the list. In
case 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 back
to the first node. However, in a program there is no identification, which is the first node, which
is the last node, and so on. Thus, our program will go in an indefinite loop. To prevent this, a
header is introduced in such lists. The header will point to the first node of the list.With this, we
can know when we have to stop traversing.
Struct linkedlist *get_node()
{
Struct linkedlist *tempnode;
Tempnode=(struct linkedlist *)malloc(size of(struct
linkedlist));
If(tempnode==NULL)
D.32 Solved Question Papers

{
Printf(“\n memory allocation failed”);
Exit(1);
}
Return tempnode;
}
Struct linkedlist *insert_node(struct linkedlist *mynode, int
element)
{
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
Solved Question Papers D.33

{
While(thisnodeànext!=myheadernode)
Thisnode=thisnodeàneat)
Tempnodeànext=lastnode;
Thisnodeànext=tempnode;
Return tempnode;
}
}
return myheadernode;
}
Struct linkedlist *delete_node(struct linkedlist *mynode, int
element)
{
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;
}
D.34 Solved Question Papers

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 if
4. increment j by 1.
5. end for
6. end for
7. 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 in
the list. The process is clearly explained in the above algorithm.
Example:-
15 18 3 9 12
The first pass takes i = 1 and j = 2, 3, 4, 5. The value 15 is compared with 18 and net changed
15>3, now values interchanged 3, 18,15, 9, 12.
Since 3<9 and 3<12, so elements are not changed
After the first pass, list is 3, 18, 15, 9 ,12
In the second pass i = 2 and j = 3, 4, 5
Values 18>15, so interchanged 3, 15, 18, 9,12
Since 15>9, so interchanged 3, 9, 18, 15, 12
Since 9<12, no change is required 3, 9, 18, 15, 12
In the third pass i = 3 and j = 4, 5.
Since 18>15, so interchanged 3, 9, 15, 18, 12
Since 15>12, so interchanged 3, 9, 12, 18, 15
In the fourth pass, i = 4 and j = 5
Since 18>15, so interchanged 3, 9, 12, 15, 18
Efficiency of bubble sort:
No. of comparison in first pass = n–1
No. 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 either
be internal or external. When sorting is done keeping the records in the main memory, it is
called internal sorting. When sorting is done by keeping the records in external files on
storage 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
Solved Question Papers D.35

Insertion sort U|
Selection sort |
Quick sort |
V Internal sorts
Heap sort |W
Merge sort ¨ External sorts
Sorting time summary
Work case Average case
Bubble 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 memory
environment
Insertion sort Good for almost sorted data
Selection sort Good for partially stored data
and small n
Merge sort Good for external file sorting
Heap sort As efficient as quick sort in an average
case and far superior to quick sort in
work case.
C Programming and Data Structures
(May/June 2006)

SET 3
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 or
bottom. 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 job
will 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 next
outer 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);
Model Question Papers D.37
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. Consider
the problem of finding the largest of N numbers defined in an array.
#include<stdio.h>

#include<conio.h>
int largest(int x[], int m)
D.38 Model Question Papers
{
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 base
exponent.
#include<stdio.h>

int power(int base, int exp)


{
int i = 0, p = 1;
while(exp>0)
{
p = p*base;
}
return(p);
}
void main()
Model Question Papers D.39
{
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 following
equations:

X1 = – b + b 2 - 4ac

X2 = – b – b 2 - 4ac
The roots of a quadratic equation of the form ax2+bx+c = 0 are given by the following
equations:
X1 = –b+ b 2 –4ac /2a
X2 = –b– b 2 –4ac/2a
Write a function to calculate the roots. The function must use two pointer parameters, one
to 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’’);
D.40 Model Question Papers
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 the
highest 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);
}
Model Question Papers D.41
(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);
D.42 Model Question Papers
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--;
Model Question Papers D.43
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);
D.44 Model Question Papers
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 elements
for 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;
Model Question Papers D.45
start -> prev = NULL;
}
else
{
new = malloc(sizeof(struct node));
new -> data = x;
printf(‘‘enter your choice 1.insertion at starting 2.ending
3.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’’);
D.46 Model Question Papers
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;
Model Question Papers D.47
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);
}
D.48 Model Question Papers
}
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’’);
Model Question Papers D.49
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];
D.50 Model Question Papers
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 time
for 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
Model Question Papers D.51

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).
C Programming and Data Structures
(May/June 2006)

SET 4
1. (a) What is meant by operator precedence? What are the relative Precedence of the
arithmetic operators ?
Each operator in ‘C’ has a precedence associated with it. This Precedence is used to
determine how an expression involving more than one operator is evaluated. There are
distinct levels of precedence and an operator may belong to one of these levels. The
relative 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 , the
high priority operators are applied as they are Encountered during the second pass, the low
priority 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:
Model Question Papers D.53

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 of
the division would be lost and the ratio would represent a wrong figure. This problem can
solved 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 as
casting 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 the
operation.
The unary operators are
(1) ! –logical not
Eg: a !a
T F
F T
(2) Short hand assignment operators:
Eg: a+ = works as a = a+1
a– =1 works as a = a-1
a*=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=5
m++; //m = m+1//
resultant m = 6
m = 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.
D.54 Model Question Papers

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 is
any entity that may change during program execution.
An array is a variable that is capable of holding many values where as an ordinary variable
can 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 stored
belonging to the same type.
An ordinary variable initialization would be
Int 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 stored
in continuous memory locations.
The array elements are read from ‘0’ i.e a [0], is assigned the value ‘1’, similarily a [1] is
arranged 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 of
the same data type under which the array is declared
(c) What are subscripts? How are they written? What restrictions apply to the Values
that 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 in
the 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 ends
at “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’.
Model Question Papers D.55

(d) What advantages is there in defining an array size in terms of a symbolic constant
rather than a fixed integer quantity?
The advantage of defining the size of an array using symbolic constant instead of fixed
numbers is that, by defining the symbolic constant at the beginning of the program, it
allows us to know the maximum size of the array and in future if we want to change the
size of the array, it can be easily done by modifying the definition of the symbolic constant
which 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();

}
D.56 Model Question Papers

3. (a) Write a ‘C’ program to compute the sum of all element stored in an array
Using pointers.
/*program to compute sum of all elements stored in an
array */
#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’)
{
Model Question Papers D.57

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 passed
individually 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 entire
structure is passed to function but any modifications made to it will not reflected in the
called function.
eg: consider a structure x,which has two members, one integer type and the other character
type. We can pass the entire structure to a function as follows.
D.58 Model Question Papers

#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 this
approach, 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);
Model Question Papers D.59

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 character
String.
/*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);
D.60 Model Question Papers

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 by
For one purpose. opening a file in this mode.
2. “r” opens the file for reading 2. “r+” opens the existing File for both reading
Only. and writing.
3. “w” opens the file for writing 3. “w+” is same as write mode but for both read
Only. and writing .
4. “a” opens the file for appending 4. “a+” same as ‘a’ except for both reading and
data 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);
Model Question Papers D.61

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;
D.62 Model Question Papers

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\t
4.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);
Model Question Papers D.63

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)
{
D.64 Model Question Papers

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)
{
Model Question Papers D.65

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)
D.66 Model Question Papers

{
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;
Model Question Papers D.67
}
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 empty
due to deletion\n”);
first=null;
free(first);
}
}
else
first=ptr->next;
free(ptr);
}
Dend()
{
ptr=first;
D.68 Model Question Papers

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 empty
due 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
Model Question Papers D.69

{
printf(“list contains only one element and now it is empty
due 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)
D.70 Model Question Papers

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;
Model Question Papers D.71

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 its
time 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++)
{
D.72 Model Question Papers

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;
Model Question Papers D.73

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 have
an efficiency of O(mlogm). So, for heapsort both the average case and worst case time complexity are of
the order of ‘mlogm’.

You might also like