C program for calculating the length of the string without using strlen() function

Length of the string without using strlen() function

In this article we will be learning about how to work with strings in C programming. This is one of the basic operation on String datatype to count it’s length without using any library functions so that we may understand how does library function eventually work.

C program for finding length of the string without using strlen() function

Algorithm:

  • Initialize a variable ‘str’ , ‘i’ , ‘length’.
  • Accept the value using ‘printf’ and ‘scanf’.
  • Initiate a for loop.
  • Terminate the loop when null(‘\0’).
  • Print length.

C code for Length of the string without using strlen() function.

 

#include <stdio.h>
int main()
{
   //Initializing variable.
    char str[100];
    int i,length=0;
    
     //Accepting input.
    printf("Enter a string: \n");
    scanf("%s",str);

     //Initializing for loop.
    for(i=0; str[i]!='\0'; i++)
    {
        length++; //Counting the length.
    }
    
    printf("\nLength of input string: %d",length);
    
     return 0;
}
Output:
Enter a string:
PREPINSTA
Length of input string: 9

Enter a string:
PREPINSTA

Length of input string: 9