Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Monday, 24 August 2015

A Quine Program in C


quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output. 

The program given below is a quine program in C.

char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}


Figure below shows the output of the program


Thursday, 12 March 2015

C Program to Find the Endianness of a Machine



Endianness is the ordering or sequencing of bytes of a word of digital data in computer memory storage or during transmission. Words may be represented in big-endian orlittle-endian manner. Big-endian systems store the most-significant byte of a word at the smallest memory address and the least significant byte at the largest. Little-endian system, in contrast, stores the least-significant byte at the smallest address.

In this post I have given a C program to find out the Endianness of your system. The program is given below.



int main()
{
    int x = 1;
    if(*(char *)&x == 1)
    {
        printf("little-endian\n");
    }
    else
    {
        printf("big-endian\n");
    }
    return 0;
}

The program finds the Endianness by using the size of integer variables and a character variables. The integer variable holds the value 1. Then this integer variable is cast into a character and if the value of this character  is 1 you have a little-endian machine. If the character    is 0 then you have a big-endian machine. What is the working principle of this program? When you cast an integer to char the lowest addressed byte of the integer is used a char variable. If this lowest addressed byte contains the value 1 then the machine is little-endian, otherwise it is a big-endian machine. Why so? The integer 1 is represented as 00000000 00000000 00000000 00000001 in a 4 byte int. When you cast this int variable as a char the lowest address contains 00000001 in little-endian and 00000000 in big-endian. Hence if the value of the character variable is 1 you have a little-endian system and if the value of the character variable is 0 you have a big-endian system.

Saturday, 9 August 2014

Client Server Program in C to Simulate TCP Multicast Server


  This program simulates a multicast server in C. The following line of code sets the number of clients accepted by the server program. 

#define NC 4

Here the number of clients is set as 4. First run the server process, then run the client processes.

Click here to download the Client program.

Clcik here to download the Server Program.

Sunday, 27 July 2014

Client Server Program in C to Simulate Go-Back-N-ARQ


  This program was also written some 5 years before. This again is a simulation program trying to imitate Go-Back-N ARQ. It is a client server program. Click here to view the Wikipedia article on Go-Back-N_ARQ. Here also the server side acts as the receiver and hence you should run this program first. Afterwards you should also run the client program which acts as the sender side. 

Figure Below Shows the Receiver

Figure Below Shows the Sender


The line given below sets the window size for the sender and the receiver.

#define W 5 
If you want you can change the window size to some other value. Currently the window size is 5.

The following lines in the receiver side decides the probability with which a frame fails to reach the destination.

#define P1 50
#define P2 10

You can increase the probability of a frame being corrupted by increasing the value of P2 and decrease the probability by decreasing the value of P2. Currently there is a 20% probability for frame corruption.

Click here to download the Receiver Side program.

Click here to download the Sender Side program.


Click here to view the article on Selective Repeat ARQ.

Client Server Program in C to Simulate Selective Repeat ARQ


  I wrote these programs 5 years ago. It is a simulation program trying to imitate the working of Selective Repeat ARQ. Click here to view the Wikipedia article on Selective Repeat ARQ. A client server C program is used to simulate the working of Selective Repeat ARQ. The server acts as the receiver. The client acts as the sender. Because of this reason first run the receiver program and afterwards run the sender program. 

Figure Below Shows theReceiver



Figure Below Shows the Sender
  

The line given below sets the window size for the sender and the receiver.

#define W 5 
If you want you can change the window size to some other value. Currently the window size is 5.

The following lines in the receiver side decides the probability with which a frame fails to reach the destination.

#define P1 50
#define P2 10

You can increase the probability of a frame being corrupted by increasing the value of P2 and decrease the probability by decreasing the value of P2. Currently there is a 20% probability for frame corruption.




In C and C++ typedef is a Storage Class Specifier


  Consider the program given below.

#include<stdio.h>
int main()
{
   typedef static int i;
   i a = 0;
   printf("%d", a);
   return 0;
}


The program when compiled as C or C++ will give you the following error "multiple storage classes in declaration specifiers". The error tells us that typedef in C and C++ is treated as a storage class specifier and this leads to the error since it is not allowed to use two storage class specifiers with a variable.

The C Reference Manual says "The typedef specifier does not reserve storage and is called a storage class specifier only for syntactic convenience".

Monday, 30 June 2014

Yet Another Difference Between C and C++: Initializing Constant Variables


  Constant variable initialization is yet another minute difference between C and C++. Consider the program given below.

