C Program to Find the Length of a String | c programming code

C Topics C strlen() Find the Frequency of Characters in a String Concatenate Two Strings String Examples in C Programming Remove all Characters in a S

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

·       C Pointers

·       Relationship Between Arrays and Pointers

·       C Pointers

·       C Pass Addresses and Pointers

·       C Dynamic Memory Allocation

·       C Programming Strings

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.

Calculate Length of String without Using strlen() Function

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


Length of the string: 18

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.


Note: Here, the array s[] has 19 elements. The last element s[18] is the null character '\0'. But our loop does not count this character as it terminates upon encountering it.


Labels : #c ,#code ,#examples ,

Post a Comment