Thursday, June 9, 2011

User defined C Program for String Functions!


   // Program for Finding String Length without String Function
  
 #include <string.h>
 #include <conio.h>
 #include <stdio.h>

 void main()
  {
     int i,j,len=0;
     char str[50];
     clrscr();
     printf("\nEnter a String : " );
     gets(str);
     for(i=0;str[i]!='\0';i++)
   {
      len++;
}
printf("\n============ String Length ========== \n");
printf("\n String  '%s' and  the Length is %d ",str,len);
getch();
}

Output :
  
Enter a String : this is a test length
  
============ String Length ==========
  
 String  'this is a test length' and  the Length is 21

  
// Program for Copy a String to another without using String Function
     
 #include <string.h>
 #include <conio.h>
 #include <stdio.h>
      void main()
          {
               int i,j,len=0;
               char src[50],dest[50];
               clrscr();
               printf("\nEnter a the Source String : " );
               gets(src);
               for(i=0;src[i]!='\0';i++)
                   {
                        dest[i]=src[i];
                   }
               dest[i]='\0';
               printf("\n============ String Copy ========== \n");
               printf("\n Source String  '%s' and  Copied to '%s' ",src,dest);
               free(src);
               getch();
      }
  

Output:
     
Enter a the Source String : Creating Function

============ String Copy ==========

 Source String  'Creating Function' and  Copied to 'Creating Function'
  

  
// Program for Compare two String without using String Function
  
 #include <string.h>
 #include <conio.h>
 #include <stdio.h>

      void main()
          {
               int i,flag=0;
               char str[50],str1[50],ch,ch1;
               clrscr();
               printf("\nEnter a the First String : " );
               gets(str);
               printf("\nEnter a the Second String : " );
               gets(str1);
               for(i=0;str[i]!='\0';i++)
                   {
                        ch=str[i];
                        ch1=str1[i];
                        if(ch>=97 && ch<=122)
                             {
                                    ch-=32;
                             }
                        if(ch1>=97 && ch1<=122)
                             {
                                    ch1-=32;
                              }
                        if(ch!=ch1)
                             {
                                    flag=1;
                                    break;
                             }
                   }
               printf("\n============ String Compare ========== \n");
               if(flag==0)
                   {
                        printf("\n Both  String  '%s' and  '%s' are equal ",str,str1);
                   }
               else
                   {
                        printf("\n Both  String  '%s' and  '%s' are Not equal ",str,str1);
                   }
               getch();
      }

Output:
  
Enter a the First String : Testing
Enter a the Second String : testing
  
============ String Copy ==========
  
 Both  String  'Testing' and  'testing' are equal

Enter a the First String : Test
Enter a the Second String : Rest
  
============ String Copy ==========
  
 Both  String  'Test' and  'Rest' are Not equal

Enter a the First String : TEST
Enter a the Second String : test
  
============ String Copy ==========
  
 Both  String  'TEST' and  'test' are equal
  

  
// Program for String Reverse without String Function
  
 #include <string.h>
 #include <conio.h>
 #include <stdio.h>
      
      void main()
          {  
               int i,j,len=0;
               char str[50],revstr[50];
               clrscr();
               printf("\nEnter a String : " );
               gets(str);
               for(i=0;str[i]!='\0';i++)
                   {
                        len++;
                   }

               j=0;
               for(i=len-1;i>=0;i--)
                   {
                        revstr[j++]=str[i];
                   }
          printf("\n Original String  '%s' and  Reversed to '%s' ",str,revstr);
          free(str);      //  Releases memory block occupied by str
          getch();
}

Output:
  
Enter a String : Hello World!
  
============ String Reverse ==========
  
 Original String  'Hello World!' and  Reversed to '!dlroW olleH'

  
