Thursday 28 February 2013

C/C++ Puzzles: PART - 24

Changing the Output Without Changing the C Program

Consider the Simple program given below.

#include<stdio.h>

int main( )
{
   printf("\n1\n");
   printf("\n2\n);
   printf("\n3\n);
}

The Output of the Program is Shown Below



The task is to get the output shown below without making any change in the "C Program".


Solution:-

  The idea is to assemble the C Program into assembly file and make changes there. To learn step by step compilation of C Programs in Linux please visit my previous post. I have shown the process in the below. 
  • Let the C Program be named as a.c.
The gcc -S a.c will give you the assembly file a.s. The assembly file is shown below.


  • Edit the file a.s. The changed program is shown below.
  • Now compile the a.s file by typing the command gcc a.s. The output file a.out is generated.
  • Run the program by typing ./a.out. The Output is shown below.

This Post also gives you an idea about optimizing C Programs by making changes in the Assembly language file.

Step By Step Compilation of C Programs in Linux


  In Linux a C program is compiled using GCC (GNU Compiler Collection) Compiler System. If the name of the program is a.c, the program is compiled using the following command.

gcc a.c

The above command will generate an executable file named a.out.

gcc a.c -o pgm

The above command will generate an executable file named pgm.

But before generating the executable file the following actions are performed  by the gcc utitility.
  • From the C program file a.c a file a.i is obtained after preprocessing.
  • From the preprocessor output file a.i the assembler generates a.s which contains the assembler code.
  • From the assembly file a.s the object file a.o is obtained after compilation.
  • From the object file a.o the executable file pgm is obtained after linking.

If required gcc allows you to do these steps separately. 


Consider the program named a.c shown below.

#include<stdio.h>

#define MAX 10

int main(int argc, char **argv)
{
    int i;
    i=MAX;
    printf("\ni = %d\n",i);
    return 0;
}

  • The following command will generate the preprocessed file a.i from the c program file a.c.
gcc -E a.c -o a.i

Figure Below Shows the Preprocessed File a.i


  • The following command will generate the assembly file a.s from the preprocessed file a.i.

gcc -S a.i

Figure Below Shows the Assembly File a.s


  • The following command will generate the object file a.o from the assembly file a.s.
gcc -c a.s
  • The following command will finally generate the executable file pgm from the object file a.o.
gcc a.o -o pgm

  • The executable file pgm can be run by using the following command.
./pgm

Figure Below Shows All the Files Generated in the Process
 

Wednesday 27 February 2013

C/C++ Puzzles: PART - 23

C/C++ Program Reading Another Program while Compiling

  Recently I have come across a puzzle. The question was to write a C Program which while compiling reads another C program. Well, frankly I had no clue. But later I got some help to solve it. The idea was to use the preprocessor. The first program only has Preprocessor code. 


#define A pgm1
#ifdef A
#warning IGNORE THE WARNING MESSAGE!!! Please Enter the Second C Program
#endif

#include "/dev/stdin"

Click here to download the C Program.

Save program as pgm1.c in Linux and compile as follows, " gcc pgm1.c ". The program waits for user input from keyboard. Type the second program and enter CTRL + D to stop typing. Now run the program as follows " ./a.out ". I have typed the following program while compiling the first program.

#include<stdio.h>

int main( )
{
   int a,b,sum;
   printf("\nEnter Two Numbers:\n");
   scanf("%d%d",&a,&b);
   sum=a+b;
   printf("\nSum = %d\n\n",sum);
}

Figure Below Shows the Output

C/C++ Puzzles: PART - 22

Obfuscating the Main( )

  Consider the C Program given below. The main( ) function is not immediately visible. But we know that every C Program requires a main( ). If you carefully analyze the program you will understand the working of it.

#include <stdio.h>

#define _(__,___,____,_____,______,_______) _____##__##____##___

#define NO_MAIN _(a,n,i,m,a,l)

NO_MAIN()
{
    printf("\nSurprise!!!\n");
}

Figure Below Shows the Output

Click here to download the C Program.

Explanation:
  The program uses preprocessor directives to hide the main( ). The preprocessor replaces NO_MAIN with the parameterized macro argument named single underscore ( _ ). Remember single underscore is a valid identifier. This macro replaces the letters a,n,i,m,a,l with main using Token Pasting Operator (##). Thus NO_MAIN is replaced with macro argument named single underscore which in turn is replaced with the word main. Also notice that the identifiers inside the macro too are made up of underscore. That made the program even more confusing.

Figure Below Shows the Substitutions Made by the Preprocessor
   

Tuesday 26 February 2013

C/C++ Puzzles: PART - 21

URL in C/C++ Program 

  Recently I come across a program similar to the program given below. At first I was surprised that there are no errors. But after some time I understood the reason. Try to find out the reason why there are no errors in the program. 

#include<stdio.h>

int main()
{
     http://www.computingforbeginners.blogspot.in/
      printf("\nNo Error? Surprise!!!\n");
     return 0;
}  


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

http: acts as a label in C/C++.
//www.computingforbeginners.blogspot.in/ is a comment in C/C++. So there are no Errors.



C/C++ Program implementing Dequeue Using Linked List

  Dequeue is a very useful Data Structure. Dequeue is also called a Double-ended queue for which elements can be added to or removed from either the front or back. In this program dequeue is implemented by using Linked List. The following types of dequeues are implemented in the program.

1. Input Restricted Dequeue.
2. Output Restricted Dequeue.

Figure Below Shows a Sample Output


Monday 25 February 2013

C/C++ Program Implementing Dequeue Using Array


  Dequeue is a very useful Data Structure. Dequeue is also called a Double-ended queue for which elements can be added to or removed from either the front or back. In this program Dequeue is implemented by using Array. The following  types of dequeues are implemented in the program.

1. Input Restricted Dequeue.
2. Output Restricted Dequeue.

Figure Below Shows a Sample Output

Tower of Hanoi: Non Recursive Solutions

  The Recursive solution for the Tower of Hanoi problem has been discussed in another post. Here I am discussing two non recursive algorithms to solve the problem.
  • Iterative Solution

  Alternate moves between the smallest disk and a non-smallest disk is carried out in the iterative solution. When moving the smallest disk, always move it to the next position in the same direction. If there is no peg position in the chosen direction, move the disk to the opposite end, but then continue to move in the correct direction. Doing this will complete the puzzle using the fewest number of moves to do so.

Figure Below Shows the Output for 3 Disks


  • Binary Solution
Disk positions may be determined more directly from the binary representation of the move number. The following rules are used to find the moves.
  1. There is one binary digit for each disk.
  2. The most significant bit represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it's on the final peg.
  3. The bit string is read from left to right, and each bit can be used to determine the location of the corresponding disk.
  4. A bit with the same value as the previous one means that the corresponding disk is stacked on top the previous disk on the same peg.
  5. A bit with a different value to the previous one means that the corresponding disk is one position to the left or right of the previous one. The initial peg is on the left and the final peg is on the right. The right peg counts as one peg "left" of the left peg, and vice versa. Let n be the number of greater disks that are located on the same peg as their first greater disk and add 1 if the largest disk is on the left peg. If n is even, the disk is located one peg to the left, if n is odd, the disk located one peg to the right.
Figure Below Shows the Output for 3 Disks


Sunday 24 February 2013

C/C++ Puzzles: PART - 20

Finding the Sum of Two Positive Integers without using Any Operator
  The Problem asks you to find the sum of two positive integers without using any of the C Operators. The solution given below uses the properties of printf( ) function defined in the header file <stdio.h>.

#include<stdio.h>
int main()
{
     int a,b;
     printf("Enter the Two Numbers:\n");
     scanf("%d%d",&a,&b);
     printf("\nThe Sum is %d\n",printf("%*c%*c",a,'\r',b,'\r'));
     return 0;
}

Here the inner printf( ) function returns the number of characters successfully printed by it. The format "%*c%*c" tells to print the character '\r' (Carriage Return) using 'a' number of spaces and 'b' number of spaces. So the total number of characters successfully printed is a+b. Hence the sum of two numbers is printed as the output.

Figure Below Shows a Sample Output

Monday 18 February 2013

C/C++ Puzzles: PART - 19

  Finding the Sum without using Addition Operator

  C/C++ puzzles often include problems which can be solved by correctly applying the properties of various Mathematical Operators. I have come across the following problem recently. Find the sum of two numbers without using the addition operator (+). The solution is given below. The solution does not depend on the intricacies of C/C++ Language; it merely uses the basic properties of Arithmetical Operators.

#include<stdio.h>

int main()
{
    int a,b,c;
    printf("Enter the Two Numbers:\n");
    scanf("%d%d",&a,&b);
    c=a-(-b);
    printf("\nThe Sum = %d\n",c);
    return 0;
}


C/C++ Program Implementing Circular Queue Using Linked List


  Circular Queue is a very useful Data Structure. In this program Queue is implemented by using Linked List. The following operations are implemented in the Program.
  • Insert Elements.
  • Delete Elements.  
    • Display Elements.
    • Search Element.
    • Change Element.

    Figure Below Shows a Sample Output

    Thursday 14 February 2013

    Shell Sort

      Shell Sort is a sorting algorithm which works in sub quadratic time. Shell Sort works by comparing elements that are distant rather than adjacent elements in an array or list. Shell Sort makes multiple passes through a list and sorts the lists using insertion sort. Shell Sort improves the insertion sort by quickly shifting values to their destinations. Shell Sort is also called diminishing increment sort because the distance between comparisons decreases as the algorithm proceeds. In the final phase adjacent elements are compared. The efficiency of Shell Sort largely depends on the increment sequence. It is faster than bubble sort, insertion sort and selection sort. But Shell Sort is slower than heap sort, merge sort and quick sort.

    C/C++ Program Implementing Circular Linked List

      Circular Linked List is a very useful Data Structure. In this program Queue is implemented by using Linked List. The following operations are implemented in the Program.
    • Create the Circular Linked List.
    • Insert Elements.
    • Delete Elements.  
      • Display Elements.

      Figure Below Shows a Sample Output








      Tuesday 12 February 2013

      C/C++ Program Implementing Circular Queue Using Array


        Circular Queue is a very useful Data Structure. In this program Circular Queue is implemented by using Array. The following operations are implemented in the Program.
      • Insert Elements.
      • Delete Elements.  
        • Display Elements.

        Figure Below Shows a Sample Output


        Sunday 10 February 2013

        C/C++ Program Implementing Queue Using Linked List

          Queue is a very useful Data Structure. In this program Queue is implemented by using Linked List. The following operations are implemented in the Program.
        • Insert Elements.
        • Delete Elements.  
        • Display Elements.
        Figure Below Shows a Sample Output

        Thursday 7 February 2013

        C/C++ Program Implementing Stack Using Linked List


          Stack is a very useful Data Structure. In this program Stack is implemented by using Linked List. The following operations are implemented in the Program.
        • Push Elements.
        • Pop Elements.   
        • Display Elements.
        Figure Below Shows a Sample Output
        Click here to download the C Program implementing Stack using Linked List.

        Wednesday 6 February 2013

        C/C++ Program Implementing Queue Using Array

          Queue is a very useful Data Structure. In this program Stack is implemented by using Array. The following operations are implemented in the Program.
        • Insert Elements.
        • Delete Elements.   
        • Display Elements.
        Figure Below Shows a Sample Output

        Tuesday 5 February 2013

        C/C++ Program Implementing Stack Using Array

            Stack is a very useful Data Structure. In this program Stack is implemented by using Array. The following operations are implemented in the Program.
        • Push Elements.
        • Pop Elements.   
        • Display Elements.
        Figure Below Shows a Sample Output

        Monday 4 February 2013

        C/C++ Program Implementing Doubly Linked List

        Doubly Linked List is a very useful Data Structure. In this Program the following operations are implemented.
        • Add Records.
        • Delete Records.   
        • Display Records.
        • Count the No. of Records in the List.
        • Searching a Record in the List.
        Figure Below Shows a Sample Output

        Click here to download the C Program implementing Doubly Linked List.
        Click here to download the C++ Program implementing Doubly Linked List.

        Sunday 3 February 2013

        C/C++ Program Implementing Linked List

        Linked List is a very useful Data Structure. In this Program the following operations are implemented.
        • Add Records.
        • Delete Records.   
        • Display Records.
        • Count the No. of Records in the List.
        • Searching a Record in the List.
        Figure Below Shows a Sample Output