Exercise:
Write a C Program to find the length of a string.
Click Here to View the Solution!
#include <stdio.h>
int main() {
char s[] = "Code of Code is a great website";
int i;
for (i = 0; s[i] != '\0'; ++i);
printf("Length of the given string = %d", i);
return 0;
}
Click Here to View the Output!
Length of the given string = 31
Click Here to View the Explanation!
- This program is used to determine the length of a string without using the
function strlen()
. - In
main()
, astring array s[]
in initialized and an integer variablei
is declared. - A for loop is initialized which iterates between the characters of the string starting from
i = 0
and continues iterations a null character is observed. - In every iteration, the value of
i
is incremented by one. - The length of the string is therefore stored in the variable
i
which is then printed.