Write a C program to find the length of a string without using strlen
Description: Take a word as input. Count its characters without using the strlen() function.
Hint:
- A string ends with the null character
'\0'. Count the characters before it.
C program to find the length of a string
#include <stdio.h>
int main(void) {
char s[50];
int length = 0;
printf("Enter a word: ");
scanf("%49s", s);
while (s[length] != '\0') {
length++;
}
printf("Length = %d\n", length);
return 0;
}
Output:
Output of the above program is
Enter a word: Programming
Length = 11
How it works
- The loop moves one character at a time, and stops at the null character.
- The value of
lengthat that point is the number of characters.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |