• Tidak ada hasil yang ditemukan

Instructions:

N/A
N/A
Protected

Academic year: 2024

Membagikan "Instructions:"

Copied!
8
0
0

Teks penuh

(1)

CS2110 - July-November 2014 Term Exam - I

22/09/2014

Weightage: ≤ 15% Roll Number:

Instructions:

1. This paper has two parts; an objective and a programming section.

2. You will be given 45 minutesto complete the objective section after which you will have to return your answer papers. After returning your answer papers you will be given 120 minutes to complete the programming section.

3. This is an exam. No form of academic dishonesty will be tolerated.

4. This exam contains 8 pages (including this cover page) and 10 questions.

Total of points is 40.

Grade Table (for official use only - Do not write anything here)

Question: 1 2 3 4 5 6 7 8 9 10 Total

Points: 1 2 1 2 2 1 3 2 12 14 40

Score:

Notes:

1. Assume that for all the code snippets given below, the required libraries such asstdio and stdlibhave been included.

2. When a question asks if a program will compile, ignore any compiler warnings you might get.

1. (1 point) General questions

(a) (0.5 points) What is your mentor’s name?

(b) (0.5 points) 75> x≥60> y >10> z≥0 and x+y+z = 75. One solution is:

(2)

Objective Section

2. (2 points) Consider the following program:

#include <stdio.h>

void swap(int* a, int* b) { int* temp = a;

a = b;

b = temp;

}

int main() { int x = 5;

int y = 4;

swap(&x, &y);

printf("%d %d", x, y);

return 0;

}

(a) (0.5 points) Does this code compile?

Yes.

(b) (0.5 points) Does the code execute without errors?

Yes.

(c) (1 point) After fixing the compile time and/or execution time errors (if any), does the code swap two numbers? If it does, explain why. If it does not, how would you fix it?

It does not, as only the pointers (and not the values pointed to by these pointers) are being swapped inside the swap function, and all changes inside the function are local.

The swap function should be modified to:

int temp = *a;

*a = *b;

*b = temp;

3. (1 point) What can you say about the number that is printed by the following code?

if(((n-1) & n) == 0) printf("%d", n);

The above function checks if n is zero, ifn is a power of 2 i.e n can be written as 2i where i = 0,1,2, . . .. Example: 8 is written as 1000 in binary and 7 is 0111. That would mean that the bit-wise AND would result in a zero whenever we have a case of the above form.

(3)

4. (2 points) Write a functionvoid print nums(int N) (on paper) to print numbers from 1 to N without using a loop.

Solution:

void print_nums (int N) { if (N <= 0) {

printf("Please enter a number greater than 1");

}

else if (N == 1) { printf("%d ", N);

} else {

print_nums(N - 1);

printf("%d ", N);

} }

5. (2 points) Analyze the code.

(a) (1 point) pow3(x) is a macro defined as below, then the output is

#define pow3(x) x*x*x int main() {

int ans = pow3(3+4);

printf("%d", ans);

return 0;

}

pow3(x) is a macro that does text replacement.

pow3(3+4) would result in 3+4*3+4*3+4.

Using BODMAS rules, the answer would be 3+12+12+4 = 31

(b) (1 point) Assume that the user entered the string hello, what is the output of:

int main() { char a[50];

printf(" %d ", scanf("%s", a));

return 0;

}

A. 50 B. 1 C. 5 D. 6

scanf returns the number of arguments read. The answer is option B.

(4)

6. (1 point) What is the most appropriate match for the questions in the next page? The answer could be one among:

• Dangling pointer

• Uninitialized pointer

• Lost memory

• None of the above.

(a) (0.5 points) m=malloc(5); m= NULL;

Lost memory (b) (0.25 points) free(n); n->value=5;

Dangling pointer (Those that do not resolve to a valid destination.) (c) (0.25 points) char *p; *p = ’a’;

Uninitialized memory

7. (3 points) A circular linked list is a modification to a singly linked list where we have the next pointer of the last node in the list pointing to the head of the list instead of pointing to NULL (except when the list is empty). A circular linked list is used to represent a queue. A single variable p is used to access the queue. How would you enqueue and dequeue efficiently using p alone? (You are not required to write any code.)

pis a pointer that points to the end or tail of the circular linked list. Doing so, would enable enqueue and dequeue operations in O(1) time. If p points to the tail:

• enqueue operation for the node pointer n would be:

n->next = p->next;

p->next = n;

p = p->next;

• dequeue operation would be:

Node* n = p->next;

p->next = p->next->next;

return n;

8. (2 points) Find the errors in the code, if any.

(a) (1 point) This code should print values from 16 to 0.

int main () {

unsigned int i = 1 << 4;

for ( ; i >= 0 ; i-- ) { printf("%d",i);

}

(5)

return 0;

}

1<<4 does indeed evaluate to 16 (as it is 24). But the loop never terminates asiis declared as an unsigned integer. After each step the value is decremented and it prints values from 16 to 0, but after that on decrementing an unsigned integer by 1, the value becomes 232−1, and is still greater than or equal to zero. Hence, it goes into an infinite loop. Note that the operator << is the left-shift operator.

(b) (1 point) This code should print 10.

struct Node { int data;

Node* next;

};

