Thursday, September 29, 2011

String in C and Some String Programs[I]




C does not have a string type as other later programming languages like Java. C only has character type. Therefore, string is defined as an array of characters or a pointer to characters.

String is always terminated by a special character which is called as null ('\0'). When we define a string you should be sure to have sufficient space for the null too. In ASCII table, the null terminator has value 0.

String Declaration

A String can be declared as an array of characters.
char a[8]="Testing";
We can use pointer also for this.
char *a="Testing";


Both declaration is look same but it is different. In first one, you declare a string as an array of character, the size of string is 8 bytes including the null. In second case, the compiler will allocate memory space for the string and the base address of the string will be assigned to the pointer variable a.

Built in Function for String is already given one of my previous post. I am giving some ‘C’ program using String. Most of the program I tried to skip the Built-in-String functions.

Separate the word from a Sentence and counting vowel, digits etc.




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

//Separating Tokens

  void main()
      {

           char sent[100],word[30],vow[10]="AEIOUaeiou";
           int i,j,w=0,c=0,s=0,c1=0,v=0,d=0,nm=0,sp=0,oth=0;
           clrscr();
           printf("Enter The Sentence : ");
           gets(sent);
           for(i=0;i<20;i++)
                   word[i]='\0';
           for(i=0;sent[i]!='\0';i++)
                   c1++;
           sent[c1]=' ';
           sent[c1+1]='\0';
           printf("\nOriginal Sentence : %s",sent);
           printf("\nThe Word Present Are : \n");
           for(i=0;i
              {
                   j=0;
                   while(sent[i]!=' ')
                        {
                            word[j++]=sent[i];
                            i++;
                        }
                   word[j]='\0';
                   printf("\n\t%s",word);
              }
           for(i=0;sent[i]!='\0';i++)
              {
                   for(j=0;j<10;j++)
                        {
                            if(sent[i]==vow[j])
                                {
                                      v++;
                                }
                        }
                   if(sent[i]==' ' && sent[i+1]!=' ')
                            w++;
                   if(sent[i]>=65 && sent[i]<=90)
                        {
                            c++;
                        }
                   if(sent[i]>=97 && sent[i]<=122)
                        {
                            s++;
                        }
                   if(sent[i]==' ')
                        {
                            sp++;
                        }
                   if(sent[i]>=48 && sent[i]<=57)
                        {
                            d++;
                        }
              }
      sp=sp-1;
      c1=c1-(c+s+sp+d);
      printf("\n\n\tNumber of Vowels %d",v);
      printf("\n\tNumber of Consonant %d",(c+s)-v);
      printf("\n\tNumber of Capital Letters : %d",c);
      printf("\n\tNumber of Small Letters : %d",s);
      printf("\n\tNumber of Spaces %d",sp);
      printf("\n\tNumber of Digits : %d",d);
      printf("\n\tNumber of Other Characters : %d\n",c1);
      getch();
  }

Password Entry Program.

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

//Check for User’s Name and Password

  void main()
   {
      char pass[20], ch,Nm[30];
      int i=0;
      ch=' ';
      clrscr();
      printf("\nEnter User's Name : ");
      gets(Nm);
      printf("\nYour Password [Limit 20 Letters] (Press Return to stop) : ");
      while(ch!=13)
           {
              ch=getch();
                   if(ch==13)
                            break;
              pass[i]=ch;
              printf("*");
              i++;

           }
       pass[i]='\0';
       if((strcmpi(Nm,"Admin")==0) && (strcmpi(pass,"Manager")==0))
           {
              printf("\n\n\tLogged In! User's Name : %s  Your Password : %s ",Nm,pass);
           }
       else
           {
              printf("\n\n\t\t** Wrong Input ** ");
              printf("\n\n\t\t\tQuit.....");
              delay(1250);
              exit(0);
           }
       getch();
  }

Find and replace a word from a sentence.


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

//Program Find-Replace

  void main()
      {
           char a[100],b[30],f[30],r[30],nw[100]="";
           int i,k,j,c1,c=0,fl=0;
           clrscr();
           printf("\nenter the sentence:");
           gets(a);
           printf("\nEnter a word to find : ");
           gets(f);
           for(i=0;a[i]!='\0';i++)
                   c++;
           a[c]=' ';
           a[c+1]='\0';
           for(j=0;j<30;j++)
              {
                   b[j]='\0';
              }
           for(i=0;a[i]!='\0';i++)
              {

                   j=0;
                   fl=0;
                   while(a[i]!=' ')
                        {
                            b[j++]=a[i];
                            i++;
                        }
                   b[j]='\0';
              if(strcmpi(f,b)==0)
                   {
                        fl=1;
                        printf("\nThe Word  '%s' Found in %d position :",b,i-strlen(b)+1);
                        printf("\nEnter the word to replace : ");
                        gets(r);
                   }
              if(fl==0)
                   {
                        strcat(nw,b);
                        strcat(nw," ");
                   }
              else
                   {
                        strcat(nw,r);
                        strcat(nw," ");
                   }
           }
      printf("\n%s",nw);
      getch();
   }

Print Initial from Given name of any length.


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

//Program for Printing Initials

void main()
      {
           char name[80];
           int i,j=0,c=0;
           clrscr();
           printf("\n\tEnter A Full Name with Title : ");
           gets(name);
           for(j=0;name[j]!='\0';j++)
              {
                   c++;
              }
           for(j=c;j>=0;j--)
              {
                   name[j]=name[j-1];
              }
           name[0]=' ';
           name[c+1]='\0';
           printf("\n\tOriginal Input >> %s and Initial : ",name);
           for(i=c;i>=0;i--)
              {
                   if(name[i]==' ')
                            break;
              }
           for(j=0;j<i;j++)
              {
                   if(name[j]==' ' && name[j+1]!=' ')
                            printf("%c. ",name[j+1]);
              }
           for(j=i+1;j<=c;j++)
              {
                   printf("%c",name[j]);
              }
      getch();
   }


Perform different string routine.

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

//Program for String routines


 void strev()
   {
      int i,j,len=0;
      char src[100],dest[100],ch='a';
      fflush(stdin);
      printf("\n\t\tEnter a String : " );
      gets(src);
  for(i=0;src[i]!='\0';i++)
  {
     len++;
  }
      j=0;
      for(i=len-1;i>=0;i--)
  {
     dest[j]=src[i];
     j++;
  }
      dest[j]='\0';
      printf("\n\t\tOriginal %s and Reversed %s ",src,dest);
      printf("\n\t\tPress any key to cont..");
      getch();
      clrscr();
   }
 void stcp()
   {
      int i,len=0;
      char src[100],dest[100];
      fflush(stdin);
      printf("\n\t\tEnter a String : " );
      gets(src);
  for(i=0;src[i]!='\0';i++)
  {
     len++;
  }
      for(i=0;ii<len;i++)
  {
     dest[i]=src[i];
  }
      dest[i]='\0';
      printf("\n\t\tOriginal %s and Copied to %s ",src,dest);
      printf("\n\t\tPress any key to cont..");
      getch();
      clrscr();
   }
 





Thursday, September 22, 2011

Recursion and Recursive Function [in C]



When a user defined function perform a routine for certain time with the help of any iteration but by calling itself, the function is known as recursive function.

Recursions are easy to handle and make the program very simple than its iterative solution, which is very big and complex but
it hurt  both the complexity, time and space.

Advantages :

While writing a program using multiple iteration make the program very complex and big while recursion is usually simple.

Disadvantages :

1.     Recursive solution is always logical and it is very difficult debug.
2.     Before each recursive calls current values of the variables in the function is stored in the PCB (process control block) and then pushed to the OS Stack. Therefore, it occupies lot of free memory.
3.     Execution also need more time than a simple iterative program.

Tail Recursion :

Tail recursive function where all recursive calls are tail calls,  making a tail-recursive call, the caller's return position need not be saved on the call stack. When the recursive call returns, it will branch directly on the previously saved return position. Therefore,  tail recursion saves both space and time.

Here is some Examples of Recursive function.

Print the sum of first ten natural number.

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

//Sum of first ten natural no.
 
int Sum(int n, int s)
  {
      if(n<=10)
           {
              s=s+n;
              printf("%d ",n);
              return Sum(n+1,s);
           }
      else
              return s;
  }
  void main()
  {
      int s=0;
      clrscr();
      s=Sum(1,s);
      printf("  Sum = %d",s);
      getch();
  }



Factorial of a given no.

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

  //Factorial

  int fact(int n) //Recursive function
      {
           if(n<=1)
              {
                   return n;       // return to main program
              }
           else
              {
                   return n*fact(n-1);   // calling self
              }
      }
  void main()
      {
            int n,f;
           clrscr();
           printf("Enter a No. : ");
           scanf("%d",&n);
           f=fact(n);
           printf("Factorial of  %d =  %d ",n,f);
           getch();
      }

GCD of two numbers. [This one is an example of Tail Recursion]

#include <conio.h>
#include <stdlib.h>


//GCD

  int gcd(int x,int y)
   {
       if(y==0)
           {
              return x;
           }
      else
           {
              return gcd (y,x%y);
           }
   }
  void main()
   {
       int a,b,c;
       clrscr();
       printf("\n\tEmter First No. : " );
       scanf("%d",&a);
       printf("\n\tEmter Second No. : " );
       scanf("%d",&b);
       c=gcd(max(a,b),min(a,b));
       printf("\n\tGCD of %d and %d = %d ",a,b,c);
       getch();

   }

Print first 10 Fibonacci Seriers.

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

//Fibonacci Series

void fibo(int a, int b, int i)
  {
    if(i<10)
       {
           printf("\n %d ",a+b);
           fibo(b,a+b,i+1);
       }

  }
  void main()
   {
      clrscr();
      printf("\n 0");
      fibo(1,0,1);
      getch();
   }

Reverse Fibonacci Series (using iteration method you will find it very though).
#include <stdio.h>
#include <conio.h>

//Reverse Fibonacci Series

 void fibo(int n,int a,int b,int c)
   {
      if(n>1)
          {
              c=a+b;
              fibo(n-1,b,c,c);
          }
               if(n>1)
                   printf(" %d ",c);
   }
   // main function
   void main()
    {
          int n;
          clrscr();
          printf("Enter a No. : ");
          scanf("%d",&n);
          fibo(n,1,0,0); // 1 and 0 the value of a and b
          printf("0 ");
          getch();
    }

Check a given numbers is prime or not

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

//Prime No.

  int IsPrime(int n,int i)
      {
           if(i<n)
              {
                   if(n%i==0)
                        {
                            return 1;
                        }
                   else
                        {
                            return IsPrime(n,i+1);
                        }
              }
           return 0;
      }
  void main()
      {
           int n;
           clrscr();
           printf("\nEnter a No. : ");
           scanf("%d",&n);
           if(IsPrime(n,2)==0)
              {
                   printf("\n\t%d is a prime ",n);
              }
           else
              {
                   printf("\n\t%d is not a prime ",n);
              }
           getch();
      }

Print Armstrong numbers between 1 to 1000


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

// Recursion for nested Loop to print Armstrong numbers

  int Armstrong(int n,int s)
      {
           int r;
           if(n>0)
              {
                   r=n%10;
                   s=s+r*r*r;
                   Armstrong(n/10,s);
              }
           else
                //    printf("\n%d ",s);
                   return s;
      }

  void Arm(int Limit)
      {  int s;
           if(Limit>=1)
              {
                   s=Armstrong(Limit,0);
                   Arm(Limit-1);
              }
           if(s==Limit)
                   printf("\n%d ",s);

      }

  void main()
      {
           int n;
           clrscr();
           printf("\nEnter the Limits : ");
           scanf("%d",&n);
           Arm(n);
           getch();
      }

Print the following  Pattern using Recursion.
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *


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

// Recursion for nested Loop

  void Pattern(int i,int j)
      {
           if(j<=(i*2)-1)
              {
                   printf("*");
                   Pattern(i,j+1);
              }
      }

  void Pat(int i,int size)
      {
           if(i<=size)
              {
                   Pattern(i,1);
                   printf("\n");
                   Pat(i+1,size);
              }
      }

  void main()
      {
           int n;
           clrscr();
           printf("\nEnter the Limits : ");
           scanf("%d",&n);
           Pat(1,n);
           getch();
      }