Skip to main content

GATE Questions - C Programming

Previous GATE questions with solutions on C Programming - CS/IT


1. The number of tokens in the following C statement.
       printf("i = %d, &i = %x", i, &i); is
(a) 3 (b) 26 (c) 10 (d) 21

Ans: option (c)

The smallest individual units are known as C Tokens
The keywords, identifiers, constants, string literals, and operators described in this section are examples of tokens. Punctuation characters such as brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) are also tokens.

printf("Hello, World! \n");
The tokens for the above statement are:
1) printf
2) (
3) "Hello, World! \n"
4) )
5) ;
So there are 5 tokens

printf("i = %d, &i = %x", i, &i);
10 Tokens are:
1) printf
2) (
3) "i = %d, &i = %x"
4) ,
5) i
6) ,
7) &
8) i
9) )


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

char inchar = 'A';
switch (inchar)
case 'A' :
    printf ("choice A \n") ;
case 'B' :
    printf ("choice B ") ;
case 'C' :
case 'D' :
case 'E' :
    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

Ans: Option (c)
In switch statement if a case is executed and if the case doesn't contain break, then all the subsequent 'case' statements are executed until a break statement is found. If I modify the above code as below:
char inchar = 'B';
switch (inchar)
case 'A' :
    printf ("choice A \n") ;
case 'B' :
    printf ("choice B ") ;
case 'C' :
case 'D' :
case 'E' :
    printf ("No Choice") ;
The output of the above program will be: Choice B No Choice


3. Consider the following C function definition:
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)
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.

GATE CS 2000

4. 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

Ans: option (a)
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

GATE CS 2002

5. Consider the following declaration of a ‘two-dimensional array in C:
                   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)
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

GATE CS 2005

6. Consider the following C-program:
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);
int main ()
  int a = 2048, sum = 0;
  foo (a, sum);
  printf ("%d\n", sum);
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

Ans: option (d)
going through each code, you will find that foo function prints all the digits of a number stored in variable a
i) k= n % 10  => modulus operator will return the remainder. for example, if n=2048, then 2048 %10 will store the value 8 in k.
ii) j is declared as integer datatype in foo function. Therefore after division if the result contains decimal part, it will be truncated and only the integer part will be stored in j. For example if j=2048/10, (actual result = 204.8) then 204 will be stored in j.
iii) The sum variable declared in the main function will not be used by thefoo function. 

GATE CS 2004

7. Consider the following C function:
int f(int n)
   static int i = 1;
   if (n >= 5)
      return n;
   n = n+i;
   return f(n);
The value returned by f(1) is
a) 5 b) 6 c) 7 d) 8

Ans: option (c)
Note that i is declared as static variable, first line of the function, static int i = 1;, will be executed only once. 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. 

GATE CS 2004

8. Consider the following C program
   int x, y, m, n;
   scanf ("%d %d", &x, &y);
   /* x > 0 and y > 0 */
   m = x; n = y;
   while (m != n)
         m = m - n;
         n = n - m;
   printf("%d", n);
The program computes
a) x + y using repeated subtraction
b) x mod y using repeated subtraction
c) the greatest common divisor of x & y
d)the least common multiple of x & y

Ans: option (c)
Give some values to x and y and work out the code step by step. The program code is an implementation of Euclid's algorithm which is an efficient method for computing the greatest common divisor (GCD) of two integers. 
For more details:


9. Consider the following C-program:
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)

Function 'foo' should have a prototype in function main()