int main () {

Node* head = (Node *) malloc(sizeof(Node));

head->data = 10;

head->next = NULL;

Node* temp = head;

while(temp != NULL) {

printf("%d ", temp->data);

temp = temp->next;

}

return 0;

}

The error here is that the following statement is missing:

typedef struct Node Node;

Alternately, one could have used struct Node instead of Node everywhere in the above program.

(6)

Programming Section

9. (12 points) Recall that a stack is a data structure that uses the Last In First Out (LIFO) policy, whereas a queue is a data structure that uses the First In First Out (FIFO) policy.

Use the stacks library (provided to you in the template) write the functions supported by QFS.h in QFS.c. Now using the queue library (provided to you in the template), write the functions supported by SFQ.h in SFQ.c.

In simple words, use (minimum number of) stacks and make a queue, and use (minimum number of) queues to make a stack.

The following is one of the efficient ways to do it.

Using stacks to make a queue:

Let two stacks be S1 and S2.

• To enqueue x:

– Push x into S1.

• To dequeue:

– Error if both stacks are empty.

– IfS2 is non-empty, pop from S2, and return it.

– Else, pop all the elements one by one fromS1 into S2. pop fromS2 and return it.

Using queues to make a stack:

Let two queues be Q1 and Q2.

• Method 1: Pop is costly.

– To push x:

∗ Enqueue x intoQ1. – To pop:

∗ While size ofQ1 is bigger than 1, enqueue the dequeued items fromQ1 intoQ2

∗ Dequeue and return the last item ofQ1, then switch the names of Q1 and Q2.

• Method 2: Push is costly.

– To push x:

∗ Enqueue x intoQ1.

∗ Enqueue all items of Q2 intoQ1, then switch the names of Q1 and Q2. – To pop:

∗ Dequeue from Q2.

(7)

10. (14 points) Recall that Merge Sort is a sorting algorithm, where we have two phases, dividing the given list into smaller lists, and then merging the lists in sorted order. Cre- ate a singly linked list using the linked list library that you have written in the previous assignments to sort the elements in the linked list in ascending order using Merge Sort.

You are not allowed to create an array to sort the elements.

Solution:

// Function to merge two sorted lists

// Input: head of 1st sorted list, head of 2nd sorted list // Output: head of the combined sorted list

Node* merge(Node* head1, Node* head2) { Node* result = NULL;

if(head1 == NULL) { return head2;

}

if(head2 == NULL) { return head1;

}

if(head1->data <= head2->data) { result = head1;

head1->next = merge(head1->next, head2);

} else {

result = head2;

head2->next = merge(head1, head2->next);

}

return result;

}

// This function splits the given list into two.

// Input: head: head of input list

// head1 would then have the head of the first half of list // head2 will have the head of the second half of the list.

void split_list(Node* head, Node** head1, Node** head2) { Node* temp1 = head;

Node* temp2 = head;

Node* prev = NULL;

/*

The idea here is to have a slow pointer and a fast pointer.

Advance the slow pointer by one and the fast pointer by two.

When the fast pointer reaches the end of the list,

the slow pointer would have reached mid way through the list.

*/

if(head == NULL || head->next == NULL) {

*head1 = head;

(8)

*head2 = NULL;

return;

}

while(temp2 != NULL && temp2->next != NULL) { temp2 = temp2->next->next;

prev = temp1;

temp1 = temp1->next;

}

*head1 = head;

*head2 = prev->next;

prev->next = NULL;

}

// Input: head of the unsorted list // Output: head of the sorted list Node* merge_sort_internal(Node* head) {

if(head == NULL || head->next == NULL) { return head;

}

Node* head1 = NULL;

Node* head2 = NULL;

split_list(head, &head1, &head2);

head1 = merge_sort_internal(head1);

head2 = merge_sort_internal(head2);

head = merge(head1, head2);

return head;

}

Referensi

Dokumen terkait

Menambah sebuah node pada doubly linked list. Menghapus sebuah node dari doubly

Jika NEW adalah suatu variabel pointer, maka GETNODE(NEW) akan menyebabkan node yang ditunjuk oleh variabel pointer NEW disisipkan ke dalam linked list..

This section will explain how to enter data in front/behind/middle, delete data, and searching for a data on a Circular Single Linked List... Circular Single

 DLLNC adalah sebuah Linked List yang terdiri dari dua arah pointer, dengan node yang saling terhubung, namun kedua pointernya menunjuk ke NULL.  Setiap node pada

 DLLNC adalah sebuah Linked List yang terdiri dari dua arah pointer, dengan node yang saling terhubung, namun kedua pointernya menunjuk ke NULL.  Setiap node pada

langsung ke node yang dituju, melainkan harus menggunakan suatu pointer penunjuk ke node pertama dalam linked list (dalam hal ini adalah head). Deklarasinya

• Jika NEW adalah suatu variabel pointer, maka GETNODE(NEW) akan menyebabkan node yang ditunjuk oleh variabel pointer NEW disisipkan ke dalam linked list.

Pointer next elemen sebelumnya menunjuk ke elemen baru Insert sebelum node tertentu Statement untuk insert setelah node tertentu dari linked list adalah sebagai berikut: void