#include<stdio.h>
int main()
{
  int x = 111;
  static int y = x;
  if(x == y)
     printf("Equal");
  else
     printf("Not Equal");
  return 0;
}


If you save the program as a C++ program, it compiles fine and shows the output as "Equal". But the same program when compiled as C will give you the following error "initializer element is not constant|". What is the reason? This is another minor difference between C and C++. In C a constant variable can only be initialized with a constant value and not by using another variable. But C++ do not have this restriction. You can initialize a constant variable with any other variable.

Click here to download the C++ program.

Yet Another Difference Between C and C++: Case Labels


 There are many major differences between C and C++. Such differences are matters for Text Books and Manuals. Here I am pointing out yet another minor difference between C and C++. This time the difference arises from the way case labels are treated in C and C++. 

 C++ will allow const int variables as case labels, whereas C will give you an error. Consider the program given below.


#include<stdio.h>

int main()
{
    int i=1;
    const int j=1;
    switch(i)
    {
        case j:
            printf("\nHello\n\n");
            break;
        case 2:
            printf("\nHi\n\n");
            break;
        default:
            printf("\nWelcome\n\n");
    }
    return 0;
}

The program will give the error 'case label does not reduce to an integer constant' when compiled as a C program. But when compiled as a C++ program the program executes without any errors and gives 'Hello' as output. 

C/C++ Puzzles: PART - 36


  The following program will give you syntax error.


#include<stdio.h>

int main()
{
    int a=10,b=5,c;
    c=a>b?a:;
    printf("\n%d\n\n",c);
    return 0;
}

Whereas the program given below will work without any syntax errors. Predict the output of the program.


#include<stdio.h>

int main()
{
    int a=10,b=5,c;
    c=a>b?:b;
    printf("\n%d\n\n",c);
    return 0;
}





Thursday, 29 May 2014

C/C++ Puzzles: PART - 35


   C Program Tricked to Believe X equals X+2

  The puzzle has been discussed previously, but only one solution was provided. But now I have added a few more solutions to this puzzle. The challenge is to get a true value for the following conditional statement. 

x==x+2  

You are free to use any feature of the C preprocessor or Compiler. If you can't get a solution then check the programs shown below.

Solution 1

#define x 2|0
#include<stdio.h>

int main()
{
    if(x == x+2)
    {
        printf("\n Hello");
    }
    else
    {
        printf("\n Hi");
    }
}


Solution 2

#include<stdio.h>

int main()
{
    float x=1.0/0;
    if(x==x+2)
    {
        printf("\nHello");
    }
    else
    {
        printf("\nHi");
    }
}

Solution 3

#include<stdio.h>

int main()
{

    float x = 1e100;
    if(x==x+2)
    {
        printf("\nHello");
    }
    else
    {
        printf("\nHi");
    }
}

Solution 4

#include<stdio.h>

struct {}*x=0;

int main()
{
    if(x==x+2)
    {
        printf("\nHello");
    }
    else
    {
        printf("\nHi");
    }
}

Solution 5

#include<stdio.h>

int (*x)[0x20000000];

int main()
{

    if(x==x+2)
    {

        printf("\nHello");
    }
    else
    {
        printf("\nHi");
    }
}

Solution 6

#include<stdio.h>

int main()
{
/////////////////////////////////////
// we initialize tr = 1            //

int tr = 1;
int x = 111;

////////////////////////////////////
// Can You change the value of tr??/
tr = (x == x + 2);

/////////////////////////////////////
// The value of tr is not changed  //
    if(tr==1)
    {
        printf("\nHello");
    }
    else
    {
        printf("\nHi");
    }
}


Power Method to Find the Largest Eigenvalue


   Power method is used to find the numerically largest eigenvalue. The method sometimes converge very slowly. In this post I am providing the C and C++ programs to implement power method.

Figure Below Shows a Sample Output




Wednesday, 30 April 2014

Fitting a Parabola Using Method of Moments : C/C++ Program


   In this post I have shared the C and C++ programs to fit a Parabola using the method of moments.

Figure Below Shows a Sample Output




Monday, 31 March 2014

Straight Line Fitting By Using the Method of Least Squares : C/C++ Program


   In this post I have shared the C and C++ Programs to perform straight line fitting by using the method of least squares. 

Figure Below Shows a Sample Output




Straight Line Fitting Using the Method of Group Averages : C/C++ Program


   In this post I have shared the C and C++ programs to perform straight line fitting by using the method of Group Averages.

Figure Below Shows a Sample Output



Friday, 28 February 2014

Gauss Seidel Method: C/C++ Program


   With this post I have provided the C and C++ programs implementing the Gauss Seidel Method.

Figure Below Shows a Sample Output

Gauss Jacobi Method: C/C++ Program


   With this post I have provided the C and C++ programs implementing the Gauss Jacobi Method.

Figure Below Shows a Sample Output


Click here to download the C Program.
 


Tuesday, 21 January 2014

C Program to Check Increasing, Decreasing and Bouncy Numbers


  Starting from left-to-right if no digit is exceeded by the digit to its left the number is called an increasing number. 125569 is an increasing number. Similarly if no digit is exceeded by the digit to its right the number is called a decreasing number. 77632 is a decreasing number. A positive integer that is neither increasing nor decreasing is called a bouncy number. 244369 is a bouncy number.

The C Program given with this post checks whether the given number is an increasing, decreasing or bouncy number.


Figure Below Shows a Sample Output


Click here to download the C Program.

Creating C Dynamic Libraries in Linux


  Dynamic library is a relocatable object file with metadata. Dynamic libraries are linked at run time. They are built from one or more object files ( .o files). In Linux Dynamic libraries are called shared objects and the extension is .so. The name of a Dynamic library should start with lib. For example libtest.so is a valid Dynamic library name. 

Creating the Dynamic Library File

Let the name of the C Program file be p1.c,

  • Creating object files: Use gcc to create object files as Position independent Code as follows.

          gcc -fPIC -c p1.c 

  • Creating the Shared Object: 
          gcc -shared p1.o -o libtest.so

Storing & Linking the Static Library File

You need to change the LD_LIBRARY_PATH as follows,

 export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/newpath

  • Store the dynamic library in the standard directory /usr/lib

          Compile & link the dynamic library file with target.c as follows,
          gcc target.c -ltest

  • Store the static library in a directory you have created. 
          For example in /usr/student/mylib.
          Compile & link the static library file with target.c as follows,
          gcc target.c -L/usr/student/mylib -ltest


  • You can also change the LD_LIBRARY_PATH as follows so that the compiler will search even the new path, 

          export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/student/mylib

          Now compile & link the dynamic library file with target.c as follows,
          gcc target.c -ltest


Thursday, 9 January 2014

Creating C Static Libraries in Linux


  A static library is a set of functions and variables which can be added to the target application at compile time. In Linux static libraries has an extension .a. Archive files are made up of object files ( Extension is .o ). The name of the static library should start with lib. For example libtest.a is a valid static library name

Creating the Static Library File

The command ar is used to create static libraries.

The procedure is described below.

Let target.c be the source file to which static libraries are to be linked.

Let p1.c and p2.c contain the functions to be added to the static library libtest.a.

gcc p1.c creates p1.o and gcc p2.c creates p2.o. 

The command to create the static library libtest.a is shown below,

ar -rcs libtest.a p1.o p2.o

Storing & Linking the Static Library File

  • Store the static library in a standard directory like /usr/local/lib.
            Compile & link the static library file with target.c as follows,
         
                     gcc target.c -ltest
  • Store the static library in a directory you have created. For example in /usr/student/mylib.
            Compile & link the static library file with target.c as follows,         
                     gcc target.c -L/usr/student/mylib -ltest

      The command nm can be used to find out the object files stored inside a static library file.

 

Tuesday, 24 December 2013

Sharing User Defined C Header Files in Linux


  In C/C++ header files are used to store common code so that they can be reused at a later stage. Header files are having an extension .h in C/C++. In this post I am discussing the different ways to share a user defined C header file in Linux.

1.  The first technique is to store the header file in the current directory along with the C program accessing the header file. In this case the header file name is included by using Double Quotes instead of angle brackets.

For example the name of the header file be myheader.h. This header file can be included in a C program as shown below,

#include "myheader.h"

2. Another technique is to store the header file in a separate directory and add the whole path while including the header file. Here also the include statement uses Double Quotes instead of angle brackets. 

For example the header file myheader.h is stored in the directory /home/myheaders. Then this header file can be included in a C program as shown below,

#include "/home/myheaders/myheader.h"

3. Finally if you are satisfied with the quality of your header file you can add it to the standard header directories in Linux. The two standard header directories in Linux are,
  • /user/local/include - This directory is used to store header files for third-party libraries.
  • /usr/include - This directory is used to store Operating System Header files.  
For example if the header file myheader.h is copied into one of the two standard header directories mentioned above, then the header file can be included in a C program as shown below,

#include <myheader.h>      

Here Angle Brackets are used in the include statement instead of double quotes. Hence the compiler searches for the header file only in the standard header libraries.