Saturday, August 7, 2010

Code to find if a given integer number is power of 2

this can be done in 2 ways


1)
if(!(x& (x - 1)) && x)
 {
     printf("GIVEN NUMBER IS POWER OF 2");
}
EXPLANATION:


Let n be the position of the leftmost 1 bit if x. If x is a power of two, its lone 1 bit is in position n. This means x – 1 has a 0 in position n. To see why, recall how binary subtraction works. When subtracting 1 from x, the borrow propagates all the way to position n; bit n becomes 0 and all lower bits become 1. Now, since x has no 1 bits in common with x – 1, x & (x – 1) is 0, and !(x & (x – 1)) is true.

2)
if(((~x+1)&x)==i)
{
     printf("GIVEN NUMBER IS POWER OF 2");
}
EXPLANATION:
The two’s complement of x is computed with ~x + 1, which inverts the bits of x and adds 1 (~x + 1 is equivalent to -x, but negation is technically illegal for an unsigned integer

Let n be the position of the leftmost 1 bit if x. If x is a power of two, its lone 1 bit is in position n. This means ~x has a 0 in position n and 1s everywhere else. When 1 is added to ~x, all positions below n become 0 and the 0 at position n becomes 1. In other words, the carry propagates all the way to position n. So what happens is this: negating x inverts all its bits, but adding 1 inverts them back, from position n on down. So, (x & (~x + 1)) == x is true.

C Code to convert from decimal to any base Like binary, hex, oct

/* Here we use a single function which can be used to convert a decimal number to any base */

#include
void  DecimalToAnybase(int n, int base);
/*n is decimal no & base indicates to which form the decimal no has to get changed*/
#define HEXADECIMAL  16
#define BINARY                2
#define OCTAL                  8
int main()
{
       DecimalToAnybase(10, BINARY);
      
DecimalToAnybase(255, OCTAL);
        getch();
}
  void 
DecimalToAnybase(int n, int base)
       {
           int i, m, digits[1000], flag;
           i=0;
           printf("\n\n[%d] converted to base [%d] : ", n, base);
           while(n)
           {
                m=n%base;
                digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];
                n=n/base;
                i++;
            }
         / /Eliminate any leading zeroes
           for(i--;i>=0;i--)
           {
              if(!flag && digits[i]!='0')flag=1;
              if(flag)printf("%c",digits[i]);
            }
          }

Various ways to swap two variables without using a temporary variable

The normal way of doing a simple swap is as follows.
int a,b,t;
t = a;
a = b;
b = t;
But this can be done in different methods with out using an extra or temporary variable but each  method has its own flaws.

Method1 (The XOR trick)

a ^= b ^= a ^= b;
Although the code above works fine for most of the cases, it tries to modify variable 'a' two times between sequence points, so the behavior
is undefined. What this means is it wont work in all the cases. . Also, think of a scenario
where you have written your code like this
swap(int *a, int *b)
{
*a ^= *b ^= *a ^= *b;
}
Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess what happens? Since Xor'ing an
element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the
variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to
some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each
other.
swap(int *a, int *b)
{
if(*a!=*b)
{
*a ^= *b ^= *a ^= *b;
}
}

Method2(using + and - )


This method is also quite popular
a=a+b;
b=a-b;
a=a-b;
But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might end up giving you wrong
results.
Method3(using macro)
One can also swap two variables using a macro. However, it would be required to pass the type of the variable to the macro. Also, there is
an interesting problem using macros. Suppose you have a swap macro which looks something like this
#define swap(type,a,b) type temp;temp=a;a=b;b=temp;
Now, think what happens if you pass in something like this
swap(int,temp,a) //You have a variable called "temp" (which is quite possible).
This is how it gets replaced by the macro
int temp;
temp=temp;
temp=b;
b=temp;
Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it?
Conclusion:
 Use a temporary variable. Its not only fool proof, but also easier to understand and maintain as trying to do something tricky will have some or the other loopholes which are very difficult to identify at the first glance.

Wednesday, August 4, 2010

FILE COPY CODE (CP cmd in Unix) basic version of CP command

/*    Basic FILE COPY FUNCTION IN UNIX SIMILAR TO CP COMMAND  */