10. Consider line number 3 of the following C-program. 
int main ( ) { /* Line 1 */ 
  int i, n; /* Line 2 */ 
  fro (i =0, i<n, i++); /* Line 3 */ 

Identify the compiler’s 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()


11. 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;

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)
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 work1a[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.

GATE - 2007

12. Consider the following C function:
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

Ans: option (d)
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.


Common data Questions (13 & 14)
Consider the following recursive C function that takes two arguments
unsigned int foo(unsigned int n, unsigned int r) {
  if (n  > 0) return (n%r +  foo (n/r, r ));
  else return 0;

13. What is the return value of the function foo when it is called as foo(345, 10) ?
(a) 345 (b) 12 (c) 5 (d) 3
Ans: option (b)
foo(345,10) = 5 + [ foo(34,10) ]
                 = 5 + [ 4 + { foo(3,10) } ]
                 = 5 + [ 4 + { 3 + foo(0,10) } ] = 5 + 4 + 3 + 0 = 12
Therefore, foo function returns sum of digits in the number n, because r = 10.

14. 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
Ans: option (d)
Executing as above we get the value returned as 2. Here, foo function returns sum of bits of a number n, because r 
= 2.


15. 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.
void reverse(void)
  int c;
  if (?1) reverse() ;
  printf ("Enter Text ") ;  printf ("\n") ;
  reverse();  printf ("\n") ;

(a) ?1 is (getchar() != '\n'’)
     ?2 is getchar(c);
(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);

Ans: option (d)
getchar() is used to get the input character.
putchar() is used to print the character.
The reverse function should read the character you type until you press the "enter" key. Hence before printing, reverse function is called again and again until "enter" key is pressed. Once the "enter" key is pressed; the functions from the function stack run putchar(c) statements one by one. Therefore, last entered character is printed first.

16. The following C declaration
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.

Ans: option (a)


17. The most appropriate matching for the following pairs
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 

(a) X—1 Y—3 Z-2
(b) X—2 Y—1 Z-3
(C) X—3 Y—2 Z-1
(d) X—3 Y—1 Z-2

Ans: option (d)
malloc(size) - malloc function allocates a block of size bytes from the free data area (heap). On success, malloc returns a pointer to the newly allocated block of memory.
Therefore after execution of m=malloc(5);,m contains a pointer to the newly allocated memory. But m=NULL; statement will store the NULL value to m, without freeing the memory. Since the allocated memory is not yet freed, it is a lost memory.

free - deallocates a memory block allocated previously by malloc, calloc, or realloc. Here, "free(n); n->value=5;", n is trying to retrieve a value after the memory has freed, hence dangling pointer.
A dangling pointer is a pointer to storage that is no longer allocated.

GATE CS 2000

18. Consider the following C declaration
struct { 
    short s [5] 
    union { 
         float y; 
         long z; 
} 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)
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 CS 2003

19. Assume the following C variable declaration
      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

Ans: option (a)
A is an array of pointers, and A[2] can be used as left hand sides of assignment statements. Suppose we have another array of integers i.e. int marks[]={10,20,30,40}. Then we can assign A[2] = marks; Because marks represents the starting address of the array marks[], and on execution, the address is stored in the 3rd element of array A. 
Considering the assignment A[2] = marks;, A[2][3] represents the element 40 (i.e. 4th element in the marks array). Therefore, A[2][3] also can be used as left hand sides of assignment statements. i.e. A[2][3] = 45; will make the contents of marks array as {10,20,30,45}.
B[2][3] =12; represents a simple assignment to an element of a two-dimensional array. So B[2][3] can also be used as left hand sides of assignment statements. 
B[1] cannot be used as left hand sides of assignment statements, because, since it is a two-dimensional array B[1] represents an address and we cannot write it. 

GATE CS 2004

20. Consider the following C function
void swap (int a, int b)
   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

Ans: option (d)
call swap (x, y) - will swap only the formal parameters (i.e. a and b). The value actual parameters (i.e. x and y) will remain the same, because the value are passed by  CALL BY VALUE.
call swap (&x, &y) - will not work because, swap function accepts VALUES as parameters, but we are passing addresses of x and y.
option (c): swap (x,y) cannot be used, it is  correct, but reason is not correct.


21. 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.
(d) A function that takes an integer pointer as argument and returns a function pointer

Ans: option (c)
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)


22. What does the following program print?
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);
  return 0;
(a) 2 2 (b) 2 1 (c) 0 1 (d) 0 2

Ans: option (d)
Initially i=0 and j=0
f(&i, &j); on execution p pointer points to i, and q pointer points to j

p = q; means p now contains the address of j, therefore p also now points to j

*p = 2; 2 value is saved in the location where the p is pointing. Since p points to j, value of j is changed to 2 now.

Now returns to main function and prints i and j.Hence i=0 and j=2 


23. 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

Ans: option (c)
p has the base address of character array c.
p[3] is E and p[1] is A

p[3] - p[1] = ASCII value of E - ASCII value of A
            = 69 - 65 =4

p = base address of C
Therefore, p + p[3] - p[1] = base_address + 4
(base_address + 4) is the base address of the string 2011.

GATE CS 2004

24. Consider the following C program segment:
char p[20];
char *s = "string";
int length = strlen(s);
int i;
for (i = 0; i < length; i++)
     p[i] = s[length — i];
The output of the program is 
(a)gnirts (b)gnirt
(c)string (d)no output is printed

Ans: option (d)
string is stored in the character array s.
We know that s[0]='s',s[1]='t',s[2]='r',...,s[5]='g',s[6]='\0'

During first iteration of the for loop, i=0, then p[0] = s[6-0]
Therefore p[0]='\0'
Hence during the execution of the printf statement since the very first character is the null character, it assumes that it is the end of the string and no output is printed.


Common Data Question for 25 & 26
Consider the following C program
int a, b, c = 0;
void prtFun (void);
int main ()
    static int a = 1; /* line 1 */
    a += 1;
    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);
25. What output will be generated by the given code segment?
(a)  (b) (c) (d)
3 1 4 2 4 2 3 1
4 1 6 1 6 2 5 2
4 2 6 1 2 0 5 2

Ans: option (c)
When a function encounters a variable, it will first check for its local variable. If local variable not found then it will go for global variable.  In the above program we can see that there are 3 global variable a,b, & c. But in prtFun() we have local variable a & b.  Therefore it will not go for the global variable a & b. But in the main function we have only a as the local variable, therefore the print statement in main() will take the value of global variable b and the value of local variable a, while printing. 

26. What output will be generated by the given code segment if:
Line 1 is replaced by “auto int a = 1;
Line 2 is replaced by “register int a = 2;
(a) (b) (c) (d)
3 1 4 2 4 2 4 2
4 1 6 1 6 2 4 2
4 2 6 1 2 0 2 0

Ans: option (d)
static variable are now made as non-static, therefore each time when the function is called the variables are again initialized. 
Note that the register variables are same as auto variables, the only difference is that the register variables are allocated iin the registers, instead of main memory, for faster access.

27. What is printed by the following C program?
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;
   c = 4; 
   b = &c;
   a = &b;  
   printf( "%d", f(c,b,a));
(a) 18 (b) 19 (c) 21 (d) 22

Ans: option(b)
Hint: pointer b and py is pointing to c
Initially c = 4
ppz contains the address of b, therefore **ppz refers to the value to which b is pointing. Since b is pointing towards c, the value of c increments when **ppz += 1; statement executes. Therefore c now becomes 5.
z=**ppz; means z = 5
py pointer is pointing towards c, therefore on execution of *py += 2;value of c becomes 7.
y=*py; means y = 7
x contains value 4, therefore on execution of  x+=3;  x becomes 7.


Popular posts from this blog

C Questions

C Questions
C Questions

Note : All the programs are tested under Turbo C/C++ compilers.
It is assumed that,
Programs run under DOS environment, The underlying machine is an x86 system, Program is compiled using Turbo C/C++ compiler.
The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed).
Predict the output or error(s) for the following:

void main()
int const * p=5; printf("%d",++(*p));
Compiler error: Cannot modify a constant value.
p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".
char s[ ]="man"; int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
Answer: mmmm
aaaa nnnn

Zoho Interview | Set 1 (Advanced Programming Round)

Third Round: (Advanced Programming Round) Here they asked us to create a “Railway reservation system” and gave us 4 modules. The modules were:
    1. Booking
    2. Availability checking
    3. Cancellation
    4. Prepare chart
We were asked to create the modules for representing each data first and to continue with the implementation phase.

 My Solution :

#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<string.h>#include<iostream.h>#include<time.h>#include<iomanip.h>#include<fstream.h>char f[10]="f";char s[10]="s";int addr,ad,flag,f1,d,m,i,amt;float tamt; class login {public:char id[100];char pass[100];char*password;void getid(){ cout<<"Enter your id:";gets(id); password=getpass("Enter the password:");strcpy(pass,password);}void displayid(){ cout<<"Id:";puts(id); cout<<"Password:";puts(pass);}}; class detail {public:in…

Hackerrank > SQL > Basic Select

01-Select All
Given a City table, whose fields are described as +-------------+----------+ | Field       | Type     | +-------------+----------+ | ID          | int(11)  | | Name        | char(35) | | CountryCode | char(3)  | | District    | char(20) | | Population  | int(11)  | +-------------+----------+
write a query that will fetch all columns for every row in the table.

My Solution
02-Select by ID
Given a City table, whose fields are described as