C Program to Find the Length of a String without using the Built-in Function

«
»

This is a C program to find the length of a string without using the built-in function.

Problem Description

This program takes a string as input and finds its length without using the built-in function.

Problem Solution

1. Take a string as input and store it in the array.
2. Using for loop count the number of characters in the array and store the result in a variable.
3. Print the variable as output.

advertisement
Program/Source Code

Here is source code of the C program to find the length of a string without using the built-in function.The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1.  
  2. /*
  3.  * C program to find the length of a string without using the
  4.  * built-in function
  5.  */
  6. #include <stdio.h>
  7.  
  8. void main()
  9. {
  10.     char string[50];
  11.     int i, length = 0;
  12.  
  13.     printf("Enter a string \n");
  14.     gets(string);
  15.     /*  keep going through each character of the string till its end */
  16.     for (i = 0; string[i] != '\0'; i++)
  17.     {
  18.         length++;
  19.     }
  20.     printf("The length of a string is the number of characters in it \n");
  21.     printf("So, the length of %s = %d\n", string, length);
  22. }
Program Explanation

1. Take a string as input and store it in the array string[].
2. Using for loop count the number of characters in the array string[]. Use the variable length to keep the count of the characters in the array.
3. Do step-2 till the end of input string.
4. Print the variable length as output.

advertisement
Runtime Test Cases
Enter a string
Sanfoundry
The length of a string is the number of characters in it
So, the length of Sanfoundry = 10

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms

advertisement
If you wish to look at other example programs on Strings, go to C Programming Examples on Strings. If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn