String length in c is a basic and easy program.
In this tutorial we are going to see one important program which is to find the length of the string without using string function.
Mostly in exam or in interview they ask such type of program.
logic to find String length in c :
We know the concept of string. String always ends with the null character.
Using this important point we can find the length of string without string function.
We take one count variable to store the length of string. We read the string character by character till we encounter Null and simultaneously we increment the count variable. As Null character encounter which means the string reached to end and we stop execution.
As we incremented and stored count variable we have final count value which is known as length of the string.
Concept from c you need to know :
Algorithm length of string in c :
- Declare variable.
- Take input string from user.
- Read string character one by one
- Increment counter variable.
- String encounters end i.e null stop
- Print counter variable as length of string.
Program to find length of string in c :
printf("Enter a string: ");
for(i = 0; str[i] != '\0'; ++i);
printf("Length of string %s: %d", str,i);
Output of length of string in c :
- First include preprocessor directives in c stdio.h and conio.h which compiler adds in our program while execution.
- Write the main function where program execution starts.
- Declare he variables. char str; to store string input and int i for temporary variable.
- Take user input a string in str.
- Now we need to find the length of the string without string function. As we know the concept of string that is string always ends with the null character using this statement we traverse the string using index starting from 0 to till we encounter null. For this we written next statement for(i = 0; str[i] != ‘\0’; ++i) which states that for loop starts with 0 and str[i] != ‘\0’ condition to check we reached at end of the string and, i++ for next index. for example : str = abc . At Iteration 1 : i=0 and condition str != ‘\0’ => it becomes true . after that i = 1. At Iteration 2 : i=1 and condition str != ‘\0’ => it becomes true . after that i = 2.
At Iteration 3 : i=2 and condition str != ‘\0’ => it becomes true . after that i = 3.
At Iteration 4 : i=3 and condition str != ‘\0’ => it becomes false.
- Now we have the value of i = 3 which is the length of the string.
- So, Print the length of the string.