Solved Question Paper 1

Page 1

Appendix

+

Solved Question Papers

C Programming and Data Structures May/June 2008 SET- 1 1.

(a) Define algorithm.

Ans: In solving a problem or to develop a program, we should have two criteria. 1. algorithm 2. flow chart Algorithm: An algorithm is a method of representing the step-by-step procedure for solving a problem. An algorithm is very useful for finding the right answer to a simple problem or a difficult problem by breaking the problem into simple cases. Algorithm for in-order traversal (recursive): 5JAF : check if tree is empty by verifying root pointer R. Print tree empty if R=NULL 5JAF : if leftptr(R)!=NULL then call in-order (leftptr(R)) 5JAF !: print data(R). 5JAF ": if rightptr(R)!= NULL then call in-order(rightptr(R)) 5JAF #: return. (b) What is the use of flow chart? Ans: Flow chart is a diagrammatic representation of an algorithm. It is built using different types of boxes and symbols. The operation to be performed is written in the box. All symbols are interconnected processing to indicate the flow of information and processing. Uses of flow chart: 1. Flow chart helps to understand the program easily. 2. As different boxes are used to specify the type of operation performed, it will be easy to understand the complex programs.


C.2 Solved Question Papers Example for flow chart: /* To print the Fibonacci series for 1 to n value*/ START A=0,b=1 Read n True

False If n ==1 True

False If n ==2

Output a Output a,b

False

Output a,b

I=2

i++

I<n

C =a+b Output c Stop A=b B=c

(c) What are the different steps followed in the program development? Ans: A C program has to pass through many phases for its successful execution and to achieve the desired output. The various steps involved in the program development are as follows: 1. Editing phase 2. Compilation phase 3. Linking phase 4. Execution phase Editing Phase

In the editing phase, the C program is entered into a file through a text editor. Unix operating system provides a text editor which can be accessed through the command Vi . Modern compiler vendors provide Indegrated Development Environment (IDS). The file is saved on the disk with an extension of C . Corrections in the program at later stages are done through these editors. Once the program has been written, it requires to be translated into machine language.


Solved Question Papers

C.3

Compilation Phase

This phase is carried out by a program called as compiler. Compiler translates the source code into the object code. The compilation phase cannot proceed successfully until and unless the source code is error-free. The compiler generates messages if it encounters syntactic errors in the source code. The error-free source code is translated into object code and stored in a separate file with an extension .obj . Linking Phase

In this phase, the linker links all the files and functions with the object code under execution. For example, if a user uses a printf function in his\ her program, the linker links the user programs, object code with the object code of the printf function. Now the object code is ready for next phase. Execution Phase

In this phase, the executable object code is loaded into the memory and the program execution begins. We may encounter errors during the execution phase even though compilation phase is successful. The errors may be run-time errors and logical errors. 2. (a) Give some important points while using return statement. Ans: Return statement: This statement returns control to the calling function. There can be a number of return statements in the program but each statement can return only one value. The return statement terminates the execution of a function and returns control to the calling function. A return statement can also return a value to the calling function. The value of expression if present is returned to the calling function. If expression is omitted, the return value of the function is undefined. The type of variable that is to be returned is to be declared in the function in which return statement is used. A return statement with a value should not use ( ) [parentheses] around the value. The return value expression must start on the same line as the return keyword in order to avoid semicolon insertion. If a return value is not required, declare the function to have void return type; otherwise the default return type is int.If the function was declared with return type void, a return statement containing an expression generates a warning and the expression is not evaluated. Example for the return statement /* Write a program to find the factorial of given number*/ Program: #include<stdio.h> #include<conio.h> int fact(int n) //starting of the sub program {


C.4 Solved Question Papers int f=1,i; if((n==0)||(n==1)) // check the condition for n value return(1); else for(i=1;i<=n;i++) // perform the looping operation for calculating the factorial f=f*i; return(f); } void main() { int n; clrscr(); printf("enter the number :"); scanf("%d",&n); printf("factoria of number%d",fact(n)); getch(); }

(b) Write a short note on scope of a variable. Ans: Scope of a variable means whether the variable declared is a global or local variable. Local variable means it is valid only to the block in which it is declared. Global variable means it is valid throughout the program and its value is not changed throughout the program. The scope of a variable for different storage classes in C language is different. The scope of variable for register storage class is local to the block in which the variable is defined. The scope of variable for automatic storage class is local to the block. The scope of variable for static storage class is local to the block in which the variable is defined. The scope of variable for external storage class is global. If the variable is declared in the main function or within any function, that variable is called local variable and if the variable is declared before main, then it is called as global variable. By the scope of variable, we can know about the functioning of the variable in a program. Example: #include<stdio.h> int a; /* global variable*/ Void main ( ) { Int n,m; /* local variable*/ Printf("none"); }

3. (a) Write a short note on pointers. Ans: Pointers: Pointer is a variable used to point the address of the another variable. When you declare a variable, storage is allocated to it and the value assigned to it is stored in that storage location. Example: int O =5 When this statement is encountered, memory is allocated to variable O. the value 5 is stored at this address


Solved Question Papers

C.5

5 2450

y

Similarly pointers are special variables which store address of some other variable or values instead of storing normal values. Declaration of pointers: Pointers can be declared as follows Data type *ptr;

Here * indicates that ptr is a pointer variable representing the value stored at a particular address. Example: int *p; char *q;

Here F is a pointer variable pointing to address location where an integer type data is stored. G is a pointer variable pointing to address location where character type data is stored. Initialization of pointer: Pointer variable can be initialized during declaration as given below int *p; *p=5;

On compilation of the above statement, the value 5 is stored in an address pointed by F. Suppose F is a pointer to an address 1540, then 5 is stored in location 1540. 5

1540 1000

p

1540

*p

Here, F is 1540 and *F gives value 5. Assigning of address of variable to pointer variables: A pointer variable is used to print the addresses of other variables. Example: int *p; int x=5; p=&x;

Here, address of variable x is assigned to pointer p. X or *p 5

1000 1000

p

1540

*p

*F gives values at location 1000 i.e., 5 which is same as value of x. Here, the & used is same as the one we use in scanf function. & is called address of operator . Example: int *p=&x;

This statement will transfer the address of N to F.


C.6 Solved Question Papers The following program is an example for pointers. Program: /* Write a C program that displays the position or index in the string S where the string T begins, or -1 if S does not contain T */ #include<stdio.h> #include<string.h> #include<conio.h> void main() { char s[30], t[20]; char *found; clrscr(); /* Entering the main string */ puts("Enter the first string: "); gets(s); /* Entering the string whose position or index to be displayed */ puts("Enter the string to be searched: "); gets(t); /*Searching string t in string s */ found=strstr(s,t); if(found) printf("Second String is found in the First String at %d position.\n",found-s); else printf("-1"); getch(); }

Output: 1. Enter the first string: kali Enter the string to be searched: li Second String is found in the First String at 2 position. 2. Enter the first string: nagaraju Enter the string to be searched: raju Second String is found in the First String at 4 position 3. Enter the first string: nagarjuna Enter the string to be searched: ma -1


Solved Question Papers

C.7

4. Write a program using structures to display the following information for each customer name, account number, street, city, old balance, current payment, new balance, account, status. Ans: Program: # include<stdio.h> #include<conio.h> Void main () { Struct organization { Char name, street, city, status, account; Int account number, oldbalance, currentpayment, newbalance; }; Struct organization cust1={"ramu",101,"subhashchandrabose street", "vijayawada", 40000, 10000, 50000, "sbaccount","new"}; Struct organization cust2={"raju",100,"subhashchandrabose street", "vijayawada", 60000, 10000, 70000, "sbaccount","new"}; Printf("the information of the particular customer1 is=%c%c%c%d%d%d%d%c%c ", cust1.name,cust1.street,cust1.city, cust1.oldbalance,cust1.currentpayment,cust1.newbalance,cust1.account,cust1.status); }

