About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Tuesday, September 3, 2013

C Program to Find Length of the String using Pointer

#include<stdio.h>
#include<conio.h>
int string_ln(char*);
void main()
{
  char str[20];
  int l;
  clrscr();
  printf("Enter any string:n");
  gets(str);
  l=string_ln(str);
  printf("The length of the given string %s is : %d",str,l);
  getch();
}
int string_ln(char*p)  /* p=&str[0] */
{
  int count=0;
  while(*p!='')
  {
    count++;
    p++;
  }
  return count;
}

Output :

Enter the String : Amit
Length of the given string Amit is : 4

Explanation :

  1. gets() is used to accept string with spaces.
  2. we are passing accepted string to the function.
  3. Inside function we have stored this string in pointer. (i.e base of the string is stored inside pointer variable).
  4. Inside while loop we are going to count single letter and incrementing pointer further till we get null character.

No comments: