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

Data Structure

The document provides information about C programming concepts including sample code snippets and questions from previous GATE exams. Some key points: 1. A sample C program is provided to demonstrate that without a break statement in a switch case, all subsequent cases will execute until a break is found. 2. Questions from past GATE exams are presented related to C programming concepts like scope rules, static variables, recursion, pointers, arrays and more. Sample programs and explanations of output are given for each question. 3. Time complexity analysis is done for two recursive functions - one to calculate Fibonacci numbers has time complexity of O(2^n) while another using arrays has time complexity of O(n).

Uploaded by

lokenders801
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
181 views

Data Structure

The document provides information about C programming concepts including sample code snippets and questions from previous GATE exams. Some key points: 1. A sample C program is provided to demonstrate that without a break statement in a switch case, all subsequent cases will execute until a break is found. 2. Questions from past GATE exams are presented related to C programming concepts like scope rules, static variables, recursion, pointers, arrays and more. Sample programs and explanations of output are given for each question. 3. Time complexity analysis is done for two recursive functions - one to calculate Fibonacci numbers has time complexity of O(2^n) while another using arrays has time complexity of O(n).

Uploaded by

lokenders801
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

C PROGRAMING

1. What will be the output of the following C program segment?

(2012)

char inchar = 'A';


switch (inchar)
{
case 'A' :
printf ("choice A \n") ;
case 'B' :
printf ("choice B ") ;
case 'C' :
case 'D' :
case 'E' :
default:
printf ("No Choice") ;
}
(A) No choice
(B) Choice A
(C) Choice A
Choice B No choice
(D) Program gives no output as it is erroneous
Answer (C)
There is no break statement in case A. If a case is executed and it doesnt contain break, then all the
subsequent cases are executed until a break statement is found. That is why everything inside the switch is
printed.
Try following program as an exercise.
int main()
{
char inchar = 'A';
switch (inchar)
{
case 'A' :
printf ("choice A \n") ;
case 'B' :
{
printf ("choice B") ;
break;
}
case 'C' :
case 'D' :
case 'E' :
default:
printf ("No Choice") ;
}
}
2. Consider the following C program
int a, b, c = 0;
IT DEPARTMENT

(2012)
GATE MATERIAL

void prtFun (void);


int main ()
{
static int a = 1; /* line 1 */
prtFun();
a += 1;
prtFun();
printf ( "\n %d %d " , a, b) ;
}
void prtFun (void)
{
static int a = 2; /* line 2 */
int b = 1;
a += ++b;
printf (" \n %d %d " , a, b);
}
What output will be generated by the given code segment?
(A) 3 1
41
42
(B) 4 2
61
61
(C) 4 2
62
20
(D) 3 1
52
52
Answer (C)
a and b are global variable. prtFun() also has a and b as local variables. The local variables hide the
globals (See Scope rules in C). When prtFun() is called first time, the local b becomes 2 and local a
becomes 4.
When prtFun() is called second time, same instance of local static a is used and a new instance of b is
created because a is static and b is non-static. So b becomes 2 again and a becomes 6.
main() also has its own local static variable named a that hides the global a in main. The printf() statement
in main() accesses the local a and prints its value. The same printf() statement accesses the global b as there
is no local variable named b in main. Also, the defaut value of static and global int variables is 0. That is why
the printf statement in main() prints 0 as value of b.
3. What output will be generated by the given code d\segment if:
Line 1 is replaced by auto int a = 1;
Line 2 is replaced by register int a = 2;
(A) 3 1
41
42
(B) 4 2
61
IT DEPARTMENT

(2012)

GATE MATERIAL

61
(C) 4 2
62
20
(D) 4 2
42
20
Answer (D)
If we replace line 1 by auto int a = 1; and line 2 by register int a = 2;, then a becomes non-static in
prtFun(). The output of first prtFun() remains same. But, the output of second prtFun() call is changed as a new
instance of a is created in second call. So 4 2 is printed again. Finally, the printf() in main will print 2 0.
Making a a register variable wont change anything in output.
4. What does the following fragment of C-program print?
char c[] = "GATE2011";
char *p =c;
printf("%s", p + p[3] - p[1]) ;
(A) GATE2011
(B) E2011
(C) 2011
(D) 011
Answer: (C)
See comments for explanation.
char c[] = "GATE2011";

(2011)

// p now has the base address string "GATE2011"


char *p =c;
// p[3] is 'E' and p[1] is 'A'.
// p[3] - p[1] = ASCII value of 'E' - ASCII value of 'A' = 4
// So the expression p + p[3] - p[1] becomes p + 4 which is
// base address of string "2011"
printf("%s", p + p[3] - p[1]) ;

5. Consider the following recursive C function that takes two arguments


(2011)
unsigned int foo(unsigned int n, unsigned int r) {
if (n > 0) return (n%r + foo (n/r, r ));
else return 0;
}
What is the return value of the function foo when it is called as foo(513, 2)?
(A) 9
(B) 8
(C) 5
(D) 2
Answer: (D)
foo(513, 2) will return 1 + foo(256, 2). All subsequent recursive calls (including foo(256, 2)) will return 0 +
foo(n/2, 2) except the last call foo(1, 2) . The last call foo(1, 2) returns 1. So, the value returned by foo(513, 2)
IT DEPARTMENT

