C Programming Code Examples C > Strings Code Examples find First and Last Occurrence of given Character in a String find First and Last Occurrence of given Character in a String This program takes a string and a character as input and finds the first and last occurrence of the input character in a string. - Take a string and a character as input and store it in the array str[] and variable key respectively. - Using for loop search for the variable key. If it is found then increment the variable count. - If the value of count is equal to 1, then copy the value of j into the variables pos1 and pos2 and print the value (pos+1) as the first position. - If the value of count is not equal to 1, then just copy the value of j into the variable pos2. Do this step until the end of string. - Print the value (pos2+1) as the last position and exit. #include <stdio.h> #include <string.h> void main() { int j, count = 0, pos1, pos2; char str[100], key, a[20]; printf("enter the string\n"); scanf(" %[^\n]s", str); printf("enter character to be searched\n"); scanf(" %c", &key); for (j = 0;j <= strlen(str);j++) { if (key == str[j]) { count++; if (count == 1) { pos1 = j; pos2 = j; printf("%d\n", pos1 + 1); } else { pos2 = j; } } } printf("%d\n", pos2 + 1); }