Sie sind auf Seite 1von 65

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 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

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.

(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++; } 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 reasonsPointer 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 employees information and write a program to carry out operations like inserting a new entry, deleting

entry.
/*accessing variables using pointers*/ #include<stdio.h> main( ) { 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;

};

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]; } } } a[ j]=*B; if(strcmp(n,*B.ename)=0) { free(B); }

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;

}; 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];

} } } a[ j]=*B; if(strcmp(n,*B.ename)=0) { free(B); }

9. 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

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.4E38 to 3.4E+38 Double 64 1.7E308 to 1.7E+308 to

Long double 80 3.4E4932 to


1.1E+4932
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. 10 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]) { 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(); }

11 (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:
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 doesnt 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 doesnt 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); } While((ch=getchar())!=EOF) { putc(ch,fp); } fclose(fp); fp=fopen(Input,r); while((ch=getc(fp)!=EOF) printf(%c,ch) }

12 (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];

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 size1. (b). Write a C program using structure to create a library catalogue with the following fields: Access number, Authors name, Title of book, Year of publication, Publishers 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

___# ________ __________


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); } }

13

Write a C program to read information about the student record containing

students name, students age and students 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 students 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); } Fclose(f); Fclose(p); P=fopen(total,r); For(i=0;i<=n;i++) { Fscanf(p,%f,& tot); Printf(% f,tot); } }

14 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)

{ 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)

{ 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(); }

15.

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) { 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 { 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; }

16. (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,n1. 2. Repeat for j = i+1 to n1. 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 = n1 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 Insertion sort Selection sort Quick sort Heap sort Internal sorts 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.

17. (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); 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); } }

18. (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) { 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() { int b, e, 1; printf(Enter base & exponent); scanf(%d%d, &b, &e); 1=power(b, e); printf(%d^%d = %d, b, e, 1); }

19. The roots of a quadratic equation of the form ax2+bx+c = 0 are given by the following equations:

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 following equations: X1 = b+ b2 4ac/2a X2 = b b2 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); for(i=0; i< = 2; i++) scanf(%f,A+i); Roots(A, R); printf(root1 = %f, *(R+0)); printf(root2=%f, *(R+1)); }

20 (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); }

(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. 21. 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); fclose(f1); }

22. 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--; 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); break; case 2: dequeue(); break; case 3: Traversal(); break; case 4: exit(0); default: puts(Invalid choice); } }while(1); }

23. 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; 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 < loc1; i++) l = l - >next; if(l==NULL) { puts(\a invalid location); 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; 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); } } 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); }

24. 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); 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]; 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 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).

25 (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: 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

TF FT (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=m1// 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. 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.

26. (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 its 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. (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(); } 27. (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) { l++; p++; } printf(the length of the given string is %d,l); getch(); }

28. (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.

#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); 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]; studenttot=t; studentavg=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); } 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); }

29. (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); 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(); }

30. 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 == size1) { printf(\n over flow\n); return; }

st->top++; st->a[st->top]=num; } Int pop(stuct stack *st) { Int num; 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); break; case 4: exit (0); default: printf(invalid choice); } } getch(); }

31. 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) { 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) {

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) { 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; } 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; 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 { 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)

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; 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; } }