Output: The information of the customer1 is : ramu,101, subhashchandrabose street, vijayawada, 40000,10000,50000, sbaccoount new 5. Write a program for indexed sequential file for the employee database for the following operation (a) add record (b) delete record (c) search record based on the department. Ans: Program:

/* Write a program to add, delete, search and retrieve records from a file*/ #include<stdio.h> Typedef struct { unsigned int empno; Char name[50]; Int salary;


C.8 Solved Question Papers } st_rec; Void main() { int ch; St_rec rec; FILE *fp; Fp= fopen("employee.rec","wb"); Printf("\n enter the empno"); Printf("type ctrl+z to stop\n"); /*read from keyboard and write to file*/ While(scanf("%u%c%d",&rec.empno,&rec.name,&rec.salary)!EOF) Fwrite(&rec,sizeof(rec),1,fp); Fclose(fp); Printf("\n"); /* read from file and write on screen*/ Fp=fopen("employee.rec","rb"); /* while loop terminates when fread returns 0*/ While (fread(&rec,sizeof(rec),1,fp)) Printf("%5u%-10c%3d\n",rec.empno,rec.name,rec.salary); int addrecord (); int removerecord(); int searchrecord (); Switch(ch) { Case 'a': int addrecord() { While(scanf("%u%c%d",&rec.empno,&rec.name,&rec.salary)!EOF) fwrite(&rec,sizeof(rec),1,fp); fclose(fp); } break; Case 'd': int removerecord(const char*employeerecord.index); Break; Case 's' : int searchrecord() { Fp=fopen("employee.rec","rb"); /* while loop terminates when fread returns 0*/ While (fread(&rec,sizeof(rec),1,fp)) Printf("%5u%-10c%3d\n",rec.empno,rec. name,rec.salary); } fclose(fp); } fclose(fp); }


Solved Question Papers

C.9

6. What do you mean by sorting? Mention the different types of sorting. Give some examples and explain any one in detail. Ans: Sorting: Sorting means arranging a set of data in some order. There are different methods that are used to sort the data in ascending or descending order. Searching and sorting techniques play a vital role for maintaining database applications. Sorting is a process of arranging the records either in ascending or descending order i.e., bringing some orderliness in the data. Sorting methods are very important in data structures. Sorting can be performed on any one or combination of one or more attributes present in each record. It is very easy and efficient to perform searching if data is stored in sorted order. The efficiency of sorting technique depends on utilisation of memory, sorting time, utilisation of processor, etc. There are many sorting techniques used. Some of them are. 1. bubble sort 4. merge sort 2. insertion sort 5. quick sort 3. selection sort 6. heap sort etc.,

Let us explain the quick sort Quick sort: This method is invented by Hoare is considered to be a fast method to sort the elements. The method is also called partition exchange sorting. The method is based on divide and conquer technique. i.e., the entire list is divided into various partitions and sorting is applied again and again on the partition. In this method, based on an element called pivot element the list is divided into two. Usually, the first element is considered to be the pivot element. Now move the pivot element to its correct position in the list. The elements to the left of the pivot element are less than pivot while the elements to the right of pivot are greater. The process is reapplied to each of these partitions till we get the sorted list of elements. Algorithm for quick sort: 1. start 2. if lowerbound < upperbound repeat through steps 3 to 13 otherwise go to step 14 begin 3. assign lowerbound to i, upperbound to j, i to pivot 4. if i<j repeat through steps 5 to 10 otherwise go to step begin 5. if a[i]<=k[pivot] and i< upperbound repeat through step 6 otherwise go to step 7 begin 6. assign i+1 to i end if 7. if k[j] > k[pivot] repeat through step 8 otherwise go to step 9 begin


C.10 Solved Question Papers 8. assign j-1 to j end if 9. if i< j go to step 10 otherwise go to step 4 begin 10. call function to swap k[i] and k[j] end if end if 11. call function to swap k[pivot] and k[j] 12. call function qsort(x,lowerbound,j-1) 13. call function qsort(x,j+1,upperbound) end if 14. stop The time complexity of the quick sort algorithm is In worst case = O(n2) In average case= log2 n In best case = log2 n Program : #include<stdio.h> main() { int x[10],i,n; clrscr(); printf("enter no of elements:"); scanf("%d",&n); printf("enter %d elements:",n); for(i=1;i<=n;i++) scanf("%d",&x[i]); quicksort(x,1,n); printf("sorted elements are:"); for(i=1;i<=n;i++) printf("%3d",x[i]); getch(); } quicksort(int x[10],int first,int last) { int pivot,i,j,t; if(first<last) { pivot=first; i=first; j=last; while(i<j) {


