C Program to Find Length of String without using Library Function

1. Introduction

Strings play a pivotal role in numerous programming scenarios. At times, developers might need to measure the length of a string without resorting to built-in functions for various reasons. 

In this blog post, we will learn how to write a C program to find the length of a string without using the library function.

2. Program Overview

The program is tailored to:

1. Prompt the user for a string.

2. Traverse through each character of the string until the null terminator is found.

3. Compute the length based on the traversal.

4. Display the computed length to the user.

3. Code Program

#include <stdio.h>  // Incorporate the Standard I/O library

int main() {  // Begin main function

    char str[100];  // Array declaration to store user's string
    int length = 0;  // Variable to keep track of the length

    // Request the user for the string
    printf("Enter a string: ");
    scanf("%s", str);  // Read the string

    // Loop to traverse each character of the string
    while(str[length] != '\0') {
        length++;  // Increment the length for each character encountered
    }

    // Display the computed length of the string
    printf("Length of the entered string is: %d\n", length);

    return 0;  // Conclude the program gracefully

}

Output:

Enter a string: programming
Length of the entered string is: 11

4. Step By Step Explanation

1. #include <stdio.h>: This line introduces the standard input/output library.

2. int main(): The execution of the C program starts from main() function.

3. Variable and Array Declaration:

- str[100]: Array that will store the user's string input.

- length: An integer variable initialized to zero, used in calculating the string's length.

4. User Input:

- The user is urged to input a string using print.

- scanf then reads and logs the string in the 'str' array.

5. String Length Calculation:

- A while loop iterates through each character of the string.

- The traversal stops once the null terminator ('\0') is identified.

- For each character, the length variable increments.

6. Display Results:

- The length of the string, as deduced, is then exhibited to the user. 

Comments