Finding length of given string(without using string library)

Program Description

Calcualates length of the given string using user defined function.The string is taken as character array. The user is first prompted for input string and its length is calculated using self defined function and displayed

Program
/*****************************************************
*  code.cheraus.com
*  
*  Finding length of given string(without using string library)	
*
**********************************************/

#include<stdio.h>

//function prototype
int length(char string[100]);

int main()
{
   //character array to store string. Here the size is arbitrarily taken as 100
   char string[100];
   int len;
   
   printf("\nEnter the string : ");
   scanf("%s",&string);
   
   //function call to calculate length
   len = length(string);
   
   printf("\nThe length of %s is %d\n",string,len);
   return 0;
}
/*
 Definition of length function

Function : length(). Calculates the length of the given string.
Input    : takes an array of characters(string) as argument
Return   : return the integer value corresponding to length to the calling
           function
*/
int length(char string[100])
{
  int i=0;
  while(string[i]!='\0')
   i++;
  return i;
}

Output
Test Case 1:

Enter the string : hello
The length of hello is 5
Test Case 2:

Enter the string : code.cheraus.com
The length of code.cheraus.com is 16

Comments
comments powered by Disqus