C Program to find length of string without using Library function

Home Forums Programming C Program to find length of string without using Library function

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #1136
    Basavaraj
    Member
    1. #include<stdio.h>  
    2. #include<conio.h>  
    3. void main()  
    4. {  
    5.   int length( char *p ); // Function prototype.  
    6.   char *ptr;  // char pointer to read the string.  
    7.   int len;    // variable in which length is stored.  
    8.   clrscr();  
    9.   printf("Enter a string : ");  
    10.   gets( ptr ); // reading string from keyboard  
    11.   len=length( ptr ); // string is passed as argument to function( funcation call)  
    12.   printf("Length of string is : %d",len); // displaying the result.  
    13.   getch();  
    14.   
    15. }  
    16.   
    17.   
    18. int length( char *p )  // Function definition  
    19. {  
    20.   int len=0;  
    21.     
    22.   while( *p )  
    23.   {  
    24.   len++;  
    25.   p++;  
    26.   }  
    27.   return(len);  
    28.   
    29. }  

    This problem is solved by defining out own function to find the length of string. here i have used char pointer to read the string.
    using the concept of pointer we could solve the problem easily.

    the while loop while( *P ) { len++; } gets executed repeatedly until it encounters null char which is usually present at the end of the string. the *p is written to fetch char from its pointer it is known as indirection operator,after fetching the char the pointer is incremented using the statement p++ which will make the pointer to point to the next char.

    #1140
    Satish
    Keymaster

    Sir, edit the post and use these syntax to format it to look better.

    Syntax For Writing Your Program Code On This Forum

    don’t forget about the < and > replacement strings of html while writing the code.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.