Solved Question Papers

C.11

while(x[i]<=x[pivot] && i<last) i++; while(x[j]>x[pivot]) j--; if(i<j) { t=x[i]; x[i]=x[j]; x[j]=t; } } t=x[pivot]; x[pivot]=x[j]; x[j]=t; quicksort(x,first,j-1); quicksort(x,j+1,last); } }

***** OUTPUT ***** enter no of elements:6 enter 6 elements: 23 12 45 34 21 87 sorted elements are: 12 21 23 34 45 87 7. What are the advantages and disadvantages of stack? Write a program to illustrate stack operation? Ans: A stack is an ordered collection of items into which new items may be inserted and items may be deleted at one end, called top of the stack. A stack is also known as LIFO structure because the element which is inserted last is the first element to be deleted. insertion

Deletion

C B A

Top of the stack


C.12 Solved Question Papers By the definition of stack, there is no upper limit on the number of items that can be kept in a stack. Pushing an element results in a larger collection of items in the stack and popping an element leads to a lesser collection of elements. Representation of stack: Advantages of stack: 1. To convert infix expression to postfix expression. 2. stack is used for recursion 3. Stack is used to evaluate postfix expressions. Disadvantages: 1. In LIFO, if we want to delete the first element then all the elements are to be deleted. 2. As insertion and deletion are done from only one end, the other end is closed. There are two operations that are performed in the stack. They are 1. push( ): Inserting an element into a stack is called as pushing operation 2. pop ( ): Deleting an element from the stack is called as popping operation. The following program illustrates the operations in a stack Program:

/* Write a ‘C’ program that implements stack and its operation by using the arrays */ # include <stdio.h> # define size 4 int choice,top=0,a[size],item; main() { clrscr(); while(1) { printf(" *** MENU ***\n 1. PUSH\n 2. POP\n 3. TRAVERSE\n 4. EXIT\n"); printf("enter your choice from menu:"); scanf("%d",&choice); switch(choice) { case 1:push(); break; case 2:pop(); break; case 3:traverse(); break; case 4:exit(); default:printf("wrong choice\n"); }

}


Solved Question Papers

C.13