// Program for String Concatenation without String Function
  
 #include <string.h>
 #include <conio.h>
 #include <stdio.h>
  
      void main()
          {
               int i,len=0,j;
               char str[50],str1[50],ch,ch1;
               clrscr();
               printf("\nEnter a the First String : " );
               gets(str);
               printf("\nEnter a the Second String : " );
               gets(str1);
               for(i=0;str[i[!='\0';i++)
                   {
                         len++;
                   }
               len=len-1;
               for(i=0;str1[i]!='\0';i++)
                   {
                        str[len++]=str1[i];
                   }
               str[len]='\0';
               printf("\n============ String Concatenation ========== \n");
               printf("\n First  String  '%s' and  Second String '%s'  ",str,str1);
               printf("\n Concatenated in First '%s' ",str);
               getch();
      }
  

   Output:
  
Enter a the First String : Microsoft
  
Enter a the Second String : Office
  
============ String Concatenation ==========
  
 First  String  'Microsoft' and  Second String 'Office'
 Concatenated in First 'MicrosoftOffice'

  
// Program for StringTokenizer  without String Function

 #include <string.h>
 #include <conio.h>
 #include <stdio.h>

      void main()
          {
               int i,len=0,j;
               char str[100],str1[50],ch,ch1;
               clrscr();
               printf("\nEnter a Sentence : " );

               gets(str);
               printf("\n============ String Tokenizer ========== \n");
               printf("\n Origina Input '%s' the Tokens : ",str);
               for(i=0;str[i]!='\0';i++)
                   {
                        len++;
                   }
               str[len]=' ';
               str[len+1]='\0';
               for(i=0;i<len;i++)
                   {
                        for(j=0;j<50;j++)
                             {
                                    str1[j]='\0';
                             }
                        j=0;
                        while(str[i]!=' ')
                             {
                                    str1[j++]=str[i];
                                    i++;
                             }
                          printf("\n%s",str1);
                   }
               getch();
      }
  

Output:
     
Enter a Sentence : I have a dream
  
============ String Tokenizer ==========
  
   Original Input 'I have a dream' the Tokens :
I
have
a
dream

Thursday, June 2, 2011

C Programs Using Buil-in-String Functions


Today will discuss some useful String functions, string.h is the header in the C/C++ standard library for the C/C++ programming language which contains macro definitions, constants, and declarations of functions and types used not only for string handling but also various memory handling functions. Functions declared in string.h are extremely popular, since as a part of the C/C++ standard library, they are guaranteed to work on any platform which supports C. The string functions only work with ASCII or character sets that extend ASCII in a compatible manner.

String function, which only valid to string type data and string handling is not an easy job in 'C'. Even string.h provide the functions you need but often you will be asked to write your own functions and prohibited from using some of the string function. So, how to do this I will come to this when we talk about programming. In C/C++, while using these following string function you must include "string.h" header file.



strlen() - Returns the number of characters in string, not including the terminating null character.

Syntax : int L=strlen(Str);

Example

/* STRLEN.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main( )
 {
      char Str[61] = "This Sentence are for testing!";
      int len;
      clrscr();      len = strlen(Str);
      printf("\n=========STRLEN================\n");
      printf( "'%s' is having %d characters \n", Str, len );
      getch(); }

Output

=========STRLEN================";

'This Sentence are for testing!' is having 30 characters


strcpy() - The strcpy() function copies Source String, including the terminating null character, to the location specified by Destination String. No overflow checking is performed when strings are copied or appended. The behavior of strcpy is undefined if the source and destination strings overlap.

Syntax : strcpy(dest,src)

Example

/* STRCPY.C*/

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main( )
  {
       char src[80]="I am fit and fine",dest[80];
       strcpy( dest,src );
       clrscr();
       printf("\n=========STRCPY================\n");
       printf( "Source '%s ' and Destination is ' %s'",src,dest);
       getch();

  }

Output

=========STRCPY================

Source 'I am fit and fine ' and Destination is ' I am fit and fine'



strncpy () - The strncpy function copies the initial count characters of Source String to Destination String. If count is less than or equal to the length of Source, a null character is not appended automatically to the copied string. If count is greater than the length of Source, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap.

Sysnatx : strncpy(dest,src,N); // 'N' is Numbers of Characters from left

Example

/* STRNCPY.C */

#include <string.h>
#include <stdio.h>
#include<conio.h>

void main( )
 {
     char src[50] = "String Function, Testing!",dest[50];
     clrscr();
     strncpy( dest, src, 15 );
     dest[15]='\0'; // Terminating with a null
     printf("\n=========STRNCPY================\n");
     printf (" Source ' %s ' and copied first 15 characters to destination '%s'",src,dest);
     getch();
}

Output

=========STRNCPY================

Source ' String Function, Testing! ' and copied first 15 characters to
destination 'String Function'



strcmp() - The strcmp function compares string1 and string2 lexicographically and returns a value indicating their relationship.

Syntax : int L= strcmp(str1,str2 );

Return Value Relationship of string1 to string2

< 0 string1 less than string2

= 0 string1 identical to string2

> 0 string1 greater than string2

Example

/* STRCMP.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main( )
 {
     char str1[50];     char str2[50];
     int result;
     clrscr();
     printf("\nEnter two String : ");
     gets(str1);
     gets(str2);
     printf("\n=========STRCMP================\n");
     printf("\nInput String ' %s ' and ' %s '",str1,str2);
     result=strcmpi(str1,str2);
     if(result==0)
          printf(" Strings are Equal ");
     if(result<0)          printf(" String1 is Smaller than String2 ");
     if(result>0)
          printf(" String1 is bigger than String2 ");  
     getch();
 }

Output

Enter two String : Testing

Testing

=========STRCMP================
Enter two String : Testing

Testing

Input String ' Testing ' and ' Testing '  Strings are Equal

=========STRCMP================

Enter two String : Jest
Test

Input String ' Jest ' and ' Test '
String1 is Smaller than String2

=========STRCMP================

Enter two String : Test
Rest

Input String ' Test ' and ' Rest '
String1 is bigger than String2

=========STRCMP================

Enter two String : test

Test
Input String ' test ' and ' Test ' String1 is bigger than String2



Check the last output in strcmp(), String values 'Test' and 'test' are showing not equal, beacuse strcmp() function is case sensitive, for this you can use strcmpi() or stricmp().

strcmpi() - The strcmpi() function lexicographically compares while ignoring cases of string1 and string2 and returns a value indicating their relationship.Retun Values are same as strcmp().

Syntax : int L= strcmpi( str1, str2 );

Example

/* STRCMPI.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main( )
 {
        char str1[50],str2[50];   
        int result;
        clrscr();
        printf("\nEnter two String : ");
        gets(str1);
        gets(str2);        printf("\n=========STRCMPI================\n");
        printf("\nInput String ' %s ' and ' %s '",str1,str2);
        result=strcmpi(str1,str2);
        if(result==0)
       printf (" Strings are Equal ");
       if(result<0)
       printf(" String1 is Smaller than String2 ");
       if(result>0)
       printf(" String1 is bigger than String2 ");
       getch();
 }

Output

Enter two String : Test
test

=========STRCMPI================

Input String ' Test ' and ' test '  Strings are Equal



strncmp() - Each of these routines compares str1 to str2, looking at no more than 'N' characters from beginning. strnicmp() and strnicmp() perform a signed comparison of s1 to s2, without case sensitivity. The string comparison starts with the first character in each string and continues with subsequent characters until the corresponding characters differ or until 'N' characters have been examined. Return Values are same as strcmp().

Syntax : strncmp(str1,str2,N); //N is numbers of characters from left

Example


/* STRNCMP.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main()
 {
   char str1[50];
   char str2[50];
   int result,N=4;
   clrscr();
   printf("\nEnter two String : ");
   gets(str1);
   gets(str2);
   printf("\n=========STRNCMP================\n");
   printf("\nInput String ' %s ' and ' %s '\n",str1,str2);
  result=strncmp(str1,str2,N);
  if(result==0)
      printf(" First %d character of Strings are Equal",N);
 if(result<0)
      printf(" First %d character String1 is Smaller than String2 ",N);
 if(result>0)
      printf(" First %d character String1 is bigger than String2 ",N);
 getch();
}

Output


Enter two String : Compare
Comparing

=========STRNCMP================

Input String ' Compare ' and ' Comparing ' First 4 character String1 is Smaller than String2

Enter two String : compare
Comparing

=========STRNCMP================

Input String ' compare ' and ' Comparing ' First 4 character String1 is bigger than String2

Enter two String : Compare
compare

=========STRNCMP================

Input String ' Compare ' and ' compare ' First 4 character String1 is Smaller than String2



/* STRNCMPI.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main()
 {
    char str1[50];
    char str2[50];
    int result,N=4;
   clrscr();
   printf("\nEnter two String : ");
   gets(str1);
   gets(str2);
   printf("\n=========STRNCMPI================\n");
   printf("\nInput String ' %s ' and ' %s '\n ",str1,str2);
   result=strncmpi(str1,str2,N);
   if(result==0)
       printf(" First %d character of Strings are Equal",N);
   if(result<0)
      printf(" First %d character String1 is Smaller than String2 ",N);
  if(result>0)
     printf(" First %d character of String1 is bigger than String2 ",N);
  getch();
}

Output


Enter two String : Compare
compare

=========STRNCMPI================

Input String ' Compare ' and ' compare ' First 4 character of Strings are Equal



strcat() - The strcat function appends strSource to strDestination and terminates the resulting string with a null character. The initial character of Source String overwrites the terminating null character of Destination String. No overflow checking is performed when strings are copied or appended. The behavior of strcat is undefined if the source and destination strings overlap.

Syntax : strcat(dest,src);

Example

/* STRCAT.C*/

#include <string.h>
#include <stdio.h>
#include <conio.h>

void main()
 {
     char src[50]="I am Fit.",dest[50]="Iam Fine. ";
     clrscr();
     printf("\n\n============STRCAT===============\n\n");
     printf("Source ' %s ' and Destination ' %s ' concatenated to Destination ",src,dest);
     strcat( dest, src );
     printf(" ' %s '\n",dest);
     getch();
}

Output

============STRCAT===============

Source ' I am Fit. ' and Destination ' I am Fine. ' concatenated to Destination '
I am Fine. I am Fit. '



strncat() - The strncat() function appends, at most, the first count characters of Source string to Destination string. The initial character of  Source string overwrites the terminating null character of destination string. If a null character appears in Source string before count characters are appended, strncat() appends all characters from Source string up to the null character. If count is greater than the length of Source string, the length of  Source stringis used in place of count. The resulting string is terminated with a null character. If copying takes place between strings that overlap, the behavior is undefined.

Syntax : strncat(dest,src,N);// 'N' is numbers of character from left of source string

Example

/* STRNCAT.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

 void main()
  {
      char src[50] = "I Love India & live in too",dest[50]="I live in India, ";
       int N =13;
      clrscr();
      printf("\n\n=================STRNCAT==============\n");
      printf("Srouce : ' %s ' and Destination ' %s '\n", src,dest);
      strncat(dest,src,N );
      printf( " After %d character Concatenate to Destination ' %s '\n", N,dest);
      getch();
  }

Output


=================STRNCAT==============

Srouce : ' I Love India & live in too ' and Destination ' I live in India, '

After 13 character Concatenate to Destination ' I live in India, I Love India '



strchr() - strchr scans a string in the forward direction, looking for a specific character. These functions find the first occurrence of the character c in the strings.

Syntax : char *p = strchr(str, char)

Return Value: On success, returns a pointer to the first occurrence of the character c in string s.

On error (if c does not occur in s), returns null.

Example:

/* STRCHR.C */

#include <string.h>
#include <stdio.h>
#include <conio.h>

 void main()
  {
      char str[25]="Searching A Character";
      char *ptr, c = 'r';
      clrscr();
      ptr = strchr(str, c);
      printf("\n\n=================STRCHR==============\n");
      if (ptr)
        printf("The character ' %c ' is at position: %d\n", c, ptr-str);
     else
        printf("The character was not found\n");
    getch();
}

Output

=================STRCHR==============
The character ' r ' is at position: 3



strstr()- Finds the first occurrence of a substring in another string. Scan str1 for the first occurrence of the substring str2.

Syntax : char *p=strstr(str1,str2);

Return Value:
On success, strstr returns a pointer to the element in str1 where str2 begins (points to s2 in s1).

On error (if s2 does not occur in s1), strstr returns null.

Example:

/* STRSTR.c */

#include <stdio.h>
#include <string.h>
#include <conio.h>

void main()
 {
     char str1[] = "Borland International", str2[] = "nation", *ptr;
     ptr = strstr(str1, str2);
     printf("\n\n==================STRSTR================\n");
     printf("Sentence ' %s ' and Search Text ' %s '\n",str1,str2);
     printf("The substring is: %s and the position is %d\n", ptr,ptr-str1);
     getch();
}

Output

==================STRSTR================
Sentence ' Borland International ' and Search Text ' nation '

The substring is: national and the position is 13



strlwr() - Converts the string to uppercase letters (A to Z) in strings to lowercase (a to z).
strupr() - Converts the string to convert lowercase letters (a to z) in string s to uppercase (A to Z).

Syntax : strlwr(Str);
               strupr(str);

Example

/*STRUPR/STRLWR()*/

#include <stdio.h>
#include <string.h>
#include <conio.h>

void main()
 {
      char str[] = "Converting Uppercase to lowercase vice versa";
      clrscr();
      printf("\n\n===============STRLWR===============\n");
      printf("\n String ' %s ' converted to lowercase \n", str);
      strlwr(str);
      printf(" ' %s '\n", str);
      printf("\n\n===============STRUPR===============\n");
      printf("\n String ' %s ' converted to uppercase \n", str);
      strupr(str);
      printf(" ' %s '\n", str);
      getch();
}

Output

===============STRLWR===============

String ' Converting Uppercase to lowercase vice versa ' converted to lowercase '
converting uppercase to lowercase vice versa '

===============STRUPR===============

String ' converting uppercase to lowercase vice versa ' converted to uppercase '
CONVERTING UPPERCASE TO LOWERCASE VICE VERSA '


strrev() - Reverses all characters in str (except for the terminating null)

Syntax : strrev(str);

Example

/*STRREV.c*/

#include <stdio.h>
#include <string.h>
#include <conio.h>

void main()
  {
        char str[] = "Borland C";
        clrscr();
        printf("\n\n===============STRREV===============\n");
        printf("\n Original String ' %s 'After \n", str);
        strrev(str);
        printf(" ' %s '\n", str);
        getch();
  }

Output

===============STRREV===============

Original String ' Borland C ' After ' C dnalroB '




strdup() - Copies a string into a newly created location. strdup() makes a duplicate of string s, obtaining space with a call to malloc().

Syntax : char *p = strdup(str);

Return Value:

On success, returns a pointer to the location containing the duplicated string
On error (if space couldn't be allocated), returns null

Example:

/*STDUP.c*/

#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <alloc.h>

void main()
 {
      char *dup_str, str[] = "abcde";
      clrscr();
      dup_str = strdup(str);
      printf("Original string is ' %s ' duplicated to ' %s '\n", str,dup_str);
      getch();
}

Output

Original string is ' abcde ' duplicated to ' abcde '



strtok() - srtok() consider the string s1 to consist of a sequence of zero or more text tokens, separated by spans of one or more characters from the separator string s2.The first call to strtok returns a pointer to the first character of the first token in s1, and writes a null character into s1 immediately following the returned token. Subsequent calls with null for the first argument will work through the string s1 until no tokens remain. The separator string, s2, can be different from call to call.

Syntax : char *p= strtok( string, delimiter);

Return Value:

On success, returns a pointer to the token found in s1.

When there are no more tokens, returns a null p

Example

/* STRTOK.C: */

#include <string.h>
#include <stdio.h>
#include <conio.h>

 void main( )
  {
        char stok[]="I live in India and India is a beautiful Country";
        char *tok;
        clrscr();
        printf("\n\n===============STRTOK===============\n");
        printf( "%s\n\nTokens:\n", stok );
        tok = strtok( stok, " " ); //Delimiter is space
        while( tok != NULL )
           {
                printf( " %s\n", tok );
                tok = strtok( NULL, " " );
           }
        getch();
  }

Output

I live in India and India is a beautiful Country

Tokens:

I
live
in
India
and
India
is
a
beautiful
Country



!!! Hope it will be helpful to you.!!!

Thursday, May 26, 2011

Built in Character Function



There are a variety of functions provided for testing and mapping characters. The testing functions, which are described first, allow you to test if a character is of a particular type, such as alphabetic, upper or lower case, numeric, a control character, a punctuation mark, printable or not and so on. The character testing functions return an integer, either zero if the character supplied is not of the category specified, or non-zero if it was. The functions all take an integer argument, which should an int of the value of which should be representable as unsigned char.,

You can write your own routine for following function or you can use these. The following is a summary of all the character testing functions. The header <ctype.h> must be included before any of them is used.



Character function - 'ctype.h', header file should be included to use following character function .


_tolower(), tolower() - Translate characters to lowercase. tolower is a function that converts an integer ch (in the range EOF to 255) to its lowercase value (a to z; if it was uppercase, A to Z). All others are left unchanged. _tolower is a macro that does the same conversion as tolower, except that it should be used ONLY when ch is known to be uppercase (A-Z).

Declaration:

int tolower(int ch);
int _tolower(int ch);

Return Value:

      If ch is uppercase, _tolower and tolower return its converted value.

     If ch is not uppercase, tolower returns ch unchanged.

     _tolower's result is undefined.


_toupper() , toupper() - Translate characters to uppercase. þ toupper is a function that converts an integer ch (in the range EOF to 255) to its uppercase value (A to Z; if it was lowercase, a to z). All others are left unchanged. _toupper is a macro that does the same conversion as toupper, except that it should be used only when ch is known to be lowercase (a to z).

Declaration:
       int toupper(int ch);
      int _toupper(int ch);

Return Value:

If ch is lowercase, _toupper and toupper return its converted value.

     If ch is not lowercase, toupper returns ch unchanged.

_toupper's result is undefined.

/* tolower / toupper example */

#include <stdio.h>
#include <ctype.h>
#include <conio.h>

void main()
 {
       int len, i;
       char str[] = "THIS IS A STRING";
       clrscr();
       printf("Original>> ' %s ' \n",str);
       len = strlen(str);
       for (i=0; i<len; i++)
           {
                   str[i] = tolower(str[i]);
           }
       printf(" After tolower() >> ' %s \n",str);
       for (i=0; i<len; i++)
           {
               str[i] = toupper(str[i]);
           }
       printf(" Change back to using toupper() >> ' %s '\n",str);
       getch();
 }

Output

Original>> ' THIS IS A STRING '

After tolower() >> ' this is a string '

Change back to using toupper() >> ' THIS IS A STRING '



 isalnum(), isalpha(), isascii(),iscntrl(), isdigit(), isgraph(), islower(), isprint(), ispunct()(),isspace(), isupper(), isxdigit() - Character classification macros. These macros classify ASCII coded integer values by table lookup. Each macro is a predicate that returns a non-zero value for true and 0 for false. isascii() is defined on all integer values. The other  macros are defined only when isascii(c) is true or c is EOF.

Declarations:
            int isalnum(int c);
            int islower(int c);
            int isalpha(int c);
            int isprint(int c);
            int isascii(int c);
            int ispunct(int c);
            int iscntrl(int c);
            int isspace(int c);
            int isdigit(int c);
            int isupper(int c);
            int isgraph(int c);
            int isxdigit(int c);

Return Value:

These. macros return a non-zero value on success. For each macro, success is defined as follows:

isalpha(): c is a letter (A to Z or a to z)
isascii(): the low order byte of c is in the range 0 to 127 (0x00--0x7F)
iscntrl(): c is a delete character or ordinary control character (0x7F or 0x00 to 0x1F)
isdigit(): c is a digit (0 to 9)
isgraph(): c is a printing character, like isprint, except that a space character is excluded
islower(): c is a lowercase letter (a to z)
isprint(): c is a printing character (0x20 to 0x7E)
ispunct(): c is a punctuation character (iscntrl or isspace)
isspace(): c is a space, tab, carriage return, new line, vertical tab, or formfeed (0x09 to 0x0D, 0x20)
isupper(): c is an uppercase letter (A to Z)
isxdigit(): c is a hexadecimal digit (0 to 9, A to F, a to f)

Some Example

#include <stdio.h>
#include <ctype.h>
#include <conio.h>

void main()
  {
        int len, i;
        char str[] = "8/F, Is My AD.";
        clrscr();
        len = strlen(str);
        printf("\nOriginal  String ' %s '\n",str);
        for (i=0; i<len; i++)
            {
                    if(islower(str[i]))
                    printf("\nCharacter in position %d is' %c ' is a lowercase letter\n",i,str[i]);
                    if(isupper(str[i]))
                        printf("\nCharacter in position %d is ' %c ' is a uppercase letter\n",i,str[i]);
                    if(isdigit(str[i]))
                        printf("\nCharacter in position %d is' %c ' is a digit\n",i,str[i]);
                    if(isspace(str[i]))
                        printf("\nCharacter in position %d is' %c ' is space\n ",i,str[i]);
                    if(ispunct(str[i]))
                        printf("\nCharacter in position %d is' %c ' is punctuation sign\n",i,str[i]);
            } 
        getch();
  }

Output

Original String ' 8/F, Is My AD. '

Character in position 0 is ' 8 ' is a digit

Character in position 1 is ' / 'is punctuation sign

Character in position 2 is ' F ' is an uppercase letter

Character in position 3 is ' , 'is punctuation sign

Character in position 4 is ' ' is space

Character in position 5 is ' I ' is an uppercase letter

Character in position 6 is ' s ' is a lowercase letter

Character in position 7 is ' ' is space

Character in position 8 is ' M ' is an uppercase letter

Character in position 9 is ' y ' is a lowercase letter

Character in position 10 is ' ' is space

Character in position 11 is ' A ' is an uppercase letter

Character in position 12 is ' D ' is an uppercase letter

Character in position 13 is ' . 'is punctuation sign


-->
Program to create your own Character Function


/* Check the type of a Character*/

#include <stdio.h>
#include <conio.h>

 void main()
   {
         char ch;
         int i;
         clrscr();
         printf("Enter A Character : ");
         fflush(stdin);
         ch=getche();
         if(ch>=65 && ch<=90 || ch>=97 && ch<=122)
                    printf("\n'%c' it is a Letter ",ch);
         if(ch>=65 && ch<=90)
                    printf("\n'%c' it is in UpperCase ",ch);
         else if(ch>=97 && ch<=122)
                    printf("\n'%c' it is in LowerCase ",ch);
         else if(ch==32)
                    printf("\n'%c' it is a Space ",ch);
         else if(ch>=48 && ch<=57)
                    printf("\n'%c' it is a Digit ",ch);
         else
                    printf("\n'%c' it is a Special Character ",ch);
         getch();
   }

Output

Enter A Character : R
'R' it is a Letter
'R' it is in UpperCase

Enter A Character : a
'a' it is a Letter
'a' it is in LowerCase

Enter A Character : 4
'4' it is a Digit

Enter A Character :
' ' it is a Space

Enter A Character : ?
'?' it is a Special Character




/* Character Conversion */
#include <stdio.h>
#include <conio.h>


 void main()
   {
         char ch;
         int i;
         clrscr();
         printf("Enter A Character : ");
         fflush(stdin);
         ch=getche();
         printf("\nOriginal Input '%c",ch);
         if(ch>=65 && ch<=90)
                    ch+=32;
         else if(ch>=97 && ch<=122)
                    ch-=32;
         printf("\nConverted to '%c' ",ch);
         getch();
   }


Output

Enter A Character : c
Original Input 'c
Converted to 'C'

Enter A Character : T
Original Input 'T
Converted to 't'



!!!While checking if you not sure about ASCII values then certainly this function will help you out.!!!

Thursday, March 31, 2011

Booth's Multiplication Algorithm


Booth's multiplication algorithm is a multiplication algorithm that multiplies two signed binary numbers in two's complement notation. Booth's algorithm involves repeatedly adding one of two predetermined values A and S to a product P, then performing a rightward arithmetic shift on P. Let X and Y be the multiplicand and multiplier, respectively; and let X and Y represent the number of bits in X and Y.
  1. Determine the values of A and S, and the initial value of P. All of these numbers should have a length equal to (x + y + 1).
  2. A: Fill the most significant (leftmost) bits with the value of x. Fill the remaining (y + 1) bits with zeros.
  3. S: Fill the most significant bits with the value of (-x) in two's complement notation.
  4. Fill the remaining (y + 1) bits with zeros.
  5.  P: Fill the most significant x bits with zeros. To the right of this, append the value of y. Fill the least significant (rightmost) bit with a zero.
  6. Determine the two least significant (rightmost) bits of P.
  7. If they are 01, find the value of P + A. Ignore any overflow. Perform right shift
  8. If they are 10, find the value of P + S. Ignore any overflow. Perform right shift
  9. If they are 00 or 11, Only perform right shift. Use P directly in the next step.
  10. Arithmetically shift the value obtained in the previous step by a single place to the right. Let P now equal this new value.
  11. Repeat steps 2 and 3 until they have been done y times.
  12. Drop the least significant (rightmost) bit from P. This is the product of x and y.
Example :Find the product of -9 * -12

A (-9)10 9=1001 and 1's Complement  = 0110 2's Complement 0110 +1 = 0111 10111 (1 is sign bit)
S  (A * -1) (9)10 (1001)2
P (-12)10 12=1100 and 1's Complement  = 0011 2's Complement 0011 +1 = 0100 10100 (1 is  sign bit)

Y = 00000 = 5 bits, so repeat the process five times.

X Y +1 New Value
A 10111 00000 0
S 01001 00000 0
101 P 00000 10100 0 Last two bits is 00 Right Shift >>1 00000  01010  0
100 P 00000 01010 0 Last two bits is 00 Right Shift >>1 00000  00101  0
011 P 00000  00101 0 Last two bits is 10 P + S 00000  00101  + 01001 00000 = 01001 00101 0 Right Shift >>1 00100 10010 1
010 P 00100 10010 1 Last two bits is 01 P + A 00100 10010 + 10111 00000 =11011 10010 1 Right Shift >>1 11101 11001 0
001 P 11101 11001 0 Last two bits is 10 P + S 11101 11001 +01001 0000 0 = 00110 11001 0 Right Shift >>1 00011 01100 1
-9 * -12 = 108 After dropping the LSB (Least Significant
Bit)  we get = 00011 01100
= 1101100 =108

Example :Find the product of 15 * -8

A (15)10 (15)10=(1111)2
S  (A * -1) (-15)10 15=1111 and 1's Complement  = 0000 2's Complement 0000 +1 = 0001 10001(1 is  sign bit)
P (-8)10 8=1000 and 1's Complement  = 0111 2's Complement 0111 +1 = 1000 11000(1 is  sign bit)


X Y +1 New Value
A 01111 00000 0
S 10001 00000 0
101 P 00000 11000 0 Last two bits is 00 Right Shift >>1 00000  01100  0
100 P 00000 01100 0 Last two bits is 00 Right Shift >>1 00000  00110
011 P 00000  00110 0 Last two bits is 00 Right Shift >>1 00000  00110
010 P 00000 00011 0 Last two bits is 10 P + S 00000 00011 + 10001 00000 = 10001 00011 Right Shift >>1 11000 10001 1
001 P 11101 11001 0 Last two bits is 11 Right Shift >>1 11100 01000 1
15 * -8 = -120 After dropping the LSB (Least Significant
Bit)  we get = 11100 01000
10001000 = -120

Example :Find the product of 9 * -12

A (9)10 (9)10=(1001)2
S  (A * -1) (-9)10 9=1001 and 1's Complement  = 0110 2's Complement 0110 +1 = 0111 10111(1 is  sign bit)
P (-12)10 12=1100 and 1's Complement  = 0011 2's Complement 0011 +1 = 0100 10100(1 is  sign bit)

X Y +1 New Value
A 01001 00000 0
S 10111 00000 0
101 P 00000 10100 0 Last two bits is 00 Right Shift >>1 00000  01010
100 P 00000 01010 0 Last two bits is 00 Right Shift >>1 00000  00101
011 P 00000  00101 0 Last two bits is 10 P + S 00000 00101 + 10111 00000 = 10111 00101 Right Shift >>1 11011 10010 1
010 P 11011 10010 1 Last two bits is 01 P + A 11011 + 10010 + 01001 00000 = 00100 10010 Right Shift >>1 00010 01001 0
001 P 00010 01001 0 Last two bits is 10 P + S 00010 01001 + 10111 000 = 11001 01001 Right Shift >>1 11100 10100 1
9 * -12 = -108 After dropping the LSB (Least Significant
Bit)  we get = 11100 10100
10010100 = -108

Example : Find the product of 3 x 4


A (3)10 (3)10=(0011)2
S  (A * -1) (-3)10 -3=011 and 1's Complement  = 100 2's Complement 100 +1 = 101 1101(1 is  sign bit)
P (4)10 4=100
4 bits Repeat it for four times

X Y +1 New Value
A 0011 00000 0
S 1101 00000 0
100 P 00000 0100 0 Last two bits is 00 Right Shift >>1 0000  0010
011 P 00000 0010 0 Last two bits is 00 Right Shift >>1 0000  0001
010 P 00000  0001 0 Last two bits is 10 P + S 0000 0001 + 1101 0000 = 1101 0001 Right Shift >>1 1110 1000 1
001 P 1110 1000 1 Last two bits is 01 P + A 1110 1000 + 0011 0000 = 0001 10001 Right Shift >>1 0000 1100 1
3 * 4 = 12 After dropping the LSB (Least Significant
Bit)  we get = 0000 1100
1100= 12

!!!Once again sorry for delay but I wanted it more descript so student can understand it. Next it will be Digital Electronics. Bye!!!

Thursday, February 17, 2011

Quine-McCluskey Method orTabulation Method


In my last blog I have given you some examples, solving Sum of Product (SOP) and Product of Sum (POS) using Karnaugh Map. Today we will solving the same using Quine-McCluskey Method (Tabulation Method)


Example 1:
Simplify the following using Quine-McCluskey Method (Tabulation Method)


f(A,B,C) = Σm(0,1,4,5,6) + Σd(7)

Example 1: f(A,B,C) = Σm(0,1,4,5,6) + Σd(7)

Terms given that includes the don't care option

0

000

1

001

4

100

5

101

6

110

7

111


Repetition of 1's is the basis of grouping.

Group 1


0

000

 Weight = 0
[Group with zero : 1's]

Group2


1

001

 Weight = 1[Group with one : 1's]



4

100


Group 3



5

101

Weight = 2 [Group with two : 1's]



6

110


Group 4



7

111

Weight = 3 [Group with three  : 1's]



Combine a suitable pair to form Column 2, pair can be formed between adjacent group basis of difference. Put a hyphen(-) to indicate difference between the terms. Forming column three will be on the basis of   adjacent pairs that having a hyphen (-) in the identical place. Those terms is used should be marked, here to mark, I used √.



Column I (Number of 1' Implicants)

Column II (Size 2)

Column III (Size 4)

Group1

0

000 √

(0,1) √

00-

(0,1,4,5)

-0-




(0,4) √

-00

(0,4,1,5)

-0-

Group 2


1

001 √

(1,5)  √

-01




4

100 √

(4,5) √

10-

(4,5,6,7)

1--




(4,6) (not used)

1-0



Group 3

5

6
101√

110 √
(5,7)

(6,7)
1-1

11-



Group 4


7

111 √







Rows = prime implicants and columns = ON-set elements place an "X",  if  ON-set element is covered by the prime implicant.Make the following chart using the given terms but do not use the don't care options (cell 7). Also omit the if any duplicate entries like  (0,1,4,5) (0,4,1,5).




0

1

4

5

6

-0- 

 B'

(0,1,4,5)
X
X

X

X


-0-

B'

(0,4,1,5)

X

X

X

X


1--

A

(4,5,6,7)



X

X

X

1- 0

AC'

(4,6)




X


X

After removing duplicate entries we get the following. Now columns 0 and 1  also to be removed as these column has a single X, it has the implicant associated with the row (+) is essential. It must appear in minimum cover.

(**) columns has only one X and row  to be covered is (0,1,4,5) = B'
(*) omit 0,1,4,5 as it is already covered.



0 (**)

1 (**)

4

5

6

-0- 

 B'

(0,1,4,5) +

X (*)

X (*)

X (*)

X (*)


1--

A

(4,5,6,7)



X

X

X

1- 0

AC'

(4,6)



X


X


Eliminate all columns covered by essential primes  (4,5). Find minimum set of rows that cover the remaining columns (4,5,6,7) = A.
f(A,B,C) = Σm(0,1,4,5,6) + Σd(6) = A + B'.

Example 2:
 

Simplify the following using Quine-McCluskey Method (Tabulation Method)

 f(A,B,C,D) = Σm(0,2,8,10,12,13,14,15) + Σd(5,7)

Terms given :
0
0000

2

0010

5

0101

7

0111

8

1000

10

1010

12

1100

13

1101

14

1110


Rewriting in the List basis of weight of 1's

0

0000

2

0010

8

1000

5

0101

10

1010

12

1100

7

0111

13

1101

14

1110

15

1111


Group it basis of repetition of 1's
Group 1

0

0000

 Weight = 0[Group with zero : 1's]

Group2


2

0010

Weight = 1[Group with one : 1's]


8

1000



Group 3

5

0101

Weight = 2 [Group with two : 1's]


10

1010



12

1100

Group 4


7

0111

Weight = 3[Group with three : 1's]


13

1101


14

1110

Group 5


15

1111

Weight = 4[Group with three : 1's]


Combine a suitable pair to form Column 2, pair can be formed between adjacent group basis of difference. Put a hyphen(-) that indicate difference between the terms. Column three only can be formed on the basis of  the pairs having a hyphen (-) in the identical place. Those terms already combined should be marked, here to mark, I used √.



Column I (Number of 1' Implicants)

Column II (Size 2)

Column III (Size 4)

Group1



0

0000 √

(0,2) √

00-0

(0,2,8,10)

-0-0






(0,8) √

-000

(0,8,2,10)

-0-0

Group 2

2
0010

(2,10) √

-010

(8,10,12,14)

1--0

8
1000 √

(8,10) √

10-0

(8,12,10,14)

1--0



(8,12) √

1-00



Group 3

5
0101 √

(5,7) √

01-1

(5,7,13,15)

-1-1

0
1010 √

(5,13) √

-101

(5,13,7,15)

-1-1

12
1100 √

(10,14) √

1-10

(12,13,14,15)

11--




(12,13) √

110-

(12,14,13,15)

11--




(12,14) √

11-0



Group 4


7

0111 √

(7,15) √

-111




13

1101 √

(13,15) √

11-1



14
1110 √

(14,15) √

111-



Group 5








15

1111 √






Rows = prime implicants and columns = ON-set elements, place an "X", if  ON-set element is covered by the prime implicant. Make the following chart using the given terms but do not use the don't care options. Also omit the duplicate entries such like (0,2,8,10) and (0,8,2,10), (8,10,12,14) and .(8,12,10,14), (5,7,13,15) and  (5,13,7,15), (12,13,14,15) and (12,14,13,15).


0

2

8

10

12

13

14

15

B'D'

-0-0

(0,2,8,10)

X

X

X

X





B'D'

-0-0

(0,8,2,10)

X

X

X

X





AD'

1--0

(8,10,12,14)



X

X

X

X

AD'

1--0

(8,12,10,14)



X

X

X


X

BD

-1-1

(5,7,13,15)






X



X

BD

-1-1

(5,13,7,15)






X



X

A

11--

(12,13,14,15)





X

X

X

X

AB

11--

(12,14,13,15)





X

X

X

X


After removing duplicate entries we get the following. Now columns 0 and 2 column has a single X, the implicant associated with the row (+) is essential. It must appear in minimum cover. (**) columns has only one X and row to be covered is (0,2,8,10) = B'.D'.

* omit 0,2,8,10 as it has already covered.


0 **

2 **

8

10

12

13

14

15

B'D'

-0-0

(0,2,8,10) +

X *

X *

X *

X *





AD'

1--0

(8,10,12,14)



X

X

X


X


BD

-1-1

(5,7,13,15)






X


X

AB

11--

(12,13,14,15)





X

X

X

X


Eliminate all columns covered by essential primes  (8,10). Find minimum set of rows that cover the remaining columns
(5,7,13,15) and (12,13,14,15) =BD and AB.

Therefore, from given minterms
f(A,B,C,D) = Σm(0,2,8,10,12,13,14,15) + Σd(5,7) = AB + B'D' + BD

To give you these two examples I have to spent a couple of hours when easily could have solve it within couple of minutes using Karnaugh Map. Often students ask me why to learn this when it is taken more time than the other easier process, frankly I have no idea.

My next target will be booth algorithm and hope will post in time.

!!!For those students who are going to  appear in I.C.S.E. and I.Sc., best wishes for your exam.!!!