GATE MATERIAL

is 1 + 0 + 0. + 0 + 1.
The function foo(n, 2) basically returns sum of bits (or count of set bits) in the number n.
6. What is the return value of the function foo when it is called as foo(345, 10) ? (2011)
(A) 345
(B) 12
(C) 5
(D) 3
Answer: (B)
The call foo(345, 10) returns sum of decimal digits (because r is 10) in the number n. Sum of digits for 345 is 3
+ 4 + 5 = 12.
Following questions have been asked in GATE CS 2010 exam.
7. What does the following program print?
(2010)
#include<stdio.h>
void f(int *p, int *q)
{
p = q;
*p = 2;
}
int i = 0, j = 1;
int main()
{
f(&i, &j);
printf("%d %d \n", i, j);
getchar();
return 0;
}
(A) 2 2
(B) 2 1
(C) 0 1
(D) 0 2
Answer (D)
See below f() with comments for explanation.
/* p points to i and q points to j */
void f(int *p, int *q)
{
p = q; /* p also points to j now */
*p = 2; /* Value of j is changed to 2 now */
}
8. What is the value printed by the following C program?
(2010)
#include<stdio.h>
int f(int *a, int n)
{
if(n <= 0) return 0;
else if(*a % 2 == 0) return *a + f(a+1, n-1);
else return *a - f(a+1, n-1);
}
int main()
{
IT DEPARTMENT

GATE MATERIAL

int a[] = {12, 7, 13, 4, 11, 6};


printf("%d", f(a, 6));
getchar();
return 0;
}
(A) -9
(B) 5
(C) 15
(D) 19
Answer (C)
f() is a recursive function which adds f(a+1, n-1) to *a if *a is even. If *a is odd then f() subtracts f(a+1, n-1)
from *a. See below recursion tree for execution of f(a, 6).
.
f(add(12), 6) /*Since 12 is first element. a contains address of 12 */
|
|
12 + f(add(7), 5) /* Since 7 is the next element, a+1 contains address of 7 */
|
|
7 - f(add(13), 4)
|
|
13 - f(add(4), 3)
|
|
4 + f(add(11), 2)
|
|
11 - f(add(6), 1)
|
|
6+0
So, the final returned value is 12 + (7 (13 (4 + (11 (6 + 0))))) = 15
Following questions have been asked in GATE CS 2008 exam.
9. What is printed by the following C program?
(2008)
int f(int x, int *py, int **ppz)
{
int y, z;
**ppz += 1;
z = **ppz;
*py += 2;
y = *py;
x += 3;
return x + y + z;
}
void main()
{
int c, *b, **a;
IT DEPARTMENT

GATE MATERIAL

c = 4;
b = &c;
a = &b;
printf( "%d", f(c,b,a));
getchar();
}
(A) 18
(B) 19
(C) 21
(D) 22
Answer (B)
/* Explanation for the answer */
/*below line changes value of c to 5. Note that x remains unaffected
by this change as x is a copy of c and address of x is different from c*/
**ppz += 1
/* z is changed to 5*/
z = **ppz;
/* changes c to 7, x is not changed */
*py += 2;
/* y is changed to 7*/
y = *py;
/* x is incremented by 3 */
x += 3;
/* return 7 + 7 + 5*/
return x + y + z;
10. Choose the correct option to fill ?1 and ?2 so that the program below prints an input string in
reverse order. Assume that the input string is terminated by a newline character.
(2008)
void reverse(void)
{
int c;
if (?1) reverse() ;
?2
}
main()
{
printf ("Enter Text ") ;
printf ("\n") ;
reverse();
printf ("\n") ;
}
(A) ?1 is (getchar() != \n)
?2 is getchar(c);
IT DEPARTMENT

GATE MATERIAL

(B) ?1 is (c = getchar() ) != \n)


