0% found this document useful (0 votes)
27 views

Solved Question Paper 3-3

Uploaded by

Sangeta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Solved Question Paper 3-3

Uploaded by

Sangeta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

C Programming and Data Structures

May/June 2008

SET- 3

1. What are different types of control statements available in ‘C’. Explain them with an
example ?
Ans: Control statements are also called as decision making statements. They are
1. If statement
2. Switch and break statements
3. Conditional operator statement
4. Go to statement
Let us discuss these statements in detail with examples.

If Statement

If statement is a powerful decision making statement and is called to control the flow of execution
of statements. It is implemented in different forms

Simple If

General form: if(expression)


{
Statements ;
}
Statements;

true
If
expression statements

false
statements

statements
C.40 Solved Question Papers

Example:
Main ()
{
Int a,b,c,d;
float ratio;
printf(enter the values");
scanf("%d%d%d",&a,&b,&c);
if(c-d!=0)
{
Ratio=(float(a+b)/float(c-d));
Printf("ratio=%f",ratio);
}

If Else Statement

General form:
If(expression)
{
True block
}
Else
{
False block
}
Statements;

false
If
False block
expression

true
statements

statements

Example:
If(c-d!=0)
{
Ratio=float(a+b)/float(c-d);
Printf("ratio=%f",ratio);
}
Else
Printf("c-d is zero");
}
Solved Question Papers C.41

Nested or if Else Statement

General form:

If(condition 1)
{
If(condition 2)
{
Statement 1;
}
Else
{
Statement 2;
}
Else
{
Statement 3;
}
Statement x;

In nested if else series if decisions are involved. It has more than one if else statements.

false true
If
condition 1

Statement 3
Condition 2

Statement 2 Statement 1

Statement

Example:
Main()
{
Float a,b,c;
Printf("enter the values");
Scanf("%F%f%f",&a,&b,&c);
Printf("largest value is");
If(a>b)
{
If(a>c)
C.42 Solved Question Papers

Printf("%f",a);
Else
Printf("%f",c);
}
Else
{
If(c>b)
Printf("%f",c);
Else
Printf("%f",b);
}
}

Else if Lader

General form:
If(condition 1)
Statement 1;
Else if(condition 2)
Statement 2;
Else if(condition 3)
Statement 3;
Else if(condition n)
Statement n;
Else
Default statement;
Statements;
Here, the conditions are evaluated from the top document cards.

Cond 1

Statement 1 Cond 2

Statement 2 Default
Cond 3 statement
Statement 3

Statements

Next Statement

Example:
Main()
{
Int units, custno;
Solved Question Papers C.43

Float charges;
Printf("enter custno and units");
Scanf("%d%d",&custno,&units);
If(units<=200)
Charges=0.5 units;
Else if(units<=400)
Charges =100+0..6s(units-200);
Else if(units<=600)
Charges=390+units-600;
Printf("custno %d", charges =%f", custno,charges);
}

Switch and Break Statements

General form:
Switch(expression)
{
Case 1:
Statements;
Break;
Case 2 :
Statements;
Break;
Default :
Statements:
Break;
}
Statements;

Switch
expression

yes
Case1 Block 1

no yes

Case2 Block 2

no

Default

Statements
C.44 Solved Question Papers

Example:
Switch(choice)
{
Case 1 ''+':
C=a+b;
Break;
Case '-':
C=a-b;
Break;
Default:
Printf("operation not possible");
}

Conditional Operator Statement

General form:
Conditional expression ? expression 1: expression 2
Example:
Flag(x<0) ? 0:1;
Salary= 4x+100 for x<40
300 for x=40
4.5x+150 for x>40
The data can be written as
Salary=(x!=40)?(x<40)?(4*x+100)L4.5*x+150):300;

Go to Statement

Go to requires a label in order to identify the place where the branch is to be made. A label is any
valid variable name
Example:
Main ()
{
Double x,y;
Read:
Scanf("%f",&x);
If(x<0) goto read;
Y=sqrt(x);
Printf("%f%f",x,y);
Go to read;
}
2. (a) Write a brief note on auto and static storage classes?
Ans: Variables in C language are not only data type but are also of storage class that provides
information about their location and visibility. The storage class decides the portion of the
program within which the variables are recognised.
Solved Question Papers C.45

Example:
int m;
main ()
{
Int I;
Float balance;
}

The variable m which has been declared before the main is called global variable. It can be
used in all the functions in the program. It need not be declared in other functions. A global
variable is also known as external variable. The variables I and balance are called local
variables. They are visible only inside functions in which they are declared.
‘C’ provides a variety of storage class specifiers that can be used to declare explicitly the
scope and lifetime of variables. The concept of scope and lifetime are important only in mal-
functioning and multiple file programming.

Four storage class specifiers are Auto, register, static, and extern.
Auto: Local variable known only to the function in which if is declared, default is auto.
Declaration:
Auto int x;
Auto variables have garbage values unless they are initialized explicitly.
Static: Local variable which exists and retains its value even after the control is
transferred to the calling function.
Declaration:
Static int x;
Static and extern variables are initialized automatically to zero.
(b) Write a short note on call by reference?
Ans: Functions are of four types
1. with argument with return
2. no argument with return
3. with argument no return
4. no argument no return
While using with arguments case, the arguments may be passed as direct values. Sometimes
they are passed with their address. This type of passing address of variable is called call by
reference.
Using the pointers in function, we can pass the address of variables in the functions.
Example:
Main()
{
Int x,y;
X=100;
C.46 Solved Question Papers

Y=200;
Printf("before exchange x:%d y: %d", x,y) ;
Exchange(&x,&y);
Printf("after exchange: x=%d y=%d",x,y);
}
Exchange(a,b)
Int *a,*b;
{
Int t;
T=*a;
*a=*b;
*b=t;
}
3. What is an array? What are the different types of arrays? Explain.
Ans: An array is a group of related data items that share a common name. All the elements should
be of same data type.
Different types of arrays are:
1. one-dimensional arrays
2. two-dimensional arrays
3. multi-dimensional arrays
Let us discuss about them in detail.

One-dimensional arrays

A list of items can be given one variable name using only one subscript and such a variable is called
a single subscripted variable or a one-dimensional array.

Accessing

Values can be initialized to arrays as three types


(i) direct :
N[0]=1
N[1]=2
N[2]=3

(ii) n[3]={0,1,2};
(iii) using for loop:
for(i=0;i<3;i++)
scanf("%d",&n[i]);
n[4]= n[0]+n[2];
n[6]= n[i]+3;
Solved Question Papers C.47

Declaration

General form is type variable name[size]


Example: float height[50];
Program
main()
{
Int I;
Float x[10], value, total;
Printf("enter 10 real no");
For(i=0;i<10;i++)
{
Scanf("%f", &value);
X[i]=value;
}
Total=0.0;
For(i=0;i<10;i++)
Printf(""x[%2d]=%st",i+1,x[i]);
Printf("total=%2f",total);
}

Two-Dimensional Arrays

Initializing

They have elements in rows and columns.


Two-dimensional arrays may be initialized by following methods.

N[2] [3]={0,0,0,1,1,1,};
N[2][3]={{0,0,0},{1,1,1}};
(OR)
N[2][3]={
{0,0,0},
{1,1,1},
};
Declaration:
Type array name[row size][column size];

Program
/*To perform the matrix addition by using two-dimensional arrays */
Main ()
{
Int a[50][50], b[50][50],c[100][100],I,j,k;
Printf("enter the elements");
C.48 Solved Question Papers

For(i=0;i<3;i++)
For(j=0;j<3;j++)
Scanf("%d",&a[i][j]);
For(i=0;i<3;i++)
For(j=0;j<3;j++)
Scanf("%d",&b[i][j]);
C[i][j]=0;
For(i=0;i<3;i++)
For(j=0;j<3;j++)
{
C[i][j]=a[i][j]+b[i][j];
Printf("\n");
}
Printf("%d",c[i][j]);
}

Multi-Dimensional Arrays

Declaration

Type array name [s1] [s2] ..[sm];


Example: int survey[3][5][12];
Float table[5][4][3];
4. Define structure and write the general format for declaring and accessing members?
Ans: Structure can store data items in consequent memory locations. The advantage of structures
is that the data items may be of different data types.
Declaring structures:
Struct student
{
Char name[20];
Int stno; (1)
};

Memory allocation is as follows:

Struct tagname
{
Data type n1;
Datatype n2;
};

In the case of (1) no memory allocation is not done, only the structure is defined for
allocating.
Solved Question Papers C.49

Struct bokkbank
{
Char title[20];
Char author[15];
Int pages;
Float price;
};
Struct bokbankk bookk1,book2,bok3;
Tag name is optional.

Giving values to members:


The link between a member and a variable is established by using 'dot operator' or 'period
operator'.
Book1.pages=250;
Book1.price=28.50;
Also initialized using scanf( ) statement
Scanf("%s",book1.title);
Scanf("%d",bok1.pages);

Structure initialization:
Main ()
{
Static struct
{
Int weight;
Float height;
}
Student={60,180,75};
-----------------
-----------------
}
Also can be initialized as
Main ()
{
Struct st_record
{
Int weight;
Float height;
};
Static struct st_record st1={60,180,75};
Static struct st_record st2={53,170,60};
-------------
-------------
C.50 Solved Question Papers

}
(OR)

Struct st_recrd
{
Int weight;
Float height;
} st1={60,180,75};
Main (0
{
Static struct st_recrd st2={53,170,60};
---------------
----------------
}
Accessing members of structure:
Structure members can be accessed by writing variable name.member
Dot( . ) operator links structure 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.51

Printf("details of employee one =%c%c%d",emp1.name ,emp1.designation,


emp1.sal);
Printf("details of employee one =%c%c%d",emp2.name ,emp2.designation,
emp2.sal);
}

5. What is purpose of library function feof()? How is feof() utilized within a program that
updates an unformatted data file. Explain.
Ans: Feof ( ) is a library function which represents end of file. It is an error handling function. It
gives the end of data in a file. The file pointer moves by one character position for every
operation of getc or putc. The getc will return an end of file marker eof, when end of the file
has been reached. Therefore, the reading should be terminated when eof is encountered.

Program
#include<stdio.h>
Main()
{
FILE *f1;
Char c;
Printf("data input");
F1=fpen("input file", "w");
While(c=getchar()!=eof)
Putc(,f1);
Fclose(f1);
Printf("data utput");
F1=fpen("input",: "r");
While(c=getc(f1)!=eof)
Printf("%c",c);
Fclose(f1);
}

The file input is reopened for reading. The program then reads its context character by
character and displays it on the screen. Reading is terminated when gets encounters the end of
file of mark. Like scanf, fscanf also returns the numbers of items that are successfully read.
When the end of the file is reached, it returns the value eof.

6. Write a program to sort the elements whose worst and average case is o(n log n)?
Ans: The sorting technique which has worst and average case o(n log n) is merge sort.
The merge sort is the sorting technique used to merge two sorted lists. If sorted lists are not
given, first lists are to be sorted individually using any sorting techniques.
Of all sorting techniques, quick sort is most efficient for sorting purpose.

Program
#include <stdio.h>
C.52 Solved Question Papers

#include <conio.h>

#define MAX_ARY 10

void merge_sort(int x[], int end, int start);


int main(void) {
int ary[MAX_ARY];
int j = 0;

printf("\n\nEnter the elements to be sorted: \n");


for(j=0;j<MAX_ARY;j++)
scanf("%d",&ary[j]);

/* array before mergesort */


printf("Before :");
for(j = 0; j < MAX_ARY; j++)
printf(" %d", ary[j]);

printf("\n");
merge_sort(ary, 0, MAX_ARY - 1);

/* array after mergesort */


printf("After Merge Sort :");
for(j = 0; j < MAX_ARY; j++)
printf(" %d", ary[j]);

printf("\n");
getch();
}

/* Method to implement Merge Sort*/


void merge_sort(int x[], int end, int start) {

int j = 0;
const int size = start - end + 1;
int mid = 0;
int mrg1 = 0;
int mrg2 = 0;
int executing[MAX_ARY];

if(end == start)
return;
mid = (end + start) / 2;
Solved Question Papers C.53

merge_sort(x, end, mid);


merge_sort(x, mid + 1, start);

for(j = 0; j < size; j++)


executing[j] = x[end + j];

mrg1 = 0;
mrg2 = mid - end + 1;

for(j = 0; j < size; j++) {


if(mrg2 <= start - end)
if(mrg1 <= mid - end)
if(executing[mrg1] > executing[mrg2])
x[j + end] = executing[mrg2++];
else
x[j + end] = executing[mrg1++];
else
x[j + end] = executing[mrg2++];
else
x[j + end] = executing[mrg1++];
}
}

If the given two lists are not sorted lists, sort the lists using quick sort.

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)
C.54 Solved Question Papers

{
int pivot,i,j,t;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
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);
}
}

Merge Sort Process

A = {56,78};
B = {45,67,89} two sorted lists.
C = {45,56,67,78,89}

A 56, 78
B 45, 67, 89
C 45 56

A 56, 78
B 45, 67, 89
C 45 56
A 56 78
B 45 67 89
C 45 56 67
Solved Question Papers C.55

A 56 78
B 45 67 89
C 45 56 67 78

C = {45,56,67,78,89} is the final sorted list using merge sort.

7. Give an algorithm/C program to reverse a singly linked circular list in place.


Ans: Circular linked list: The small change to the structure of a linear list such that the link field
in the last node contains a pointer back to the first node rather than a NULL. Such a list is
called a circular linked list.

10 17 18 5

Here is the routine which reverses circular list.


typedef struct node Node;

void reverse(Node** headRef)


{
Node* result = NULL;
Node* current = *headRef;
Node* next;

while (current != NULL)


{
next = current->next; // tricky: note the next node
current->next = result; // move the node onto the result
result = current;
current = next;
if (current == *headRef)
{
//met the beginning node...
break;
}
}
(*headRef)->next = result;
*headRef = result;
}
C.56 Solved Question Papers

Program
#include<conio.h>
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
struct node *root;
void addnode()
{
int item;
struct node *newnode,*p;
printf("\n Enter the item");
scanf("%d", &item);
newnode=(struct node*) malloc(sizeof(struct node));
newnode->data=item;
newnode->next=NULL;
if(root==NULL)
{
root=newnode;
return;
}
____ _________ ________
p=root;
while(p->next!=NULL)
p=p->next;
p->next=newnode;
}
void display()
{
struct node*p=root;
while(p!=NULL)
{
printf("\n %d ",p->data);
p=p->next;
}
}
void reverse()
{
struct node *p,*oldnode=NULL,*newnode;
p=root;
while(p!=NULL)
Solved Question Papers C.57

{
newnode=p;
p=p->next;
if(oldnode==NULL)
{
oldnode=newnode;
oldnode->next=NULL;
}
else
{
newnode->next=oldnode;
oldnode=newnode;
}
}
root=oldnode;
}
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
addnode();
}
printf("\nbefore reverse");
display();
printf("\n After reverse");
reverse();
display();
return 0;
}
8. Write an algorithm to perform deletion operation in a binary tree search?
Ans: There are four possible cases that we need to consider
(a) No node in the tree contains the specified data
(b) The node containing the data has no children
(c) The node containing data has exactly one child
(d) The node containing data has two children
Case a: We merely need to print the message that data item is not present in the tree.
Case b: Since the node to be deleted has no children, the memory occupied by this should be
freed and either the left link or right link of parent of this node should be set to NULL. Which
of these to set to NULLL, depends upon whether the node being deleted is a left child or a
right child of its parent.
C.58 Solved Question Papers

Case c: Since the node to be deleted has one child, the solution is again rather simple. We
have to adjust the pointer of the parent of the node to be deleted, such that after deletion it
points to child of node being deleted.

20
23
17
25
6 18
20 29
10 24
5
17 23
9
25
6 18 After deletion
24 29
5 8
10
9
Before deletion

Case d: Since the node to be deleted has two children, the solution is more complex. The
whole logic of deleting a node with two children is to locate the in-order successor, copy its
data and reduce the problem to a simple deletion of a node with one or zero child.

20
23
17
18 25
6
24 29 20
5 8 23
17
10 25
7 6 18
9 24
29
Before deletion 5 9
7 10

After deletion

Algorithm to perform deletion operation in a binary search tree.


ALGORITHM:
Step 1: Start
Step 2: Define a structure btree
Step 3: Type define struct btree as node
Step 4: While(tree), begin
Step 5: Print MENU
Step 6: Write your choice
Solved Question Papers C.59

Step 7: If choice=1
Step 8: Enter your no of nodes
Step 9: Read nodes n
Step 10: for i=1 to n in steps of 1 do
Step 11: Print enter item
Step 12: Read item
Step 13: Root =call create (root, item).end for
Step 14: if choice=2
Step 15: Read element to be deleted
Step 16: Call delete(root, item) end for
Step 17: If choice=3
Step 18: Call preorder(root)
Step 19: Call postorder(root)
Step 20: Call inorder(root)
Step 21: Break, end of switch
Step 22: Stop

For insert function


Step 1: Start
Step 2: If t= null

Step 3: Allocate memory to temp

Step 4: Temp->data =item

Step 5: Temp-> lc=null

Step 6: Temp->rc=null

Step 7: return t to main and end

Step 8: If item< (l->data)

Step 9: T->lc=call insert(e->lc, t)


C.60 Solved Question Papers

Step 10: T->rc=call insert(e->lc,t)

Step 11: Return t

Step 12: Stop

For DELETION function


Step 1: Start
Step 2: x=d
Step 3: while x!=null
Step 4: If x->data =t
Strep5: Break
Step 6: Parent =x
Step 7: if t<x->data
Step 8: t=tÆlc
Step 9: t=lÆrc
Step 10: If xÆlc!=null &&xÆrc!=null
Step 11: parent =x
Step 12: If parent==null
Step 13: parentÆlc==null
Step 14: parentÆrc==null
Step 15: If p->lc=x->rc
Step 16: If p->rc=x->rc
Step 17: While insert->lc=null
Step 18: Insert=insert->la
Step 19: x->data=insert->data
Step 20: x=insert
Step 21: Return d
Step 22: Stop
Solved Question Papers C.61

Processing to perform deletion operation in a binary search tree.

Binary tree before deletion


7 8 9 10 11 12 13 14 15
Delete element 10
Binary tree after deletion
7 8 9 11 12 13 14 15

You might also like