Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to find the length of a string

C Code Example — String Programs

ADVERTISEMENT

C Program to find the length of a string

Objective

Write a C program to find the length of a string without using library functions.

Algorithm / Approach

  1. Declare a character array and read input using gets().
  2. Initialize a length counter to 0.
  3. Start a while loop that runs as long as the current character is not the null terminator '\0'.
  4. Inside the loop, increment the length counter and the array index.
  5. Print the final length.
main.c
#include<stdio.h>
int main( ) {
 char a[100];
 int i=0, length = 0;
 printf("Enter a String : ");
 gets(a);
 while(a[i] != '\0') {
  length++;
  i++;
 }
 printf("Length = %d",length);
 return 0;
}

Expected Output

Enter a String : C Prowess
Length = 9

Explanation of the Program

  • In C, a String is simply an array of characters. The compiler automatically adds a special hidden character at the very end of every string called the Null Terminator ('\0').
  • To find the length manually, we just iterate through the array counting characters until we hit that null terminator.

Complexity

Time Complexity O(n) - Where n is the string length.
Space Complexity O(1)
ADVERTISEMENT