#include
#define MAX_LINE_LEN 1000      /* maximum line length supported. */
void main(int argc, char* argv[])
{
      char* filePathFrm;
      char* filePathTo;
      FILE* fFrm;
      FILE* fTo;
      char buf[MAX_LINE_LEN+1];
      filePathFrm = "";
      filePathTo = "";
      fFrm = fopen(filePathFrm, "r");
      if (!fFrom) 

      {
        // Print log or some exception handling
            perror("source Fileopen failed:");
            exit(1);
      }
      f_to = fopen(file_path_to, "w+");
       if (!f_to)
       {
         // Print log or some exception handling
          perror("destination fileopen failed:")
          exit(1);
       }
         /* Copy source to target, line by line. */
     while (fgets(buf, MAX_LINE_LEN+1, f_from))
     {
         if (fputs(buf, f_to) == EOF)
          {
                    exit(1);
           }
     }
     if (!feof(f_from))
     {
       
         exit(1);
     }
     if (fclose(f_from) == EOF)
     {
        exit(1);
      }
     if (fclose(f_to) == EOF)
     {
        exit(1);
     }
     return(0);
}


NOTE:
  •  fopen() function shall open the file whose pathname is the string pointed to by filename, and associates a stream with it.returnvalue:Pointer to the opened files object.on failure it returns NULL
  •  fclose() function causes the stream pointed to by stream to be flushed and the associated file to be closed . returnvalue:  0on succes. Otherwise, it returns EOF.
  • feof() function tests the end-of-file indicator for the stream pointed to by stream. returnvalue: non-zero if and only if the end-of-file indicator is set for stream
  • perror():The perror() function shall map the error number accessed through the symbol errno to a language-dependent error message.returnvalue:no return value
        

Tuesday, August 3, 2010

C code for Comparision of 2 Given Strings

/*        strcmp() function defination in c       */
int myStrCmp(const char *s1, const char *s2)
{
    while (*s1==*s2)
    {
       if(*s1=='\0')
          return(0);
         s1++;
         s2++;
    }
     return(*s1-*s2);/*an integer greater than, equal to, or less than 0, if the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2, respectively.*/
}
/* const keyword : is used so that the data pointed by s1 and s2 remains unchanged and if any statement tries to modifie it ,then the compiler will post an error so in order to safe guard some information which we expect to be unchaged we declare it with the key word const */

C Code To find the Factorial of a Number(Recursive function Call)

/***********Factorial of a Number ( recursive C program) ************/
int fact(int n)
{
    int fact;
    if(n==1 || n==0)
       return(1);
    else
        fact = n * fact(n-1);
   return(fact);
}
/* Implementing code in recursive manner is avoided in most cases as it reduces coding complexity and increases the overhead as lot of stacks get created as the function gets called again and again recursively */

C CODE FOR strcat() function

/*******MY STRCAT FUNCTION *************/
char *myStrcat(char *s, const char *t)
{
    char *p = s;
    if (s == NULL || t == NULL) 
        return s;
    while (*s)
       s++;
    while (*s++ = *t++);
   return p;
}

Friday, April 23, 2010

print Numbers from 1 to 100 With out using loops

Input   : start number and end number
output : all numbers to be printed between start and end number


Implemented methods:
 using recursion:
#include
Void NumberPrinter(int ,int );
void main()
{
    int iStartNo,iEndNo;
    printf("Enter the Start and End numbers: ");
    scanf("%d,%d",&iStartNo,&iEndNo);
    NumberPrinter(iStartNo,iEndNo);
}


void NumberPrinter(int iStartNo,int  iEndNo)
{
      if(iStartNo
           return ;
     printf("%d ",iStartNo++);
     NumberPrinter(iStartNo,iEndNo);
}

Wednesday, March 10, 2010

Sorting Strings

Implement a function which will sort the strings. Donot use any c library functions related to strings.

I have used Bubblesort for my Implementation:
Avinash
#include "stdio.h"
#include "stdlib.h"
void StringBubbleSort(char **aStringNames);
void DisplayArray(char **aArrayPtr);
void InputArray(char **aArrayPtr);
int iTotalNames;
void MyStrCpy(char *Src ,const char *Dest);
int  MyStrcmp(char *string1 , char *string2);
void main()
{
   char SZTemp[50];
   char **aArrayPtr = NULL;
   printf("ENTER THE TOTAL NO OF NAMES TO BE ENTERED:");
   scanf("%d",&iTotalNames);
   char a = getchar();
   aArrayPtr = (char **)malloc(sizeof(int)*iTotalNames);
   InputArray(aArrayPtr);
   StringBubbleSort(aArrayPtr );
   DisplayArray(aArrayPtr);
  
}
  
  
  
  
   void InputArray(char **aArrayPtr)
   {
       int iCount = 0;
      
       for(iCount=0; iCount
            aArrayPtr[iCount] = (char *)malloc(sizeof(char)* 20);
       printf("\nEnter the Names: \n");
       for(iCount=0; iCount
            fgets(aArrayPtr[iCount], 20, stdin);
   }
  
  

   void DisplayArray(char **aArrayPtr)
   {
       int iCount = 0;
       for (iCount=0; iCount
       {
            fputs(aArrayPtr[iCount], stdout);
       }
       printf("\n");
   }
   void StringBubbleSort(char **aStringNames)
   {
      int iPass,iCompare;
      char temp[20];
      for(iPass = 1; iPass
      {
          for(iCompare = 0; iCompare
          {
              if((MyStrcmp(aStringNames[iCompare],aStringNames[iCompare+1])) == 1)
              {
                 MyStrCpy(temp,aStringNames[iCompare+1]);
                 MyStrCpy(aStringNames[iCompare+1],aStringNames[iCompare]);
                 MyStrCpy(aStringNames[iCompare],temp);
              }
          }
      }
   }


  int  MyStrcmp(char *string1 , char *string2)
   {
        while((*string1 == *string2) && (*string1 != NULL))
        {
            string1++;
            string2++;
        }
        if(*string1 == *string2)
            return 0;
        else if(*string1 > *string2)   
           return 1;
        else
           return -1;
  }
       
           
    void MyStrCpy(char *Dest ,const char *Src)
    {
        while(*Src !=0 )
        {
            *Dest = *Src;
            Dest++;
            Src++;
        }
        *Dest = '\0';
    }
 

Monday, March 8, 2010

find duplicate in array

Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it.

Tuesday, March 2, 2010

DECIMAL TO BINARY

INPUT       : 7
OUTPUT   : 0000000000000111(16bit)
                    0000000000000000000000000000111(32bit)

Poster         :Avinash



Solutioions:


Monday, March 1, 2010

Sorting

WAP to perform ascending order sort without using bubble sort mechanism for sorting!!(i.e; with min overhead!!)



SOLUTIONS:

BY AVINASH

As per my knowledge sorting with less overhead can vary from algorithm and many dependencies on algorith so i am posting Quick sort which is also a sorting algorithm with fastest.

#include"stdio.h"
#include"stdlib.h"
#define MAX 10

void MyQuickSort(int iLow, int iHigh, int aNumbers[]);
int MySortDivision(int iLow, int iHigh, int aNumbers[]);

int main()
{
    int aNumbers[MAX];
    int iCount = 0;
    for(iCount =0; iCount < MAX; iCount++)
        //aNumbers[iCount] = rand()%100;
        scanf("%d",&aNumbers[iCount]);
    printf("NUMBERS BEFORE SORTING:");
    for(iCount =0; iCount < MAX; iCount++)
        printf("%d ",aNumbers[iCount]);
    printf("\n");
    MyQuickSort(0, MAX-1,aNumbers);
    printf("NUMBERS AFTER SORTING:");
    for(iCount =0; iCount < MAX; iCount++)
        printf("%d ",aNumbers[iCount]);
    return 0;
}

void MyQuickSort(int iLow, int iHigh, int aNumbers[])
{
    int iPivotElementIndex = 0;
    if(iLow < iHigh)
    {
        iPivotElementIndex = MySortDivision(iLow, iHigh, aNumbers);
        MyQuickSort(iLow, iPivotElementIndex - 1 ,aNumbers);
        MyQuickSort(iPivotElementIndex + 1, iHigh, aNumbers);
    }
    return;
}


int MySortDivision(int iLow, int iHigh, int aNumbers[])
{
    int iInternalLow = iLow;
    int iInternalHigh = iHigh;
    int iPivot = aNumbers[iLow];
    int iLowValue,iHighValue;
    while(iInternalLow < iInternalHigh)
    {
        iHighValue = aNumbers[iInternalHigh];
        while(iPivot <= iHighValue)//changed
        {
            if(iInternalHigh <= iInternalLow)
                break;
            iInternalHigh--;
            iHighValue = aNumbers[iInternalHigh];
        }
        aNumbers[iInternalLow] = iHighValue;
        iLowValue = aNumbers[iInternalLow];
        while(iPivot > iLowValue)
        {
            if(iInternalLow >= iInternalHigh)
                break;
            iInternalLow++;
            iLowValue = aNumbers[iInternalLow];
        }
        aNumbers[iInternalHigh] = iLowValue;
    }
    aNumbers[iInternalLow] = iPivot;
    return iInternalLow;
}

SIZEOF OPERATOR

CODE FOR USER DEFINED OPERATOR


Solutions :

BY Santosh
#define MYSIZEOP(x) ((char*)(&x+1)-(char*)(&x) )


By Avinash

#define MYSIZEOP(x) ((char*)(&x+1)-(char*)(&x) )
Works only for variables LIMITATION :does not support   For data type alone. like  sizeof(int);


 

PALINDROME

INPUT            : ANY STRING

OUTPUT         : SHOULD CHECK IF IT IS A PALINDROME ARE NOT

         POSTER       :  PUJA
PAlindrome ->string when reverse also provides same kind example :MALAYALAM solutions:

BY SANTOSH

#include "stdafx.h"
#include
#include "stdlib.h"
#include "string"

int CheckPalindrome(char *);

int _tmain(int argc, _TCHAR* argv[])
{
       char *pString = NULL;
      
       bool chkStatus = FALSE;
      
       pString = (char *)malloc(10*sizeof(char));

       if(!pString)
       {
              printf("Memory Allocation Failed\n");
              exit(EXIT_FAILURE);
       }
       printf("Enter the string to be checked:\n");
       scanf("%s",pString);

       chkStatus = CheckPalindrome(pString);

       if(chkStatus)
              printf("The entered string is Palindrome\n");
       else
              printf("The entered string is not Palindrome\n");

       free(pString);

       return 0;
}

int CheckPalindrome(char *pSrc)                        //Function works irrespective of case senstivity
{
       int chkCnt1,chkCnt2,strLen;

       chkCnt1 = chkCnt2 = 0;

       strLen = strlen(pSrc);

       for(chkCnt1 = 0,chkCnt2 = strLen - 1;(chkCnt1!=chkCnt2) && (chkCnt1 < chkCnt2);chkCnt1++,chkCnt2--)
       {
              if((*(pSrc + chkCnt1) != *(pSrc + chkCnt2)) && (*(pSrc + chkCnt1) != *(pSrc +chkCnt2) - 32) && (*(pSrc + chkCnt1) != *(pSrc + chkCnt2) + 32))
                     return FALSE;
       }

       return TRUE;

}

CHARCTEREXTRACTOR

     INPUT          : STRING-> Battle of the Vowels:Hawaii
                         REMOVE-> AEIOU

OUTPUT         : BTTL F TH VWLS:HW

POSTER          : Santosh
Solutions:

BY EZHILMANI
#include
#include
int RemoveChars(char *str, char *Substring)
{
     
      char *startaddr=NULL;// Pointer which has  the starting address 4 reference
      char *indexidentifyptr=NULL;// ptr vch identifies index 4 searching subchar
      startaddr =str;        // initializing with starting address
     
      if(*Substring!=NULL)
      {
            while(*Substring!='\0')    // condition to check for end of substring
            {
                  str=startaddr;
                  while(*str!='\0')     //  condition to check for end of string
                  {
                        if(*str == *Substring) // comparing string and substring
                        {    
                              indexidentifyptr = str; // storing the address for refernce so for next time the string is searched from this point
                              for(;*str!='\0';str++)  // for adjusting the position of cahracter in the string
                                    *str=*(str+1);
                              *(str-1)='\0'// placing null at the end of string
                              str =indexidentifyptr;
                              indexidentifyptr =0;
                        }
                        else
                              str++;   // if not matched just increment the adress
                  }
                  Substring++;           
            }
            printf("%s%s",startaddr,Substring);
      }
      else
      {
            printf("substring not present");
            return -1;
      }
            return 0;
}
int main()
{
      char str[]={"Battle of the Vowels:Hawaii"};
      char Substring[]={"aeiou"};
      if(RemoveChars(str,Substring)== -1)
            printf("enter substring\n");
      return 0;
}


BY AVINASH:

#include"stdio.h"
#include "string"

bool MyStrExtractor(char *,char*);

int main()
{
       char *pszInput,*pszExtractChar;
       pszInput       = (char *)malloc(30);
       pszExtractChar = (char *)malloc(10);
       memset(pszExtractChar,0X00,10);
       memset(pszInput,0X00,30);                       
       printf("Enter the String:");
       fgets(pszInput, 30, stdin); //MY NAME IS KHAN      
       printf("\nEnter the Extractor variables:");
       fgets(pszExtractChar, 10,stdin);//AEIK
       if(true != MyStrExtractor(pszInput,pszExtractChar))
              printf("\n MYSTREXTRACTOR FAILED");
       else
             printf("\n%s",pszInput);

       free(pszInput);
       free(pszExtractChar);
       return 0;
}

bool MyStrExtractor(char *pszIn,char *pszExtract)
{     
       char *pszTempExtract = pszExtract;
       char *pszTempIn = pszIn;
       while(NULL != *pszIn )//practicing  this way to avoid mistake of EQUAL '=' instead of '=='(as null is a constant it cannot be assigned and generates a error)
       {
             while(NULL != *(pszTempExtract+1))
             {
                    if(*pszTempExtract == *pszIn)
                    {
                           pszTempIn = pszIn;
                           while(NULL != *(pszTempIn+1))//Afterextracting the char shifting entire chars to overwrite the other chars
                           {
                                 *pszTempIn = *(pszTempIn+1);
                                 pszTempIn++;
                           }
                           *(pszTempIn+1)='\0';
                           pszIn--;
                           break;
                    }
                   
                    pszTempExtract++;
             }

             pszTempExtract = pszExtract;
             pszIn++;

       }
       return true;
} BY SANTOSH:
#include "stdafx.h"
#include
#include
#include "string"

char * RemoveChar(char *,char *);


int _tmain(int argc, _TCHAR* argv[])
{
       char *pSrc,*pDest,*pRef;
       int inpStrLen1,inpStrLen2;

       pDest = NULL;

       printf("Enter the approx Input String Length\n");                                                             //Enter your approx string lengths so tat u can allocate
       scanf("%d",&inpStrLen1);                                                                                                   //memory excatly required

       pSrc = (char *)malloc(inpStrLen1*sizeof(char));
       memset(pSrc,0X00,inpStrLen1);

       printf("Enter the approx Removal Character Set String Length\n");                              
       scanf("%d",&inpStrLen2);

       pRef = (char *)malloc(inpStrLen2*sizeof(char));
       memset(pRef,0x00,inpStrLen2);

       fflush(stdin);

       printf("Enter the Input String:\n");                                                                                 //Enter the source string and string that has to be compared.
       fgets(pSrc,inpStrLen1,stdin);

       fflush(stdin);

       printf("Enter the Referenc String:\n");
       fgets(pRef,inpStrLen2,stdin);

       pDest = RemoveChar(pSrc,pRef);                                                                                       //Calling the for extraction which return pointer to extracted
                                                                                                                            //string
       printf("The Extracted String is: %s\n",pDest);

       return 0;
}

char * RemoveChar(char *pInput,char *pCharSet)
{
       int inCnt,outCnt,loopCnt1,loopCnt2;

       char *pOutput;

       bool status = FALSE;

       inCnt = outCnt = loopCnt1 = loopCnt2 =0;

       for(loopCnt1 = 0;*(pInput + loopCnt1) != NULL;loopCnt1++)                                              //Loop for counting extracted characters and
       {                                                                                                      //depending on the count, allocate memory
              for(loopCnt2 = 0;*(pCharSet + loopCnt2) != NULL;loopCnt2++)
              {
                     if(*(pInput + loopCnt1) == *(pCharSet + loopCnt2))
                     {
                           status = TRUE;
                           break;
                     }
              }
              if (!status)
              {
                     outCnt++;
              }
              else
                     status = FALSE;
       }

       pOutput = (char *)malloc(outCnt*sizeof(char));
       memset(pOutput,0x00,outCnt);

       for(loopCnt1 = 0;*(pInput + loopCnt1) != NULL;loopCnt1++)                                                     //Loop for transfering the extracted characters to pOutput
       {
              for(loopCnt2 = 0;*(pCharSet + loopCnt2) != NULL;loopCnt2++)
              {
                     if(*(pInput + loopCnt1) == *(pCharSet + loopCnt2))
                     {
                           status = TRUE;
                           break;
                     }
              }
              if (!status)
              {
                     *(pOutput + inCnt) = *(pInput + loopCnt1);
                     inCnt++;
              }
              else
                     status = FALSE;
       }

       *(pOutput +inCnt) = NULL;

       return pOutput;
}

counter