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
- Declare a character array and read input using
gets(). - Initialize a
lengthcounter to 0. - Start a
whileloop that runs as long as the current character is not the null terminator'\0'. - Inside the loop, increment the length counter and the array index.
- 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)