Here's a C program to find the length of the given string with output and explanation. This program makes use of C concepts like For loop and gets Function in C.
# include <stdio.h> # include <conio.h> void main() { char str[80] ; int i ; clrscr() ; printf("Enter the string : ") ; gets(str) ; for(i = 0 ; str[i] != '\0' ; i++) ; printf("\nThe length of the string is : %d", i) ; getch() ; }
Output of above program
Enter the string : C Program
The length of the string is : 9
Explanation of above program
In this program, we have first declared a character array str of size 80. Then, the program prompts the user to enter a string whose length is to be found. String is taken as input using gets function (What is gets function?) and stored in character array str itself. After that using FOR loop, length of string is determined.
Here if you look at the FOR loop, you might find its syntax a bit weird as there is no body of this FOR loop and the FOR statement is terminated by a semicolon (;). But working of FOR loop in this program is very simple. The loop runs from loop variable i = 0 to str[i] != '\0', incrementing i each time until null character is encountered. This means that this FOR loop will until str[i] is null.
Lets understand the working of FOR loop using an example.
Suppose, user enters the string as "Hello" and this is stored in str. So now str = "Hello". Now, working of FOR loop is as follows -
When i = 0, str[i] = H: Value of i is incremented to 1.
When i = 1, str[i] = e: Value of i is incremented to 2.
When i = 2, str[i] = l: Value of i is incremented to 3.
When i = 3, str[i] = l: Value of i is incremented to 4.
When i = 4, str[i] = o: Value of i is incremented to 5.
When i = 5, str[i] = \0: Loop is terminated.
So, after FOR loop is executed, value of i shows the length of the string.