32 . 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++) { 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;

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.

9. (a) What is a flowchart? Explain the different symbols used in a flowchart. A flowchart is the pictorial representation of an algorithm. The various steps in an algorithm are drawn in the form of prescribed symbols. The flow of the algorithm is maintained in a flowchart. The various symbols used in a flowchart are as below. The name of the symbol is given inside the symbol itself.
Process Assignment Decision Data Internal storage Output document Terminator (Start/Stop) Input from keyboard Connector Page Connector Disk storage (database) Monitor output

9. (b) Write a flowchart to find the maximum and minimum of given numbers.
Start Input A, B Is A > B? Write A is maximum,

B is minimum Write B is maximum, A is minimum Stop Yes No

10 (a) What do you mean by functions? Give the structure of the functions and explain about the arguments and their return values. A C program has always a main module (called main) where the execution of the program begins and ends. If a program is very big and if we write all the statements of that big program in main itself, the program may become tool complex and large. As a result, the task of debugging and maintaining will become very difficult. On the other hand, if we split the program into several functional portions, these are easier. These subprograms are called functions. The structure of a function is: Function name (argument) Argument declaration; { local variables declaration; Executable statements; Return value; } Argumentsthe arguments are valid variable names separated by commas. The argument variables receive values from a calling function. Thus they provide as the link between the main program and the function. Return valuesa function may or may not send a value back to the calling function. This value which is sent to the calling function is the return value of the function. It is achieved through the return keyword. There can be only one value in a return statement. 10. (b) Write a C program that uses a function to sort an array of integers.
main() { int i; static int data[6] = {20, 10, 5, 12, 13, 3}; printf(\nList before sorting}; for (i = 0; i < 6; i++) printf(%d, , data[i]); sort(data, 6);

printf(\nList after sorting}; for (i = 0; i < 6; i++) printf(%d, , data[i]); } sort(arr, n) int arr[], n; { int j, k, temp; for (j = 1; j <= n 1; j++) for (k = 1; k <= m j; k++) if (arr[k 1] >= arr[k]) { temp = arr[k 1]; arr[k 1] = arr[k]; arr[k] = temp; } }

11. (a) Explain the advantages of structure type over the array type variable. 1. An array type variable can store only homogeneous data i.e. it can store only values of data types according to which the variable is declared. For example, an integer array can store only integer numbers. This limitation is not there in a structure variable. A structure variable can host many data types at the same time. 2. An array type is subjected to lower and upper bounds limitations. If we try to read or write past these bounds, we will get error. This is not a limitation in structure variable. 3. A structure variable can host an array variable also. 11.(b) Define a structure that represent a complex number (contains two floatingpoint members, called real and imaginary). Write a C program to add, subtract and multiply two complex numbers.
struct complexnumber { float real; float imaginary; }; main() { struct complexnumber c1, c2, add, sub, mult; printf(\nEnter complex number 1 (Real imaginary));

scanf(%f %f,&c1.real, &c1. imaginary); printf(\nEnter complex number 2 (Real imaginary)); scanf(%f %f,&c2.real, &c2. imaginary); add.real = c1.real + c2.real; add.imaginary = c1.imaginary + c2.imaginary; sub.real = c1.real - c2.real; sub.imaginary = c1.imaginary - c2.imaginary; mult.real = c1.real * c2.real; mult.imaginary = c1.imaginary * c2.imaginary; printf(\nSum is Real %f imaginary %f, add.real, add.imaginary); printf(\nDiff is Real %f imaginary %f, sub.real, sub.imaginary); printf(\nProduct is Real %f imaginary %f, mult.real, mult.imaginary); }

12. The roots of a quadratic equation of the form ax2 + bx + c = 0 are given by the following equations: X1 = b + root(b2 4ac) / 2a; X2 = b root(b2 4ac) / 2a; Write a function to calculate the roots. The function must use two pointers, one to receive the coefficients and the other to send the roots to the calling function.
#include <math.h> struct equation { float a, b, c; }; struct roots { float x1, x2; }; void findroots(); main() { struct equation myeq; struct roots myroots; printf(\nEnter values for a, b and c);

scanf(%f %f %f, &myeq.a, &myeq.b, &myeq.c); findroots(&myeq, &myroots); printf(\nRoots are X1 = %f, X2 = %f, myroots.x1, myroots.x2); } void findroots(struct equation *myeqarg, struct roots *myrootarg) { float a, b, c, discr, a1; a = myeqarg->a; b = myeqarg->b; c = myeqarg->c; discr = b * b - 4.0 * a * c; myrootarg->x1 = (-b + sqrt(discr)) / (2.0 * a); myrootarg->x2 = (-b - sqrt(discr)) / (2.0 * a); }

_________

________

__

5. Define a file and elaborately discuss about reading, opening and closing of a file. If we want to store data in a file in the secondary memory, we must specify certain things about the file, to the operating system. They include: 1. Filename. 2. Data structure. 3. Purpose. Filename is a string of characters that make up a valid filename for the operating system. It may contain two parts, a primary name and an optional period with the extension. Examples:
Input.data store PROG.C Student c Text.out

Data structure of a file is defined as FILE in the library of standard I/O function definitions. Therefore, all files should be declared as type FILE before they are used. FILE is a defined data type. When we open a file, we must specify what we want to do with the file. For example, we may write data to the file or read the already existing data. Following is the general format for declaring and opening a file:
FILE *fp; fp = fopen(filename, mode);

The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier. FILE is a structure that is defined in the I/O library. The second statement opens the file

named filename and assigns an identifier to the FILE type pointer fp. This pointer which contains all the information about the file is subsequently used as a communication link between the system and the program. The second statement also specifies the purpose of opening this file. The mode does this job. Mode can be one of the following: r open the file for reading only. w open the file for writing only. a open the file for appending (or adding) data to it. Note that both the filename and mode are specified as strings. They should be enclosed in double quotation marks. When trying to open a file, one of the following things may happen: 1. When the mode is writing a file with the specified name is created if the file does not exist. The contents are deleted, if the file already exists. 2. When the purpose is appending, the file is opened with the current contents safe. A file with the specified name is created if the file does not exist. 3. If the purpose is reading, and if it exists, then the file is opened with the current contents safe; otherwise an error occurs. Consider the following statements:

__

_ _________

________

FILE *p1, *p2; p1 = fopen(data, r); p2 = fopen(results, w);

The file data is opened for reading and results is opened for writing. In case, the results file already exists, its contents are deleted and the file is opened as a new file. If data file does not exist, an error will occur. Many recent compilers include additional modes of operation. They include: r+ The existing file is opened to the beginning for both reading and writing. w+ Same as w except both for reading and writing. a+ Same as a except both for reading and writing. We can open and use a number of files at a time. This number however depends on the system we use. 6. Write a program that uses a stack to check for matching left and right parentheses, left and right braces, and left and right brackets in a string of characters.
#include<stdio.h> #define MAXSIZE 50 static struct stack {

int top; int numbers[MAXSIZE]; } mystack; void push(struct stack *,int); int pop(struct stack*); int isempty(struct stack*); main() { char expression[MAXSIZE]; int i = -1; int number; mystack.top = -1; printf(\nEnter the expression > ); scanf(%s,expression); while(expression[++i] != \0) { switch (expression[i]) { case ( : push(&mystack,(); break; case ) : number = pop(&mystack); break; case [ : push(&mystack,[); break; case ] : number = pop(&mystack); break; case { : push(&mystack,{); break; case } : number = pop(&mystack);

_________
break; } }

________

__

if (!isempty(&mystack)) printf(\nExpression has unmatched parenthesis); else

printf(\nExpression is okay); } void push(struct stack *mystack,int number) { if (mystack->top==MAXSIZE-1) { printf(\nStack Overflow\n); exit(1); } mystack->numbers[++mystack->top]=number; } int pop(struct stack *mystack) { if (isempty(mystack)) { printf(\nStack Underflow\n); exit(1); } return(mystack->numbers[mystack->top]); } int isempty(struct stack *mystack) { return((mystack->top==-1)); }

7. How can a polynomial in three variables (x, y and z) be represented by a singly linked list? Each node in a list should represent a term and should contain the powers of x, y and z as well as the coefficient of that term. Such a polynomial can be represented with a linked list in the same way as we represent a polynomial with a single variable. Each node in the list will have the following structure:
COEFFICIENT X-POWER Y-POWER Z-POWER NEXT ADDR

Consider a simple polynomial P(x, y, z) = 10x4y3z2 + 15 xy2 + 5 yz3. Please do not worry about the validity of this polynomial. The idea is to explain the representation. This can be represented as follows: 10 4 3 2 15 1 2 0 5 0 1 3 NULL

__

_ _________

________

8. Explain the algorithm for selection sort and give a suitable example. As the name suggests, the first element of the list is selected. It is compared repeatedly with all the elements. If any element is found to be lesser than the selected element, these two are swapped. This procedure is repeated till the entire array is sorted. Let us understand this with a simple example. Consider the list 74, 39, 35, 32, 97, 84. Following is the table, which gives the status of the list after each pass is completed.
Pass List after pass
1 32, 39, 35, 74, 97, 84 2 32, 35, 39, 74, 97, 84 3 32, 35, 39, 74, 97, 84 4 32, 35, 39, 74, 97, 84 5 32, 35, 39, 74, 84, 97
C program for selection sort

Let us assume that an array named elements[] will hold the array to be sorted and maxsize is the number of elements to be sorted. We will also assume that the sorting order is ascending in nature.
#include <stdlib.h> #include <stdio.h> #define MAXSIZE 500 void selection(int elements[], int maxsize); int elements[MAXSIZE],maxsize; int main() { int i; printf(\nHow many elements you want to sort: ); scanf(%d,&maxsize); printf(\nEnter the values one by one: ); for (i = 0; i < maxsize; i++) { printf (\nEnter element %i :,i); scanf(%d,&elements[i]); } printf(\nArray before sorting:\n); for (i = 0; i < maxsize; i++) printf([%i], ,elements[i]);

printf (\n); selection(elements, maxsize); printf(\nArray after sorting:\n); for (i = 0; i < maxsize; i++) printf([%i], , elements[i]); } void selection(int elements[], int array_size) { int i, j, k;

_________
int min, temp;

________

__

for (i = 0; i < maxsize-1; i++) { min = i; for (j = i+1; j < maxsize; j++) { if (elements[j] < elements[min]) min = j; } temp = elements[i]; elements[i] = elements[min]; elements[min] = temp; } }

Let us now analyze the efficiency of the selection sort. You can easily understand from the algorithm that the first pass of the program does (maxsize 1) comparisons. The next pass does (maxsize 2) comparisons and so on. Thus, the total number of comparisons at the end of the sort would be : (maxsize 1) + (maxsize 2) + + 1 = maxsize * (maxsize 1) / 2 = O(maxsize2).

Das könnte Ihnen auch gefallen