Program 332: Find First Small Letter in String
Output:
#include<stdio.h> #include<string.h> main() { int i,flag=0; char str[100]; printf("Enter String to get First Small Letter of String\n"); gets(str); for(i=0;i<strlen(str);i++) { if(str[i]>'a' && str[i]<'z') { printf("The First Small Letter is %c\n",str[i]); flag=1; break; } } if(flag!=1) printf("There is no small letter\n"); }Explanation:
- First, we are declaring i, flag, and string array str[100] which can contain 100 characters
- i → as an index variable
- flag → to check if finding the first small letter is successful or not which is initialized to 0 which means we are first considering it as unsuccessful
- str[100] → To store the string given by the user
- We used gets(str) to get the user input and remember our string str can only hold up to 100 characters.
- Main Logic
for(i=0;i<strlen(str);i++) { if(str[i]>'a' && str[i]<'z') { printf("The First Small Letter is %c\n",str[i]); flag=1; break; } }
We are iterating through each character in string str. Consider str contains HArRy PoTtER then our first small letter is r at index 2 i.e we are counting the characters from 0
*Note: Check ASCII values of a-z and A-Z from the table within this app
- Iteration 1: i=0, and 0<strlen(str) => 0<12 (one space included) and its true
We go inside and check if the first letter in the string at index 0 which is 'H' is in between 'a' and 'z'.
In most languages, there is a concept called typecasting and the same thing will occur here to check if the character is in the range of ASCII values which are from a=97 to z=122. *You can refer ASCII table within this app.
Since ASCII value of 'H' is 72 which is not in the range of 97 to 122. it will go to the next iteration - Iteration 2: i=1, and 1<strlen(str) => 1<12 and its true
Now we check if 'A' is a small letter or not and since the ASCII value of A is 65 which is not in the range of 97 to 122 then it will continue to the next iteration - Iteration 3: i=2, and 2<strlen(str) => 2<12 and its true
Now we check if 'r' is a small letter or not and since the ASCII value of r is 114 which is in the range of 97 to 122 . We update the value of flag=1 and print "The First Small letter is r" then we come out of the loop using a break statement if(flag!=1) printf("There is no small letter\n");
Finally since flag=1 then we don't print anything under this 'if ' condition
Output: