Program 40:
Output:
#includeExplanation:<stdio.h> main() { char str[100]; int i,len=0; printf("Enter a string to know the length\n"); scanf("%s",&str); for(i=0;str[i]!='\0';i++) { len++; } printf("The length of %s is %d\n",str,len); }
- This program starts with initializing :
- str[100] → To store string with length of 100 which means it can store 100 letters
- i →Used as helping variable
- len→ To store length of given string and is initilized to zero.
printf("Enter a string to know the length\n"); scanf("%s",&str);
takes the string from userfor(i=0;str[i]!='\0';i++) { len++; }
When ever you enter a string,compiler will add \0 at the end of the string.This is not visible to us.So if you enter "helloworld" which is interpreted as "helloworld\0" where \0 is single letter indicates the end of the string.- Lets take a small example of string "he"
- Iteration 1:i=0,and str[0] is 'h' and it is not \0 which means for loop is executed
- now len will be incremented by 1 so len=1
- i will be incremented by 1 and i=1
- Iteration 2:i=1,and str[1] is 'e' and it is not \0 which means for loop is executed
- now len will be incremented by 1 so len=2
- Iteration 3:i=2,and str[2] is '\0' so for loop is terminated
- Iteration 1:i=0,and str[0] is 'h' and it is not \0 which means for loop is executed
printf("The length of %s is %d\n",str,len);
Finally len is printed.Which is len=2
Output:
No comments:
Post a Comment