Below is the program to find the length of a string with explanation.
#include <stdio.h>
int main() {
char s[] = “Programming is fun”;
int i;
for (i = 0; s[i] != ‘\0’; ++i);
printf(“Length of the string: %d”, i);
return 0;
}
Output-
Length of the string: 18
Below is the step-by-step explanation of the program.
- We start by including the standard input/output library with the
#include <stdio.h>statement. - We then define the
main()function, which is the starting point of any C program. - We declare a character array called
sand initialize it with the string “Programming is fun” with the statementchar s[] = "Programming is fun";. This arraysholds the characters of the string we want to find the length of. - We declare an integer variable
iwhich will be used to iterate over the characters of the strings. - We start a
forloop with the statementfor (i = 0; s[i] != '\0'; ++i);. This loop will iterate over each character in thesarray starting from the first character with the index 0. It will continue to loop until it reaches the null character'\0', which indicates the end of the string. - The loop condition
s[i] != '\0'checks if the current character is not equal to the null character. If it is not equal, the loop body is executed. Otherwise, the loop terminates. - In each iteration of the loop, we increment the value of
iby 1 with the statement++i. This means we move to the next character in the arrays. - When the loop terminates,
iwill hold the number of characters in the strings. - Finally, we print the length of the string with the statement
printf("Length of the string: %d", i);. The%dformat specifier tellsprintf()to print an integer value, which we provide with the variablei. - We end the program by returning 0 from the
main()function with the statementreturn 0;.
Once you have written the code, you can compile and run it using a C compiler, such as GCC, on your computer. The program will then display output on the screen when executed.
For more information about C programming join our course of C programming.