Introduction:

This C program calculates the length of a string provided by the user. Unlike the built-in strlen function, this program manually counts the number of characters in the string until it reaches the null terminator. This capability is fundamental in programming and helps illustrate how strings are represented in C.

#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    int length = 0;
    while (str[length] != '\0') {
        length++;
    }
    
    // Exclude newline character if present
    if (str[length - 1] == '\n') {
        length--;
    }

    printf("Length of the string: %d\n", length);
    return 0;
}

Include Header Files:

  • #include <stdio.h>: This header file is included for standard input and output functions like printf and fgets.

Declare Variables:

  • char str[100];: An array of characters is declared to hold the input string. The size is set to 100, which allows for input of up to 99 characters plus the null terminator.
  • int length = 0;: A variable to store the length of the string is initialized to zero.

Input the String:

  • printf("Enter a string: ");: Prompts the user to enter a string.
  • fgets(str, sizeof(str), stdin);: Reads a line of text from standard input, including spaces, and stores it in str.
  • str[strcspn(str, "\n")] = 0;: This line removes the newline character that fgets adds to the string. The strcspn function finds the length of the string up to the first newline character, and this position is set to 0 to terminate the string there.

Calculate the Length:

  • while (str[length] != '\0'): This loop iterates through the string until it encounters the null terminator ('\0'), which marks the end of the string.
  • length++;: For each character encountered, the length counter is incremented by one.

Output the Length:

  • printf("Length of the string: %d\n", length);: This line prints the length of the string to the console.

Return Statement:

  • return 0;: Indicates successful completion of the program.

Input/Output Block:

Input:

  • The user is prompted to enter a string.

Example Input:

Enter a string: Hello, World!

Output:

  • The program outputs the length of the entered string.

Example Output:

Length of the string: 13

Conclusion:

The string length program effectively demonstrates how to determine the length of a string in C without relying on built-in functions. By iterating through each character of the string until the null terminator is encountered, the program provides a clear understanding of string manipulation and memory representation in C. This fundamental skill is essential for various programming tasks, including data processing and string analysis. Overall, the program serves as an educational tool, reinforcing key concepts in programming and algorithm design.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights