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 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;
}
                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.