?2 is getchar(c);
(C) ?1 is (c != \n)
?2 is putchar(c);
(D) ?1 is ((c = getchar()) != \n)
?2 is putchar(c);
Answer(D)
getchar() is used to get the input character from the user and putchar() to print the entered character, but before
printing reverse is called again and again until \n is entered. When \n is entered the functions from the
function stack run putchar() statements one by one. Therefore, last entered character is printed first.
You can try running below program
void reverse(void); /* function prototype */
void reverse(void)
{
int c;
if (((c = getchar()) != '\n'))
reverse();
putchar(c);
}
main()
{
printf ("Enter Text ") ;
printf ("\n") ;
reverse();
printf ("\n") ;
getchar();
}
For questions 11 & 12, consider the following C functions:
int f1(int n)
{
if(n == 0 || n == 1)
return n;
else
return (2*f1(n-1) + 3*f1(n-2));
}
int f2(int n)
{
int i;
int X[N], Y[N], Z[N] ;
X[0] = Y[0] = Z[0] = 0;
X[1] = 1; Y[1] = 2; Z[1] = 3;
for(i = 2; i <= n; i++)
{
X[i] = Y[i-1] + Z[i-2];
Y[i] = 2*X[i];
Z[i] = 3*X[i];
IT DEPARTMENT

GATE MATERIAL

}
return X[n] ;
}
11. The running time of f1(n) and f2(n) are
(2008)
(A) (n) and (n)
(B) (2^n) and (n)
(C) (n) and (2^n)
(D) (2^n) and (2^n)
Answer (B)
For f1(), let T(n) be the function for time complexity.
T(n) = T(n-1) + T(n-2)
Above recursion is a standard one for Fibonacci Numbers. After solving the recursion, we get
T(n) = 1/sqrt(5)[(1 + sqrt(5))/2]^n - 1/sqrt(5)[(1 - sqrt(5))/2]^n
Above recursion can also be written as (1.618.^n)
(Please see this).
In f2(), there is a single loop, so time complexity is (n)
Among all the 4 given choices, (B) looks closest.

12. f1(8) and f2(8) return the values


(2008)
(A) 1661 and 1640
(B) 59 and 59
(C) 1640 and 1640
(D) 1640 and 1661
Both functions perform same operation, so output is same, means either (B) or (C) is correct.
f1(2) = 2*f1(1) + 3*f1(0) = 2
f1(3) = 2*f1(2) + 3*f1(1) = 2*2 + 3*1 = 7
f1(4) = 2*f1(3) + 3*f1(2) = 2*7 + 3*2 = 20
f1(5) = 2*f1(4) + 3*f1(3) = 2*20 + 3*7 = 40 + 21 = 61
We can skip after this as the only remaining choice is (C)
f1(6) = 2*f1(5) + 3*f1(4) = 2*61 + 3*20 = 122 + 60 = 182
f1(7) = 2*f1(6) + 3*f1(5) = 2*182 + 3*61 = 364 + 183 = 547
f1(8) = 2*f1(7) + 3*f1(6) = 2*547 + 3*182 = 1094 + 546 = 1640
Following questions have been asked in GATE CS 2006 exam.
13. Consider the following C-program fragment in which i, j and n are integer variables. (2006)
for (i = n, j = 0; i >0; i /= 2, j += i);
Let val(j) denote the value stored in the variable j after termination of the for loop. Which one of the
following is true?
(A) val(j) = (logn)
(B) vaI(j) = (sqrt(n))
(C) val(j) = (n)
(D) val(j) = (nlogn)
Answer (C)
Note the semicolon after the for loop, so there is nothing in the body. The variable j is initially 0 and value of j
is sum of values of i. i is initialized as n and is reduced to half in each iteration.
j = n/2 + n/4 + n/8 + .. + 1 = (n)
IT DEPARTMENT

GATE MATERIAL

14. Consider the following C-function in which a[n] and b[m] are two sorted integer arrays and c[n +
m] be another integer array.
2006
void xyz(int a[], int b [], int c[])
{
int i, j, k;
i = j = k = O;
while ((i<n) && (j<m))
if (a[i] < b[j]) c[k++] = a[i++];
else c[k++] = b[j++];
}
Which of the following condition(s) hold(s) after the termination of the while loop?
(i) j < m, k = n+j-1, and a[n-1] < b[j] if i = n
(ii) i < n, k = m+i-1, and b[m-1] <= a[i] if j = m
(A) only (i)
(B) only (ii)
(C) either (i) or (ii) but not both
(D) neither (i) nor (ii)
Answer (C)
The condition (i) is true if the last inserted element in c[] is from a[] and condition (ii) is true if the last inserted
element is from b[].

15. Consider this C code to swap two integers and these five statements: the code
2006
void swap(int *px, int *py)
{
*px = *px - *py;
*py = *px + *py;
*px = *py - *px;
}
S1: will generate a compilation error
S2: may generate a segmentation fault at runtime depending on the arguments passed
S3: correctly implements the swap procedure for all input pointers referring to integers stored in memory
locations accessible to the process
S4: implements the swap procedure correctly for some but not all valid input pointers
S5: may add or subtract integers and pointers.
(A) S1
(B) S2 and S3
(C) S2 and S4
(D) S2 and S5
Answer (C)
S2: May generate segmentation fault if value at pointers px or py is constant or px or py points to a memory
location that is invalid
S4: May not work for all inputs as arithmetic overflow can occur.
IT DEPARTMENT

GATE MATERIAL

16. In the C language (GATE CS 2002)


a) At most one activation record exists between the current activation record and the activation record
for the main
b) The number of activation records between the current activation record and the activation record for
the main depends on the actual function calling sequence.
c) The visibility of global variables depends on the actual function calling sequence.
d) Recursion requires the activation record for the recursive function to be saved on a different stack
before the recursive function can be called.
Answer(b)
a) > There is no such restriction in C language
b) > True
c) > False. In C, variables are statically scoped, not dynamically.
c) > False. The activation records are stored on the same stack.
17. Consider the C program shown below.
(GATE CS 2003)
# include <stdio.h>
# define print(x) printf ("%d", x)
int x;
void Q(int z)
{
z += x;
print(z);
}
void P(int *y)
{
int x = *y+2;
Q(x);
*y = x-1;
print(x);
}
main(void)
{
x=5;
P(&x);
print(x);
getchar();
}
The output of this program is
a) 1276
b) 22 12 11
c) 14 6 6
d) 766
Answer (a)
Note that main() and Q() are accessing the global variable x. Inside P(), pointer variable y also holds address of
global variable x, but x in P() is its Ps own local variable.
18. Consider the following C program segment:
(GATE CS 2004)
char p[20];
char *s = "string";
int length = strlen(s);
IT DEPARTMENT

GATE MATERIAL

int i;
for (i = 0; i < length; i++)
p[i] = s[length i];
printf("%s",p);
The output of the program is
a) gnirts
b) gnirt
c) string
d) no output is printed
Answer(d)
Let us consider below line inside the for loop
p[i] = s[length i];
For i = 0, p[i] will be s[6 0] and s[6] is \0
So p[0] becomes \0. It doesnt matter what comes in p[1], p[2].. as P[0] will not change for i >0. Nothing is
printed if we print a string with first character \0
19. Consider the following C function
void swap (int a, int b)
(GATE CS 2004)
{
int temp;
temp = a;
a = b;
b = temp;
}
In order to exchange the values of two variables x and y.
a) call swap (x, y)
b) call swap (&x, &y)
c) swap (x,y) cannot be used as it does not return any value
d) swap (x,y) cannot be used as the parameters are passed by value
Answer(d)
Why a, b and c are incorrect?
a) call swap (x, y) will not cause any effect on x and y as parameters are passed by value.
b) call swap (&x, &y) will no work as function swap() expects values not addresses (or pointers).
c) swap (x, y) cannot be used but reason given is not correct.
20. Consider the following C function:
int f(int n)
(GATE CS 2004)
{
static int i = 1;
if (n >= 5)
return n;
n = n+i;
i++;
return f(n);
}
The value returned by f(1) is
a) 5
b) 6
c) 7
d) 8
IT DEPARTMENT

GATE MATERIAL

Answer (c)
Since i is static, first line of f() is executed only once.
Execution of f(1)
i=1
n=2
i=2
Call f(2)
i=2
n=4
i=3
Call f(4)
i=3
n=7
i=4
Call f(7)
since n >= 5 return n(7)
21. Consider the following program fragment for reversing the digits in a given integer to obtain a
new integer. Let n = D1D2Dm
int n, rev;
rev = 0;
(GATE CS 2004)
while (n > 0)
{
rev = rev*10 + n%10;
n = n/10;
}
The loop invariant condition at the end of the ith iteration is:
a) n = D1D2.Dm-i and rev = DmDm-1Dm-i+1
b) n = Dm-i+1Dm-1Dm and rev = Dm-1.D2D1
c) n rev
d) n = D1D2.Dm and rev = DmDm-1D2D1
Answer (a)
22. Consider the following C program
main()
(GATE CS 2004)
{
int x, y, m, n;
scanf ("%d %d", &x, &y);
/* x > 0 and y > 0 */
m = x; n = y;
while (m != n)
{
if(m>n)
m = m - n;
else
n = n - m;
}
printf("%d", n);
}
The program computes
a) x + y using repeated subtraction
IT DEPARTMENT

GATE MATERIAL

b) x mod y using repeated subtraction


c) the greatest common divisor of x and y
d) the least common multiple of x and y
Answer(c)
This is an implementation of Euclids algorithm to find GCD
23. Consider the following three C functions :
(GATE 2001)
[PI] int * g (void)
{
int x = 10;
return (&x);
}
[P2] int * g (void)
{
int * px;
*px = 10;
return px;
}
[P3] int *g (void)
{
int *px;
px = (int *) malloc (sizeof(int));
*px = 10;
return px;
}
Which of the above three functions are likely to cause problems with pointers?
(a) Only P3
(b) Only P1 and P3
(c) Only P1 and P2
(d) P1, P2 and P3
Answer: (c)
Eplaination: In P1, variable x is a local variable to g(), and g() returns address of this variable. x will vanish
after g() has returned as x exists on stack. So, &x will become a dangling pointer.
In P2, pointer variable px is being assigned a value without allocating memory to it.
P3 works perfectly fine. Memory is allocated to pointer variable px using malloc(). So, px exists on heap, its
existence will remain in memory even after return of g() as it is on heap.
24. The value of j at the end of the execution of the following C program. (GATE CS 2000)
int incr (int i)
{
static int count = 0;
count = count + i;
return (count);
}
main ()
{
int i,j;
for (i = 0; i <=4; i++)
IT DEPARTMENT

GATE MATERIAL

j = incr(i);
}
(a) 10
(b) 4
(c) 6
(d) 7
Answer (a)
Eplaination: count is static variable in incr(). Statement static int count = 0 will assign count to 0 only in first
call. Other calls to this function will take the old values of count.
Count will become 0 after the call incr(0)
Count will become 1 after the call incr(1)
Count will become 3 after the call incr(2)
Count will become 6 after the call incr(3)
Count will become 10 after the call incr(4)
25. Consider the following C declaration
(GATE CS 2000)
struct {
short s [5]
union {
float y;
long z;
}u;
} t;
Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively.
The memory requirement for variable t, ignoring alignment
considerations, is
(a) 22 bytes
(b) 14 bytes
(c) 18 bytes
(d) 10 bytes
Answer: (c)
Explanation: Short array s[5] will take 10 bytes as size of short is 2 bytes. Since u is a union, memory
allocated to u will be max of float y(4 bytes) and long z(8 bytes). So, total size will be 18 bytes (10 + 8).
26. The number of tokens in the following C statement.
(GATE 2000)
printf("i = %d, &i = %x", i, &i);
is
(a) 3
(b) 26
(c) 10
(d) 21
Answer (c)
Explanation:In a C source program, the basic element recognized by the compiler is the token. A token is
source-program text that the compiler does not break down into component elements.
There are 6 types of C tokens : identifiers, keywords, constants, operators, string literals and other separators.
There are total 10 tokens in the above printf statement.

