Saturday 30 March 2013

PhD Admission Test Question Papers: PART - 3

  In this post I have given a few question papers and model papers of Admission Test conducted by Chennai Mathematical Institute for PhD in Computer Science and Engineering. I have also included question papers and model papers of Admission Test conducted by CMI for PhD in Mathematics, as this might also help the candidates in Computer Science.

Computer Science
Mathematics

Friday 29 March 2013

C/C++ Puzzles: PART - 32

The sizeof character literal in C/C++

  Consider the C Program given below. 

#include<stdio.h>

int main()
{
    printf("\nSize of char is %d\n",sizeof(char));
    printf("\nSize of char 'a' is %d\n",sizeof('a'));
    return 0;
}


Figure Below Shows the Output

Now consider the case where the same code being executed as a C++ Program. The Program and Output is shown below.

include<stdio.h>

using namespace std;

int main()
{
  printf("\nSize of char is %d\n",sizeof(char));
  printf("\nSize of char 'a' is %d\n",sizeof('a'));
  return 0;
}


Figure Below Shows the Output

The same program gives different output when executed as C and C++ Programs. Why? This is because of a minor difference between C and C++. In C a character literal like 'a' is treated as an int, hence the size is 4 Byte. Whereas in C++ character literals are treated as characters and the size is just 1 Byte.

C/C++ Puzzles: PART - 31

Printing the Map of India

  Yes, Yet another obfuscated C Program. But this one is interesting. The program is printing the map of India. I got this program from stackoverflow. But the name of the author was not specified. But he deserves full credit for this brilliant piece of code. The program is shown below.

#include <Stdio.h>
main()
{
    int a,b,c;
    int count = 1;
    printf("\n\n");
    for (b=c=10;a="- FIGURE?, UMKC,XYZHello Folks,\
    TFy!QJu ROo TNn(ROo)SLq SLq ULo+\
    UHs UJq TNn*RPn/QPbEWS_JSWQAIJO^\
    NBELPeHBFHT}TnALVlBLOFAkHFOuFETp\
    HCStHAUFAgcEAelclcn^r^r\\tZvYxXy\
    T|S~Pn SPm SOn TNn ULo0ULo#ULo-W\
    Hq!WFs XDt!" [b+++21]; )
    for(; a-- > 64 ; )
    putchar ( ++c=='Z' ? c = c/ 9:33^b&1);
    printf("\n\n");
    return 0;
}

Click here to download the C Program.


Figure Below Shows the Output


The program is obfuscated to hide the working from casual onlookers. But the version given below might help you understand the working of the program.


#include <stdio.h>

int main (void) 
{
    int a=10, b=0, c=10;
    char* bits ="TFy!QJu ROo TNn(ROo)SLq 
    SLq ULo+UHs UJq TNn*RPn/QPbEWS_JSWQAIJO^NBELPeHBFHT}
    TnALVlBLOFAkHFOuFETpHCStHAUFAgcEAelclcn^r^r\\tZvYxXyT|S~Pn 
    SPm SOn TNn ULo0ULo#ULo-WHq!WFs XDt!";
    a = bits[b];
    printf("\n\n");
    while (a != 0) 
    {
        a = bits[b];
        b++;
        while (a > 64)
        {
            a--;
            if (++c == 'Z') 
            {
                c /= 9;
                putchar(c);
            } 
            else 
            {
                putchar(33 ^ (b & 0x01));
            }
        }
    }
    printf("\n\n");
    return 0;
}


Click here to download the C Program.

The string contains the run length encoding of the map to be printed. The run length encoding tells us how many times to print each character. The statement putchar(c) prints the newline character and the statement putchar(33 ^ (b & 0x01)) prints the character !.

Thursday 28 March 2013

C/C++ Puzzles: PART - 30

The "goes to" Operator in C/C++

What is a "goes to" operator in C/C++? Well most of you might not have heard about it. I have come across this operator (-->) in a C/C++ puzzle recently. The program is shown below.

#include<stdio.h>
int main()
{
   int x=10;
   while(x --> 0)
   {
       printf("%d ", x);
   }
   printf("\n\n\n");
   return 0;
}


The Figure Below Shows the Output

The loop iterates until x reaches the value 0. Well the operator is not a standard operator in C. It is just post decrement ( -- ) followed by the greater than operator ( > ).To understand the working of the so called "goes to" operator consider the loop given below.

while(x--  >  0)
{
    printf("\n%d",x);
}

Also read the post on The Rule of Maximal Munch in C/C++ to understand the compilation process of operators. 

Tuesday 26 March 2013

C/C++ Puzzles: PART - 29

Accessing the Stack Memory from C Program

  Recently I have seen this puzzle in which you have access the stack memory from the C Program to obtain a solution. Consider the code given below.

#include <stdio.h>

void change( )
{
        
}

int main( )
{
        printf("Hello\n");
        change( );
        printf("Hai\n");
        printf("How are you?\n");
        return 0;
}

The expected output of the program is shown below

The problem asks us to change the Output to the following form by adding code in the function change( ) alone. You are not supposed to make any change in the main( ) or any other part of the Program.


One simple yet ingenious solution was to add the following code in change( ).


void change( )
{
        printf("Hai\n");
        exit(0);
}


  But the expected solution for this puzzle is obtained by changing the return address of change( ) stored in Stack Memory. There are no functions in C which allows you to do this by directly accessing the stack memory. But the following code can achieve this by finding the location of stack memory from the address of  the variable x declared inside change( ). The code is shown below and the output obtained for this program is the required one.

#include <stdio.h>

void change( )
{
        char x;
        /* skip local variable by changing the return address in the Stack Memory*/
       *(long*)(&x + sizeof(char) + sizeof(long*)) += 10;

int main( )

{

        printf("Hello\n");
        change( );
        printf("Hai\n");
        printf("How are you?\n");
        return 0;

}


Click here to download the C Program.


WARNING!!!
Some Operating Systems might give you segmentation fault on this C Program.

Friday 22 March 2013

C/C++ Puzzles: PART - 28

Sizeof Structure Variables

  Consider the code given below. What is the Output? 

struct outer_str 

    struct nest_str1 
    { 
         int mem1; 
    }; 
    struct nest_str2 
    { 
         int mem2; 
    }nest_var2; 
}outer_var; 

int main( ) 
{
      printf("\n\nThe size of structure variable outer_var is %d\n\n",sizeof(outer_var)); 
      return 0;
}
Click here to download the C Program.
The expected Output is 8 bytes. But the actual Output is 4 bytes. Why?

Figure Below Shows the Output

  The inner structure nest_str1 does not have any structure variable associated with it. So there is no memory allocated for this structure. Thus the total memory size of the outer structure variable is just 4 bytes. The program given below will show a size of 8 bytes.

struct outer_str 

    struct nest_str1 
    { 
         int mem1; 
    }nest_var1; 
    struct nest_str2 
    { 
         int mem2; 
    }nest_var2; 
}outer_var; 

int main( ) 
{
      printf("\n\nThe size of structure variable outer_var is %d\n\n",sizeof(outer_var)); 
      return 0;
}

Monday 11 March 2013

Java Development Kit (JDK)

  Java Development Kit ( JDK ) contains a collection of programming tools for Java Developers. Here in this post I am discussing about a few useful tools in JDK.
  • appletviewer - appletviewer runs Java applets without the help of a java enabled web browser.
  • javac - javac is the Java Compiler which produces Byte code from the Java Source code.
  • java - java is the Java Interpreter which runs the Byte code produced by the Java Compiler javac.
  • javah - javah produces header files to use with native methods.
  • javap - javap is the Java Disassembler which enables us to convert Byte code files into a program description.
  • javadoc - javadoc creates HTML format documentation from Java Source code files.
  • jdb - jdb is the Java Debugger.

Differences between Java and C++

  In this post I am discussing about the main differences between Java and C++. The subject is not covered thoroughly.
  • Java is a pure object oriented language, while C++ is basically C with object oriented extension.
  • Java does not support operator overloading.
  • Java does not have template classes as in case of C++.
  • Java does not support multiple inheritance of classes. To achieve multiple inheritance Java uses interface.
  • Header files are not there in Java.
  • There are no global variables in Java.
  • Java does not use explicit pointers.
  • In Java destructors are replaced with finalize( ). 

Sunday 10 March 2013

C/C++ Program to Find the Sum of Perfect Numbers

  A perfect number is a positive integer that is equal to the sum of its proper positive divisors that is, the sum of its positive divisors excluding the number itself. For example 28 is a perfect number. The proper positive divisors of 28 are 1, 2, 4, 7 and 14 which adds up to 28. In this post I have added C/C++ Programs to print  the first N perfect numbers. The sum of these perfect numbers is also found by the program. For large values of N the program will not generate any output.

 Figure Below Shows a Sample Output



Saturday 9 March 2013

The near, far and huge Pointers

  I have read about the near, far and huge pointers in many text books. Most of them were not helpful. In this post I just want to give you some basic ideas about them.
  • The near, far and huge pointers are not part of the standard C Programming language. Even if you haven't heard about them, it doesn't make you less of a C programmer. 
  • They are only relevant in case of 16 bit Intel Architectures. So these pointers are mostly a relic of the past without any proper use nowadays. I still remember the time when I used some of the functions in Turbo C Compiler to copy the memory content. I was unsuccessful in my attempt since my system was having a 32 bit architecture. So these pointers are not useful with most of today's machines.
  • Only 16 bit Compilers like Turbo C++, Borland C++, etc. have support for these compilers nowadays.
  • They were mainly used to deal with segmented memory architectures.
far pointer
A far pointer is a 32-bit pointer and contains both a segment address and an offset address.

huge pointer
A huge pointer is also 32-bit pointer and contains both a segment address and an offset address. When a far pointer is incremented or decremented ONLY the offset of the pointer is actually incremented or decremented but in case of huge pointer both segment and offset value will change.

near pointer
A near pointer is a 16-bit pointer. The current content of the Code Segment or Data Segment is used as the segment part and near pointer contains the offset part.   

C/C++ Puzzles: PART - 27


  Recently I have prepared a Multiple Choice Question Paper for a Coding and Debugging contest. I thought it might be a good idea to post those questions here. Most of the questions and their solutions are already discussed in this blog.

  1.     #include<stdio.h>
        int main( )
       {
           int x;
           int *y;
           int **z;
           x=10;
           y=&x;
           z=&y;
           printf(“%d”,*z);
           return 0;
       }
             
A. Syntax Error       B. 10                        C. Address of y                              D. Address of x

 2.         #include<stdio.h>
        int main( )
        {
           enum tag {a, b=3, c};
           printf(“%d%d”,a,c);
           return 0;
        }

A.     Syntax Error                          B. 14                            C. 13                        D. 04

3.      #include<stdio.h>
      int main( )
      {
         int a[ ] = {1,2,3};
         int i=2;
         printf(“%d”,i[a]);
         return 0;
      }

A.     Address of i                        B. 2                            C. 3                           D. Syntax Error

4.  #include<stdio.h>
     int main( )
     {
        int a,b;
        float c;
        a=10;
        b=5;
        c=(a+b)/2;
        printf(“%f”,c);
        return 0;
     }

A.     7.000000                               B. 7.500000              C. 7                          D. Syntax Error

5.      #include<stdio.h>
      int main()
      {
           int a;
           int *b;
           a=10;
           b=&a;
           printf(“%d”,b);
           return 0;
      }

A.     10                    B. Address of a                     C. Syntax Error                    D. Address of b 

 6.   #include<stdio.h>
      int main( )
      {
         float a;
         a = 10.5;
         printf(“%d”,a);
         return 0;
      }
                               
A. 10.500000             B. 10.000000                        C. 0                                                D. 10

 7.  #include<stdio.h>
      int main( )
      {
         int ch=1;
         switch (ch)
         {
            case 1: printf(“1”);
            case 2: printf(“2”);
            case 3: printf(“3”);
         }
      }

A. 123                      B. Syntax Error                        C. 2                                 D. 1

8.   #include<stdio.h>
     int main()
     {
       int x,y,z;
       x=5;
       y=10;
       z=x+++++y;
       printf(“%d”,z);
       return 0;
     }

A. 10                        B. Syntax Error                     C. 15                                    D. 5

 9.   #include<stdio.h>
     #define SQR (x) x * x
     int main( )
     {
        int a;
        a = SQR (3+5);
        printf(“%d”,a);
        return 0;
     }

A. 64                                 B. 25                            C. 23                                D. Syntax Error
    
10.  #include<stdio.h>
       int main()
       {
           int x,y,z;
           x=10;
           y=20;
           z=x+++y;
           printf(“%d”,z);
           return 0;
       }

A. 30                               B. 31                              C. 32                                   D. Syntax Error

11.   #include<stdio.h>
       int main( )
      {
         int x;
         int *ptr;
         x=10;
         ptr=&x;
         (*ptr)++;
         printf(“%d”,x);
         return 0;
      }

A. 10                            B. 11                                   C. 12                              D. Syntax Error

12.   #include<stdio.h>
       int main( )
       {
           const char str [ ] = “hello”;
           str[0] = ‘H’;
           printf(“%s”,str);
           return 0;
       }
 
 A. Syntax Error            B. Hello                           C. hello                               D. ello

13.   #include<stdio.h>
       int a;
       int main( )
       {
          printf(“%d”,a);
          return 0;
       }

A. Compile Time Error            B. Run Time Error                  C. 0                     D. Garbage Value

14.   #include<stdio.h>
      int main( )
     {
         int i=-1;
         if(i< sizeof(int))
         {
              printf(“%d”,-i);
         }
         else
        {
              printf(“%d”,+i);
        }
        return 0;
     }

 A. 1                                B. Syntax Error                      C. -1                        D. 11    

15.   #include<stdio.h>
      int main( )
      {
          int a=10,b;
          b=sizeof(++a);
          printf(“%d%d”,a,b);
          return 0;
      }
     
A. 104                             B. 114                            C. 102                            D. Syntax Error

C/C++ Puzzles: PART - 26

Consider the C code given below.


#include<stdio.h>

int main( )
{
    int x=0;
    const int y=10;
    /* You Should only change the test condition of the while loop */
    while( )
    {
       printf("\nHello\n");
       x--;
    }
}


The task is to print the message "Hello" 10 times by filling the test condition of the while loop. But the following restrictions are applicable while filling the test condition.

1) You should only use the variables a and y.
2) Only operator can be used in the test condition.

Solution:-

If you haven't got the answer please select the Red Colour Field given below using your mouse.

    while(x+y)
    {
       printf("\nHello\n");
       x--;
    }



Differences Between Java and C

  In this post I am listing out some differences between Java and C. Of course it does not cover all the differences between Java and C.

  • Java is an Object Oriented Programming Language, where as C is a Procedural Programming Language.
  • Java does not have the C Keywords sizeof and typedef.
  • There are no structures and unions in Java. Consequently the C Keywords struct and union are absent in Java.
  • Type Modifiers auto, extern, register, signed and unsigned present in C are not there in Java.
  • Explicit pointers are not supported in Java.
  • There is no preprocessor for java. So statements like #define, #include etc are absent in Java.
  • In Java functions with no argument must be declared with empty parenthesis. In C this can be done by using the void keyword.
  • New operators such as >>> and instanceof are added in Java.
  • Java supports labelled breaks and continue statements.
  • New data types like boolean, reference etc. are added in Java. 
  • Many new keywords like private, protected, public etc are added in Java.

MySQL: Finding the Details of Maximum Elements in Every Group from a Table

  The table for our discussion is called emp and contains 4 fields. The fields are ENAME, ID, SAL and DEPT, Where ENAME stores the employee name, ID stores the employee ID, SAL stores the salary and DEPT stores the department. The table with sample data is shown below.


Sample Table

  
  The Task was to find the NAME, DEPARTMENT and SALARY of the employee having highest salary in each Department. I used the Query given below to solve the problem. 

select 
    ENAME, DEPT, Max(SAL)
from
    emp
group by DEPT;        # Wrong Query

But the output was wrong to my dismay. The incorrect output is shown below.

Wrong Output

I used many different Queries and finally got the correct query to solve the problem. The correct query and output is shown below.

 select 
    e.ENAME, e.DEPT, e.SAL
from
    emp e
        join
    (select 
        DEPT, MAX(SAL) MS
    from
        emp
    group by DEPT) m ON e.DEPT = M.DEPT and e.SAL = m.MS        # Correct Query


Correct Output


Friday 8 March 2013

MySQL: Finding the Details of a Maximum Element

  Recently I have come across a table of data containing 4 fields. The fields are ENAME, ID, SAL and DEPT, Where ENAME stores the employee name, ID stores the employee ID, SAL stores the salary and DEPT stores the department. The table with sample data is shown below.

TABLE 1

  I was supposed to find out the name, department, and salary of the employee with maximum salary from the given table. I used the following query.

Select ENAME, DEPT, MAX(SAL) from employee;         # Wrong Query

To my horror, I received the following output when applied on Table 1.

Wrong Output


At first I was confused. But then I have referred Table 2 given below.

TABLE 2


  I understood the mistake after referring Table 2. The reason was very simple. Max( ) returns the maximum salary, but it doesn't retrieve any other data corresponding to the maximum value. In order to get the correct result use the following query. 

Select ENAME, DEPT, MAX(SAL) from employee where SAL in
(
Select MAX(SAL) from employee);        # Correct Query

The following correct output is obtained when the query is applied on Table 2
.
Correct Output

Sunday 3 March 2013

C/C++ Puzzles: PART - 25

Peculiar behavior of Arrays

Consider the program given below. The program prints the array elements in different ways. How is it possible? 

#include<stdio.h>

int main( )
{
    int a[ ]={1,2,3,4,5};
    int i;
    for(i=0;i<5;i++)
   {
       printf("\n%d\t%d\t%d\t%d\n",a[i],i[a],*(a+i),*(i+a));
   }
   return 0;
}

Click here to download the C Program.


Figure Below Shows the Output


Explanation:-


  The content of an array a[i] is calculated as follows. *(Starting Address  + Array Index ), where a is the starting address and i is the array index. Since addition is a commutative operation a+b and b+a are the same, so a[i], i[a], *(a+i) and *(i+a) all returns the ith element of the array a.