getch(); } push() { if(size==top) printf("*** stack is full ***\n"); else { printf("enter the item to be pushed into the stack:"); scanf("%d",&item); top++; a[top]=item; } } pop() { if(top==0) printf("*** stack is empty ***\n"); else { item=a[top]; top--; printf("the deleted item from stack is %d\n",item); } traverse() { int i; if(top==0) printf("**** stack is empty ****"); else { printf("*** stack display ***\n"); for(i=1;i<=top;i++) if(i==top) printf("%d at %d ->top\n",a[i],i); else printf("%d at %d\n",a[i],i); } {

8.

(a) What is a network? (b) What is a spanning tree? (c) Define minimal spanning tree. (d) What are the various traversals in a tree? Ans: (a) A network means connection / communication between two mediums. According to C language, a network means the connection between two or more nodes (or)


C.14 Solved Question Papers communication from one graph to another graph. Graph node is connected with another node called Edge. The following graph explains and shows how the network operation is performed.

(b) Spanning trees are usually represented as graphs. Hence, spanning trees are undirected trees, residing with only those edges which are sufficient to connect all the nodes with a tree. There are two important considerations regarding a spanning tree. 1. Each pair of nodes in the spanning trees should possess a single path. 2. The number of edges in the spanning tree is one less than the total number of nodes [if a tree consists of ‘n’ nodes, then the edges should be (n-1)]. 3. Hence, any tree passing successfully through above-mentioned considerations can be termed as a spanning tree. Here are few examples of spanning trees. A

A B

D

B C

C

There are three major concepts associated with each spanning tree. These are 1. depth first search spanning tree 2. breadth first search spanning tree 3. cost of spanning tree. The spanning tree obtained by considering the depth first search mechanism is called as depth first search spanning tree. The spanning tree obtained by considering the breadth first search mechanism is called as breadth first search spanning tree. When there is a cost associated with each edge at the spanning tree, then the cost of spanning tree is nothing but the sum of costs of all the edges of the spanning tree. Based on the cost features of spanning tree, it has been successfully applied in various studies related to electrical circuits and determining of shortest paths in the bulk routes of networks. (c) The minimal spanning tree (MST) of a weighted graph is a spanning tree whose sum of edge weights is minimal. The minimum spanning tree describes the cheapest network to connect all of a given set of vertices.


Solved Question Papers

C.15

Kruskal s algorithm for minimal spanning tree works by inserting edges in order of increasing cost (adding as edges to the tree those which connect two previously disjoint components). The minimal spanning tree (MST) of a graph defines the cheapest subset of edges that keeps the graph in one connected component. Telephone companies are particularly interested in minimal spanning trees, because the minimal spanning tree of a set of sites defines the wiring scheme that connects the sites using as little wire as possible. It is the mother of all network design problems. Minimal spanning trees prove important for several reasons: ∑ They can be computed quickly and easily, and they create a sparse subgraph that reflects a lot about the original graph. ∑ They provide a way to identify clusters in sets of points. Deleting the long edges from a minimal spanning tree leaves connected components that define natural clusters in the data set. ∑ They can be used to give approximate solutions to hard problems such as Steiner tree and travelling salesman. ∑ As an educational tool, minimal spanning tree algorithms provide graphic evidence that greedy algorithms can give provably optimal solutions. Example of minimal spanning tree A weighted graph G The minimal spanning tree from weighted graph G

Using Kruskal s Algorithm, to find the mimimum cost of the tree. MST Problem: Given a connected graph G=(V,E) and a weight d:E->R+, find a minimum spanning tree T. Kruskal s Algorithm 1. Set i=1 and let E0={} 2. Select an edge ei of minimum value not in Ei 1 such that T;=<Ei 1 cup {ei} >is acyclic and define Ei=Ei 1 cup {ei}. If no such edge exists, Let T=<Ei>and stop. 3. Replace i by i+1. Return to Step 2. The time required by Kruskal s algorithm is O(|E|log|V|). (d) Tree traversal are of three types: 1. In-order traversal 2. Pre-order traversal 3. Post-order traversal


C.16 Solved Question Papers In-order traversal: In-order traversal is given by the following steps. 1. traverse the left sub-tree 2. process the root node 3. traverse the right sub-tree Algorithm for in-order traversal (recursive): 5JAF : 5JAF : 5JAF !: 5JAF ": 5JAF #:

check if tree is empty by verifying root pointer R. print tree empty if R=NULL if leftptr(R)!=NULL then call in-order (leftptr(R)) print data(R). if rightptr(R)!= NULL then call in-order(rightptr(R)) return. A

D

B E

C

G F

So the in-order of the binary tree in the figure above is C B A E F D G. Pre-order traversal: Pre-order traversal is defined as follows: 1. process the root node 2. traverse the left sub-tree in pre-order 3. traverse the right sub-tree in pre-order Algorithm for pre-order traversal: 5JAF : check if tree is empty by verifying root pointer R If R=NULLL, then print "tree empty" 5JAF : print data(R) 5JAF !: if leftptr(R)!=NULL then call pre-order(leftptr(R)) 5JAF ": if rightptr(R)!=NULL call pre-order(rightptr(R)) 5JAF #: return A D

B C

E

G F


Solved Question Papers

Pre-order traversal is A B C D E F G Post-order traversal: Post-order traversal is defined as follows: 1. traverse the left sub-tree 2. traverse the right sub-tree 3. process the root node A D

B C

E

G F

Post-order traversal for the above tree is C-B-F-E-G-D-A

C.17


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.