C Program to Find the Length of a String Without using 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.

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
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 Books in C Programming, Data-Structures and Algorithms

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
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.