IT DEPARTMENT

GATE MATERIAL

27. The following C declarations


(GATE CS 2000)
struct node
{
int i;
float j;
};
struct node *s[10] ;
define s to be
(a) An array, each element of which is a pointer to a structure of type node
(b) A structure of 2 fields, each field being a pointer to an array of 10 elements
(c) A structure of 3 fields: an integer, a float, and an array of 10 elements
(d) An array, each element of which is a structure of type node.
Answer: (a)
28. Assume the following C variable declaration
(GATE CS 2003)
int *A [10], B[10][10];
Of the following expressions
I A[2]
II A[2][3]
III B[1]
IV B[2][3]
which will not give compile-time errors if used as left hand sides of assignment statements in a C
program?
a) I, II, and IV only
b) II, III, and IV only
c) II and IV only
d) IV only
Answer (a)
See below program
int main()
{
int *A[10], B[10][10];
int C[] = {12, 11, 13, 14};
/* No problem with below statement as A[2] is a pointer
and we are assigning a value to pointer */
A[2] = C;
/* No problem with below statement also as array style indexing
can be done with pointers*/
A[2][3] = 15;
/* Simple assignment to an element of a 2D array*/
B[2][3] = 15;
printf("%d %d", A[2][0], A[2][3]);
getchar();
}
IT DEPARTMENT

GATE MATERIAL

29. Consider the following declaration of a two-dimensional array in C: (GATE CS 2002)


char a[100][100];
Assuming that the main memory is byte-addressable and that the array is stored starting from memory
address 0, the address of a[40][50] is
a) 4040
b) 4050
c) 5040
d) 5050
Answer(b)
Address of a[40][50] =
Base address + 40*100*element_size + 50*element_size
0 + 4000*1 + 50*1
4050
30. The C language is. (GATE CS 2002)
a) A context free language
b) A context sensitive language
c) A regular language
d) Parsable fully only by a Turing machine
Answer (a)
Most programming languages including C, C++, Java and Pascal can be approximated by context-free
grammar and compilers for them have been developed based on properties of context-free languages.
References:
http://acm.pku.edu.cn/JudgeOnline/problem?id=3220
http://www.cs.odu.edu/~toida/nerzic/390teched/cfl/cfg.html
31. The most appropriate matching for the following pairs (GATE CS 2000)
X: m=malloc(5); m= NULL;
1: using dangling pointers
Y: free(n); n->value=5;
2: using uninitialized pointers
Z: char *p; *p = a;
3. lost memory is:
(a) X1 Y3 Z-2
(b) X2 Y1 Z-3
(C) X3 Y2 Z-1
(d) X3 Y1 Z-2
Answer (d)
X -> A pointer is assigned to NULL without freeing memory so a clear example of memory leak
Y -> Trying to retrieve value after freeing it so dangling pointer.
Z -> Using uninitialized pointers
32. Consider the following C-program:
(GATE CS 2005)
void foo(int n, int sum)
{
int k = 0, j = 0;
if (n == 0) return;
k = n % 10;
j = n / 10;
sum = sum + k;
foo (j, sum);
printf ("%d,", k);
}
IT DEPARTMENT

GATE MATERIAL

int main ()
{
int a = 2048, sum = 0;
foo (a, sum);
printf ("%d\n", sum);
getchar();
}
What does the above program print?
(a) 8, 4, 0, 2, 14
(b) 8, 4, 0, 2, 0
(C) 2, 0, 4, 8, 14
(d) 2, 0, 4, 8, 0
Answer (d)
sum has no use in foo(), it is there just to confuse. Function foo() just prints all digits of a number. In main,
there is one more printf statement after foo(), so one more 0 is printed after all digits of n.
33. Consider the following C function definition:
GATE-1999
int Trial (int a, int b, int c)
{
if ((a > = b) && (c < b)) return b;
else if (a > = b) return Trial (a,c,b);
else return Trial (b,a,c);
}
The function Trial:
(a) Finds the maximum of a, b, and c
(b) Finds the minimum of a, b and c
(c) Finds the middle number of a, b, c
(d) None of the above
Ans: (c)
Explanation:
The first condition, (a > = b) && (c < b), if true will return the middle number, i.e. b. Again on calling
the Trial function, it will return the middle number.
34. The value of j at the end of the execution of the following C program.
int incr (int i)
{
static int count = 0;
count = count + i;
return (count);
}
main ()
{
int i,j;
for (i = 0; i <=4; i++)
j = incr(i);
}
(a) 10 (b) 4 (c) 6 (d) 7

IT DEPARTMENT

GATE CS 2000

GATE MATERIAL

Ans: option (a)


Explanation:
count variable is declared as static in incr function. Therefore, static int count = 0;, will assign zero to
the count variable in the first call only. When the incr function is called for 2nd, 3rd or 4th times, count
variable will hold its previous value, and will not be re-initialized to zero again.
Static variables hold their previous values, and they do not re-initialized when the function is called
again. The lifetime of a static variable is in the entire program.
For 1st iteration when i=0, incr(0) => count= 0 + 0 = 0
For 2nd iteration when i=1, incr(1) => count= 0 + 1 = 1
For 3rd iteration when i=2, incr(2) => count= 1 + 2 = 3
For 4th iteration when i=3, incr(3) => count= 3 + 3 = 6
For 5th iteration when i=4, incr(4) => count= 6 + 4 = 10
35. Consider the following declaration of a two-dimensional array in C:
GATE CS 2002
char a[100][100];
Assuming that the main memory is byte-addressable and that the array is stored starting from memory address
0, the address of a[40][50] is
(a) 4040
(b) 4050
(c) 5040
(d) 5050
Ans: option (b)
Explanation:
Address of a[40][50] = Starting Address + 40 x 100 x memorySize + 50 x memorySize
= 0 + 40 x 100 x 1 + 50 x 1 = 4050
Note: Since byte addressable, memorySize = 1
36. Consider the following C-program:
GATE-2005
double foo (double); /* Line 1 */
int main () {
double da, db;
// input da
db = foo (da);
}
double foo (double a) {
return a;
}
The above code compiled without any error or warning. If Line 1 is deleted, the above code will show:
(a) no compile warning or error
(b) some compiler-warnings not leading to unintended results
(c) some compiler-warnings due to type-mismatch eventually leading to unintended results
(d) compiler errors
Ans: option (d)
Error:
Function 'foo' should have a prototype in function main()
37. Consider line number 3 of the following C-program.
int main ( ) { /* Line 1 */
int i, n; /* Line 2 */
IT DEPARTMENT

GATE-2005

GATE MATERIAL

fro (i =0, i<n, i++); /* Line 3 */


}
Identify the compilers response about this line while creating the object-module:
(a) No compilation error (b) Only a lexical error
(c) Only syntactic errors (d) Both lexical and syntactic errors
Ans: option(c)
Error: Function 'fro' should have a prototype in function main()
38. Consider these two functions and two statements S1 and S2 about them.
int work1(int *a, int i, int j)
{
int x = a[i+2];
a[j] = x+1;
return a[i+2] 3;
}

GATE-2006

int work2(int *a, int i, int j)


{
int t1 = i+2;
int t2 = a[t1];
a[j] = t2+1;
return t2 3;
}

S1: The transformation from work1 to work2 is valid, i.e., for any program state and input arguments, work2
will compute the same output and have the same effect on program state as work1
S2: All the transformations applied to work1 to get work2 will always improve the performance (i.e reduce
CPU time) of work2 compared to work1
(a) S1 is false and S2 is false
(b) S1 is false and S2 is true
(c) S1 is true and S2 is false
(d) S1 is true and S2 is true
Ans: option (d)
Explanation:
Both functions work1 & work2 performs the same task, therefore S1 is true.
In S2 it is asking about improvement in performance i.e. reduction in CPU time. When compared work2 will
reduce the CPU time, because in work1 a[i+2] is computed twice but in work2 a[i+2] is computed once and
stored in t2, and then t2 is used. When we consider the performance in terms of reduction in CPU time, S2 is
correct.
39. Consider the following C function:
GATE - 2007
int f(int n)
{
static int r = 0;
if (n <= 0) return 1;
if (n > 3)
{
r = n;
return f(n-2)+2;
}
return f(n-1)+r;
}
What is the value of f(5) ?
(a)5 (b)7 (c)9 (d)18
IT DEPARTMENT

GATE MATERIAL

Ans: option (d)


Explanation:
As explained before, Static variables retain their values throughout the life of the program. The steps
involved in the execution is shown below.

Since f(3) returns value 16, the final step is 16+2 = 18. Therefore f(5) will return value 18.
40. Consider the following C declaration
GATE CS 2000
struct {
short s [5]
union {
float y;
long z;
}u;
} t;
Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively.
The memory requirement for variable t, ignoring alignment considerations, is
(a) 22 bytes (b) 14 bytes (c) 18 bytes (d) 10 bytes
Ans: option (c)
Explanation:
The amount of memory required to store a structure variable is the sum of the sizes of all its members.
But in the case of union, the amount of memory required is the amount required by its largest member.
Therefore u, which is a union member of the struct, occupies only 8 bytes of memory, because the
largest memory is 8 bytes consumed by long z;. Another member in the struct is short s [5], this will
occupy 10 bytes of memory ( 2 bytes x 5).
Hence total 10 + 8 =18 bytes.
GATE-2005
41. What does the following C-statement declare?
int ( * f) (int * ) ;
(a) A function that takes an integer pointer as argument and returns an integer
(b) A function that takes an integer as argument and returns an integer pointer
(c) A pointer to a function that takes an integer pointer as argument and returns an integer.
IT DEPARTMENT

GATE MATERIAL

(d) A function that takes an integer pointer as argument and returns a function pointer
Ans: option (c)
Explanation:
Syntax to declare pointer to a function => datatype (*pointer_variable)(list of arguments)
To make a pointer to a function => pointer_variable = function_name
Note: don't use parenthesis of the function.
To call (invoke) the function => pointer_variable(list of arguments)
Print statement in main() will take the value of global variable b and the value of local variable a, while
printing.

42. Which one of the following is the tightest upper bound that represents the time complexity of
inserting an object into a binary search tree of n nodes?
(A) O(1)

(B) O(log n)

(C) O(n)

(D) O(n log n)

(GATE 2013)

Answer: (C)
Explanation: For skewed binary search tree on n nodes, the tightest upper bound to insert a node is O(n).
43. Which one of the following is the tightest upper bound that represents the number of swaps required
to sort n numbers using selection sort?
(A)O(log n)

(B) O(n)

(C) O(n log n)

(D) O(n2)

(GATE 2013)

Answer: (B)
Explanation: The maximum number of swaps that takes place in selection sort on n numbers is n
44. Consider the following operation along with Enqueue and Dequeue operations on queues, where k is
global parameters
MultiDequeue(Q) {
m=k
while (Q is not empty) and (m >0) {
Dequeue(Q)
m=m-1
} }
What is the worst case time complexity of a sequence of n queue operations on an initially empty queue?
(A) (n)

(B) (n+k)

(C) (nk)

(D) (n2)

(GATE 2013)

Answer: (C)
IT DEPARTMENT

GATE MATERIAL

45. The preorder traversal sequence of a binary search tree is 30, 20, 10, 15, 25, 23, 39, 35, 42. Which one
of the following is the postorder traversal sequence of the same tree?
(A) 10,20,15,23,25,35,42,39,30

(B) 15,10,25,23,20,42,35,39,30

(C) 15,20,10,23,25,42,35,39,30

(D) 15,10,23,25,20,35,42,39,30

Answer: (D)

Explanation:
Preorder : 30,20,10,15,25,23,39,35,42
Inorder :10,15,20,23,25,30,35,39,42

46. What is the return value of f p,pif the value of p is initialized to 5 before the call? Note that the first parameter
is passed by reference, whereas the second parameter is passed by value.

int f(int&x,int c)
{
c=c-1;
if (c==0) return 1;
x=x+1;
return f(x,c)*x;
}
(A) 3024
Answer: (B)

IT DEPARTMENT

(B) 6561

(C) 55440

(D) 161051

(GATE 2013)

GATE MATERIAL

Explanation:

Common Data Questions 6 & 7:


The procedure given below is required to find and replace certain characters inside an input character string
supplied in array A. The characters to be replaced are supplied in array oldc, while their respective
replacement characters are supplied in array newc. Array A has a fixed length of five characters, while arrays
oldc and newc contain three characters each. However, the procedure is flawed

voidfind_and_replace( char *A, char *oldc, char *newc)


{
for (inti=0;i<5;i++)
for (int j=0;j<3;j++)
if (A[i]==oldc[j])
A[i]=newc[j];
}

The procedure is tested with the following four test cases


(1) oldc= "abc ", newc= "dab" (2) oldc= " cde", newc= "bcd"
(3) oldc= "bca", newc= "cda" (4) oldc= "abc ", newc= "bac "
IT DEPARTMENT

GATE MATERIAL

47. The tester now tests the program on all input strings of length five consisting of characters a, b, c,
d and e with duplicates allowed. If the tester carries out this testing with the four test cases given
above, how many test cases will be able to capture the flaw?
(A) Only one (B) Only two (C) Only three (D) All four

(GATE 2013)

Answer: (B)
Explanation: Flaw in this given procedure is that one character of Array A can be replaced by more than one
character of newc array, which should not be so.Test case (3) and (4) identifies this flaw as they are
containing oldc and newc array characters arranged in specific manner. Following string can reflect flaw, if
tested by test case (3).

Likewise single character b in A is replaced by c and then by d. Same way test case (4) can also catch the
flaw.
48. If array A is made to hold the string abcde, which of the above four test cases will be successful in
exposing the flaw in this procedure?
(A) None

(B) 2 only

(C) 3 and 4 only

(D) 4 only

(GATE 2013)

Answer: (C)
Explanation: Now for string abcde in array A, both test case (3) and (4) will be successful in finding the flaw,
as explained in above question.
8. What will be output of the following program?
char inChar=A;
switch(inChar)
{
case A: print(Choice A\n);
IT DEPARTMENT

GATE MATERIAL

case B:
case C: printf(Choice B);
case D:
case E:
default: printf(No Choice);
}

(A) No Choice
(B) Choice A
(C) Choice A
Choice B No Choice
(D) Program gives no output as it is erroneous

(GATE 2012)

Answer: (C)
Explanation:-Since there is no break statement, the program executes all the subsequent case
statements after printing choice A.

49. Supposeacircularqueueofcapacity(n1)elementsisimplementedwithan
arrayofnelements.AssumethattheinsertionanddeletionoperationsarecarriedoutusingREARandFRONTa
sarrayindexvariables,respectively.Initially,REAR=FRONT=0.Theconditionstodetectqueuefullandqueue
emptyare
(A)full:(REAR+1)modn==FRONT
empty:REAR==FRONT

(B)full:(REAR+1)mod n==FRONT
empty:(FRONT+1)modn==REAR

(C)full:REAR==FRONT(D)full:(FRONT+1)mod n==REAR
empty:(REAR+1)modn==FRONTempty:REAR==FRONT
(GATE 2012)

Answer:(A)
Explanation:Thecounterexamplefortheconditionfull:REAR=FRONTis
InitiallywhentheQueueisemptyREAR=FRONT=0bywhichtheabovefullconditionissatisfiedwhi
chisfalse
Thecounterexamplefortheconditionfull:(FRONT+1)modn=REARis
InitiallywhentheQueueisemptyREAR=FRONT=0andletn=3,soafterinsertingoneelementREAR
=1andFRONT=0,atthispointtheconditionfullaboveissatisfied,butstillthereisplacefor
onemoreelementinQueue,sothisconditionisalsofalse
Thecounterexamplefortheconditionempty:(REAR+1)modn=FRONTis
InitiallywhentheQueueisemptyREAR=FRONT=0andletn=2,soafterinsertingoneelementREAR
=1andFRONT=0,atthispointtheconditionemptyaboveissatisfied,butthequeueofcapacityn1isfullhere
Thecounterexamplefortheconditionempty:(FRONT+1)modn=REARis
InitiallywhentheQueueisemptyREAR=FRONT=0andletn=2,soafterinsertingoneelementREAR
=1andFRONT=0,atthispointtheconditionemptyaboveissatisfied,butthequeueofcapacityn1isfullhere
IT DEPARTMENT

GATE MATERIAL

COMMON DATA QUESTIONS 50 & 51


Consider the following C program

(2012)

int a, b, c = 0;
voidprtFun (void);
int main ()
{
staticint a = 1; /* line 1 */
prtFun();
a += 1;
prtFun();
printf ( "\n %d %d " , a, b) ;
}
voidprtFun (void)
{
staticint a = 2; /* line 2 */
int b = 1;
a += ++b;
printf (" \n %d %d " , a, b);
}
50. What output will be generated by the given code segment?
(A) 3 1
(B) 4 2
(c) 4 2
(D) 3 1
41
61
62
52
42
61
20
52
Answer (C)

Explanation:
a and b are global variable. prtFun() also has a and b as local variables. The local variables hide the
globals (See Scope rules in C). When prtFun() is called first time, the local b becomes 2 and local a becomes
4.
When prtFun() is called second time, same instance of local static a is used and a new instance of b is
created because a is static and b is non-static. So b becomes 2 again and a becomes 6.
main() also has its own local static variable named a that hides the global a in main. The printf()
statement in main() accesses the local a and prints its value. The same printf() statement accesses the global
b as there is no local variable named b in main. Also, the defaut value of static and global int variables is 0.
That is why the printf statement in main() prints 0 as value of b.
51. What output will be generated by the given code d\segment if:
Line 1 is replaced by auto int a = 1;
Line 2 is replaced by register int a = 2;
(A) 3 1
(B) 4 2
(C) 4 2 (D) 4 2
41
61
62
42
42
61
20
20

(GATE 2012)

Answer (D)
Explanation:
IT DEPARTMENT

GATE MATERIAL

If we replace line 1 by auto int a = 1; and line 2 by register int a = 2;, then a becomes non-static in
prtFun(). The output of first prtFun() remains same. But, the output of second prtFun() call is changed as a
new instance of a is created in second call. So 4 2 is printed again. Finally, the printf() in main will print 2
0. Making a a register variable wont change anything in output.

IT DEPARTMENT

GATE MATERIAL

You might also like