Professional Documents
Culture Documents
Solved Question Paper 2-1
Solved Question Paper 2-1
Solved Question Paper 2-1
May/June 2008
SET- 2
1. (a) Explain the working of unary operator with example.
(b) Explain the working of binary operator with example.
(c) Explain the working of assignment operator with example.
(d) Explain the working of ternary operator with example.
Ans: (a) C supports a rich set of operators, such as +,-,=,*,& and <.
1. An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
2. Operators are used in programs to manipulate data and variables. They usually form a part of
the mathematical or logical expressions.
3. C operators can be classified into a number of categories. They include:
1. arithmetic operators.
2. relational operators.
3. logical operators
4. assignment operators
5. increment or decrement operators.
6. conditional operators
7. bitwise operators
8. special operators.
C provides all the basic arithmetic operators. These operators are +, -, * and /. All work
the same way as they do in other languages. They can operate on any built-in data type al-
lowed in c.
Unary Operators
2. Minus Operator
Program:
/* write a program to subtract two numbers */
#include<stdio.h>
#include<conio.h>
Main ()
{
Int a,b,s;
Clrscr();
Printf("enter the values of a,b:");
Scanf("%d%d",&a,&b);
S=a-b;
Printf("%d=subtraction",s);
Getch();
}
Output: enter the values of a,b
11,9
Subtraction=2.
3. Increment Operator(++)
The operator ++ adds one to its operand whereas the operator--subtracts one from its operand.
Example:
X=x+1 can be written as x++
Consider, z=x*y++
Where x=20, y=10
In the above example, the current value of y is used for product and after performing the opera-
tion, the value of y is incremented.
Result is z = 20*10=200
Now consider, x=20, y=10
Z=x*++y
Here, first the value of y is incremented then it is used for the product.
Result is, z=20*11=220.
The sizeof operator gives the bytes occupied by a variable. The number of bytes occupied varies
from variable to variable.
The & operator prints the address of the variable in the memory.
The program below explains these operators.
#include<stdio.h>
#include<conio.h>
Solved Question Papers C.21
Main ()
{
Int x=2;
Float y=2;
Printf("sizeof (x)=%d bytes", size of(x));
Printf("sizeof (y)=%f bytes",size of(y));
Printf("\n address of x=%u and y=%u",&x,%y);
}
Output:
Size of(x)= 2
Size of(y)= 4
Address of x = 4066 and y=25096.
(b) Simple binary operators:
Expression:
Expression + expression
Expression - expression
Expression * expression
Expression / expression
Expression % expression
Expression == expression
Expression != expression
Expression < expression
Expression > expression
Expression <= expression
Expression >= expression
Expression && expression
Expression || expression
Expression & expression
Expression / expression
Expression ^ expression
Expression << expression
Expression >> expression
Example : p+-3 is same as = p-3
(c) Assignment operator:
Assignment operators are used to assign the result of an expression to a variable. We have seen the
usual assignment operator '='.
In addition, C has a set of 'shorthand' assignment operators of the form
V op =exp;
Where 'V' is a variable, 'exp' is an expression and op is a C binary arithmetic operator.
The operator op= is known as the shorthand assignment operator.
The assignment statement
V op = exp;
C.22 Solved Question Papers
Example:
X+=y+1;
This is same as the statement, x=x+(y+1);
Statement with simple assignment operator statement with shorthand operator
A=a+1 a+=1
A=a-1 a-=1
A=a*(n+1) a*=n+1
A=a/(n+1) a/=n=1
A=a%b a%=b
The use of shorthand assignment operators has three advantages:
1. What appears on the left hand side need not be repeated. Therefore, it becomes easier to write.
2. The statement is more concise and easier to red.
3. The statement is more efficient.
(d) The ternary operator is also called as conditional operator.
Syntax:
Exp1?exp2:exp3;
Where exp1, exp2 and exp3 are expressions.
The value of exp1 is evaluated first. If it is true, value of exp2 is evaluated, otherwise exp3 is
evaluated.
Example:
Int a=5,b=10,c=15;
Y=(a>b)?b:c;
In the above statement, the expression a>b is evaluated. Since it is false, value of c will be assigned
to y.
So, the value of y will be 15.
Y=(a<b)?b:c;
Here a<b is true so value of b is assignment to y.
So, value of y will be 100.
Program:
/* Write a program to find the largest of three input numbers using ternary operator */
#include<stdio.h>
#include<conio.h>
Main ()
{
Int a,b,c,largest;
Clrscr();
Printf("enter the values of a,b,c:\n");
Scanf("%d%d%d",&a,&b,&c);
Solved Question Papers C.23
Largest=(a>b)?(a>c)?(b<c)? a:b:c;
Printf("the largest number is: %d", largest);
Getch();
}
2. What is the advantage of using functions. Write a C program to explain about built-in
functions with an example.
Ans: A function is a self-contained program segment that performs specific and well defined tasks.
Use of functions ease the complex tasks by dividing the program into modules.
There are two functions in C language
1. programmer defined functions.
2. library functions.
1. When programs are very lengthy, handling them becomes difficult. It is also difficult to debug
and understand such lengthy programs. In order to overcome these drawbacks, complex pro-
grams can be subdivided into smaller modules. These modules are implemented using func-
tions. Hence these subprograms or functions make programs easy to understand, debug and
test.
2. The part of program which has to be repeated and used many times can be written as a func-
tion and can be called wherever needed to avoid repetition. This helps in reducing the size of
the program.
3. A function can be shared by many programs.
4. It facilities top-down modular programming.
Before writing a program on built-in functions, let us know what is meant by built-in functions.
Built-in functions
1. Built-in functions are commonly required functions that are not grouped together and are stored
in a library.
2. These functions are not modifiable.
3. These are not written by the programmers.
4. White space between the function names and parenthesis ( ) are ignored in case of built-in
functions.
5. They are predefined.
6. Built-in functions cannot be overloaded.
7. Programmers overhead is reduced here, as they are available as ready to use functions.
8. Already available for the programmers to call.
9. Their definitions appear in standard libraries.
10. Declarations of the built-in functions are not required
11. Example: cos(x), sqrt(x), sin(x), etc.,
The following is a C program to explain about built-in functions.
Program:
/* a C program to find the square root of x */
C.24 Solved Question Papers
#include<stdio.h>
#include<conio.h>
#include<math.h>
Void square(int);
Main ()
{
Int x,y;
Printf("enter the value of x");
Scanf("%d",&x);
Square(x);
Y=sqrt(x); /* call to a built-in function */
Printf("%d",y);
}
Void square(int a)
{
Int p;
P=a*a;
Printf("%d",p);
}
The built-in function sqrt(x) is available in the standard library header file "math.h", hence it
must be included in the program.
3. What is the advantage of using arrays? Give the syntax for declaration, accessing and
printing one-dimensional array.
Ans:
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.
The following are the advantages of using arrays.
1. An array is a variable that is capable of handling many values, whereas, 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 eight storage locations reserved where eight different values can be
stored belonging to the same type. An ordinary variable initialization would be,
int number;
and only one storage location is reserved and can hold only one value at a time.
2. Elements of an array can be initialized at the time and place of their declaration.
Consider an array with its elements.
Int a[4] = {5,6,7,8};
In the above example, four elements are stored in an array a. The array elements are stored in
contiguous memory locations. The array elements are read from 0.i.e., a[0] is assigned the value
5. Similarly, a[1] is assigned the value 6. The number 4 in a[4] represents the total number of
elements.
Solved Question Papers C.25
The condition that needs to be satisfied is that all the elements of the array must be of the same
datatype. Types of the declared array.
This is about the advantages of using arrays. The following is about the syntax for declaration,
accessing and printing one-dimensional array.
One-dimensional Array
It is the simplest form of an array in which the list of elements are stored in contiguous memory
locations and accessed using only one subscript.
Example:
Int abc[10];
Here abc is an array of 10 integers.
We can initialize array elements at the place of their declaration itself. The general format of this
initialization is,
Type array_name [size]={list of elements separated by commas}
Example:
Int a[4]={5,10,1,55};
Here the size of this array is 4, 5 is assigned to first element, i.e., a[0]=5,10 is as-
signed to second element i.e., a[1]=10, 1 is assigned to third element, i.e., a[2]=1, 55 is assigned to
fourth element a[3]=55.
Suppose the list of elements specified are less than the size of array then only that many elements
are initialized. The remaining elements are assigned garbage values.
Example:
Int xyz[5]={10,5,20};
Here, the first element is assigned value 10, second element is assigned value 5 and third element
is assigned value 20. Since, the list of elements is less than the size of the array, the remaining two
elements are assigned garbage values. Index in general runs from 0 to n-1 i.e., for an array a[n], we
have values from a[0],a[1], ..a[n-1].
Xyz[0], xyz[1]=5, xyz[2]=20,
C.26 Solved Question Papers
Main ( )
{
Int i;
Float x[10], value, total;
/* reading values into array */
Printf("enter 10 real numbers\n");
For(i=0;i<10;i++)
{
Scanf("%f",&value);
X[i]=value;
}
/* computation of total */
Total = 0.0;
For(i=0;i<10;i++)
Total= total+x[i]*x[i];
/* printing of x[i] values and total */
Printf("\n");
For(i=0;i<10;i++)
Printf("x[%2d]=%5.2 f\n", i+1,x[i]);
Printf("\n total =%2f \n", total);
}
Output of 10 real numbers: 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9,10.10.
4. Define structure and write the general format for declaring and accessing members.
Ans: Structure:
When you want to access data consisting of different types of elements, it cannot be done using
arrays, as array is a collection of similar data items. Suppose that you want to store information
Solved Question Papers C.27
regarding a student. Each student will have a name, roll number and branch of study. This entire
information cannot be stored in a single array as student information consists of data of different
types [name is a string, roll number is an integer and branch is a string]. To handle such string of
data, C provides a derived data type known as structure.
name
student Roll. no
branch
Structure definition :
A structure is a collection of data items of different datatypes under a single name. Or, a structure is
a collection of heterogeneous data items.
A structure is declared as follows
Struct < tag >
{
Data type member1;
Data type member2;
………..
……………
Data type member n;
};
* In this declaration struct is a keyword.
* <tag > is the name given to the structure declared.
* Data type can be integer, float, char or any other data types.
* member1, member2, ..member n are members of structures. Individual members
can be variable, pointers, arrays or other structures.
* Individual members cannot be initialized within structure definition. After
structure has been declared, individual structure type variable are declared as
follows.
Struct <tag> variable1,variable2 variable n;
* Variable 1, variable2, variable n are structure variables of type tag.
* After closing bracket semicolon ';' must be specified.
* Members of structure themselves do not occupy any space. Memory is allocated only
after declaring structure variables.
Structure can be declared as,
Struct tag
{
Type 1 data 1;
Type 2 data 2;
C.28 Solved Question Papers
Type n data n;
} variable1, variable2, ..variable n;
In the case of above declaration, tag is optional
Example:
Struct
{
Char name[26];
Int age;
Char gender[6];
Char occupation[25];
} p1,p2;
In the above declaration, there is no need to specify structure name.
Structure members can be accessed by writing variable name.member. Dot( . ) operator links struc-
ture variable to the data member. It is the highest precedence operator and associatively is left to
right.
Assigning values to structure:
One way is to assign values at the time of declarating structure variables.
Struct person p1={ravi,21,male,student}
Another way is to assign values to each member separately as shown below.
Strcpy(p1.name,ravi);
P1.age=21;
Strcpy(p1.gender,male);
Strcpy(p1.occupation,student);
Here is an example demonstrating the structure with initialized values.
/* structure with initialized values */
#include<stdio.h>
#include<conio.h>
Void main ( )
{
Struct organization
{
bb Char name[20];
Char designation[20];
Int sal;
};
Struct organization emp1={ramu,secretary,8000};
Struct organization emp2={raju,manager,18000};
Solved Question Papers C.29
#include<stdio.h>
main()
{
int i,j,t,a[5],n;
clrscr();
printf("enter the range of array:");
scanf("%d",&n);
printf("enter elements into array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
printf("the sorted order is:");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
getch();
}
* This sorting method requires many comparisons, thus take more time than quick sort, insertion
sort, etc.
Insertion Sort
Insertion sort is similar to playing cards. To sort the cards in your hand, you extract a card, shift the
remaining cards and then insert the extracted card in its correct place. The efficiency of insertion
sort is O(n2).
As the name suggests, insertion sort is a technique, which inserts an element at an appropriate
location by comparing each element with the corresponding elements present at its left and accord-
ingly moves rest of the given array.
Solved Question Papers C.31
Consider insertion sort mechanism with an example
1) 9 6 14 2 1
2) 6 9 14 2 1
3) 6 9 14 2 1
4) 2 6 9 14 1
5) 1 2 6 9 14.
Program :
/* Write a C program that implements the insertion sort method */
#include<stdio.h>
main()
{
int i,j,t,a[10],n,p=0;
clrscr();
printf("enter the range of array:");
scanf("%d",&n);
printf("enter elements into array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
t=a[i];
for(p=i;p>0 && a[p-1]>t;p--)
a[p]=a[p-1];
a[p]=t;
}
printf("the sorted order is:");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
getch();
}
Insertion sort requires more comparisons than quick sort but is easy to implement.
Selection Sort
A selection sort algorithm sorts the list by selecting the largest element in the unsorted list and
places it at the appropriate position. In each pass the largest element in the list is placed at appropri-
ate position. If there are n elements in the list, then
In the first pass all the elements are compared and largest element is placed at the last position.
In the second pass, first n-1 elements are compared and process continues for list of n-2 ele-
ments, then for n-3 elements and so on until first element.
If there are n elements, we require n-1 passes.
The time complexity of selection sort is O(n2) in all cases.
C.32 Solved Question Papers
Program:
/* Write a C program that implements the selection sort method */
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a[20],I,j,temp,t,n,max;
Clrscr();
Temp=0;
Printf("\n enter the no of elements in the list:");
Scanf("%d",&n);
Printf("\n enter the elements of the list\n");
For(i=0;i<n;i++)
Scanf("%d",&a[i]);
For(i=n;i>1;i--)
{
Max=0;
For(j=1;j<I;j++)
If(a[j]>a[max])
Max=j;
Temp=a[i-1];
A[i-1]=a[max];
A[max]=temp;
}
Printf("\n elements in the ascending order are as follows:\n");
For(i=0;i<n;i++)
Printf("%d\n",a[i]);
Getch();
}
Advantage:
Selection sort minimizes data movement by putting one entry at its final position at every pass.
Hence this algorithm is useful for continuous list of large elements where movement of entries is
expensive.
Disadvantage:
If the elements are stored using linked lists, then insertion sort is more efficient than selection sort.
It requires more comparisons than quick sort but is easy to implement than quick sort.
7. Define abstract data type. Explain with an example.
Ans: An abstract data type (ADT) is a general way to group and operate on data, independent of
any particular language. Two classic ADTs are List and Stack. These concepts exist as general
Solved Question Papers C.33
Computer Science. Sci. structures, and can be implemented in many languages. The key features of
how they store and operate on data are defined by the ADTs, and implemented in code in various
languages. In OO languages like Java, an ADT would typically be implemented by a class or group
of classes. In non-OO languages like C, it would be implemented by a data structure and a set of
functions to be called against it.
The examples of an abstract data type can be implemented in stack, queue, linked list, etc. Let us
discuss one of these topics.
Stack:
A stack is a data structure in which addition of new element or deletion of an existing element
always takes place at the same end. This end is called as top of stack. A stack is generally imple-
mented with two basic operations. They are push and pop. Here, push operation allows adding an
element at the top of the stack.
Pop operation allows removal of an element from the top of the stack. Before making use of
stack in a program, it is very important to decide how to represent a stack. There are several ways of
representing a stack such as by using arrays, by using pointers, by using linked list, etc.
The following program explains the stack by using single linked list.
Program:
/* Write a program to implement the stack operation by using single linked list*/
#include<malloc.h>
#include<stdio.h>
struct node
{
int info;
struct node *next;
};
main()
{
nodeptr stack;
int choice;
clrscr();
stack=NULL;
while(1)
{
printf("\n\t1\tpush\n\t2\tpop\n\t3\tdisplay\n\t4\tEXIT\n");
C.34 Solved Question Papers
switch(choice)
{
case 1: stack = push(stack);
break;
case 2: stack = pop(stack);
break;
case 3: display(stack);
break;
case 4: exit();
}
}
getch();
}
push(nodeptr stack)
{
nodeptr temp;
int info;
printf("ENTER THE ELEMENT TO BE PUSHED");
scanf("%d",&info);
temp=(nodeptr)malloc(sizeof(nodeptr));
temp->info=info;
temp->next=stack;
stack=temp;
return(stack);
display(stack);
}
display(nodeptr stack)
{
printf("TOP");
while(stack != NULL)
{
printf("%d",stack->info);
stack=stack->next;
printf("->");
}
printf("NULL\n");
}
nodeptr pop(nodeptr stack)
{
Solved Question Papers C.35
nodeptr temp;
if(stack == NULL)
printf("POP OPERATION IS NOT POSSIBLE");
else
{
temp=stack;
printf("THE POPED ITEM IS %d\n",stack->info);
printf("press any key to continue");
getchar();
stack=stack->next;
}
free(temp);
return(stack);
}
/*
INPUT / OUTPUT
1 PUSH
2 POP
3 DISPLAY
4 EXIT
ENTER YOUR CHOICE 1
ENTER THE ELEMENT TO BE PUSHED 34
1 PUSH
2 POP
3 DISPLAY
4 EXIT
ENTER YOUR CHOICE 3
TOP 34->NULL
1 PUSH
2 POP
3 DISPLAY
4 EXIT
ENTER YOUR CHOICE 2
THE POPED ITEM IS 34
PRESS ANY KEY TO CONTINUE
1 PUSH
2 POP
3 DISPLAY
4 EXIT
ENTER YOUR CHOICE 4
EXIT.
8. (a) What is a network?
(b) What is a spanning tree ?
C.36 Solved Question Papers
B
D
B
C C
There are three major concepts associated with each spanning tree. There 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 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 route of networks.
Solved Question Papers C.37
Using Kruskals Algorithm 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.
Kruskals Algorithm
1. Set i=1 and let E0={}
2. Select an edge ei of minimum value not in Ei-1 such that Ti=<Ei-1 cup {ei} >is acyclic
C.38 Solved Question Papers
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) What are the various traversals in a tree ?
Ans: Example
Tree traversal are of three types: A
1. In-order traversal
2. Pre-order traversal
D
3. Post-order traversal B
In-order traversal:
In-order traversal is given by following steps. E G
1. Traverse the left sub tree C
2. Process the root node
3. Traverse the right sub-tree F
So the in-order of the binary tree in the figure above is CBAEFDG.
Pre-order traversal Example
Pre-order traversal is defined as follows: A
1. Process the root node
2. Traverse the left sub-tree in pre-order
D
3. Traverse the right sub-tree in pre-order B
Pre-order traversal is A B C D E F G
E G
C
Post-order traversal: D
B
Post-order traversal is defined as follows:
1. Traverse the left sub-tree
2. Traverse the right sub-tree E G
C
3. Process the root node
F
Algorithm for post-order traversal :
Step 1: check if tree is empty by verifying root pointer R. print tree empty if
R=NULL, then print "tree empty"
Step 2: if leftptr(R)!=NULL then call post-order (leftptr(R))
Step 3: print data(R).
Step 4: if rightptr(R)!= NULL then call post-order(rightptr(R))
Step 5: return.