Home / Programs / Calculate Length of String without Using strlen() Function
Programming Example

Calculate Length of String without Using strlen() Function

👁 568 Views
💻 Practical Program
📘 Step by Step Learning

To understand this example, you should have the knowledge of the following C programming topics:

  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • C for Loop

As you know, the best way to find the length of a string is by using the strlen() function. However, in this example, we will find the length of a string manually.

Program Code

#include <stdio.h>
int main() {
    char s[] = "Programming is fun";
    int i;

    for (i = 0; s[i] != '\0'; ++i);
    
    printf("Length of the string: %d", i);
    return 0;
}

Output

Length of the string: 18

Explanation

Here, using a for loop, we have iterated over characters of the string from i = 0 to until '\0' (null character) is encountered. In each iteration, the value of i is increased by 1.

When the loop ends, the length of the string will be stored in the i variable.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.