C Program to Find Length of String Without using Library Function
C Program to Find Length of String Without using Library Function
It is easier to find the length of the string using given library function, but in this program we are finding the length of the string without using library function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include<stdio.h> int main() { char str[100]; int length; printf("\nEnter the String : "); gets(str); length = 0; // Initial Length while (str[length] != '\0') length++; printf("\nLength of the String is : %d", length); return(0); } |
Explanation of Program :
In the above program we have accepted the string from the user.
1 2 | printf("\nEnter the String : "); gets(str); |
After that we have initialized the length variable with zero. “length” variable is used to keep track of the number of character accessed.
1 | length = 0; // Initial Length |
Initially length is 0. Now we are accessing very first character. If it is equal to NULL then we are terminating the loop else we are incrementing the length.
1 2 | while (str[length] != '\0') length++; |
Dry Run :
Consider input string - “mumbai”.
While loop Iteration | length | str[length] |
---|---|---|
Before While Loop | 0 | m |
After Iteration 1 | 1 | u |
After Iteration 2 | 2 | m |
After Iteration 3 | 3 | b |
After Iteration 4 | 4 | a |
After Iteration 5 | 5 | i |
After Iteration 7 | 6 | Loop Terminated |
Now last step is to print the length of the string -
1 | printf("\nLength of the String is : %d", length); |