This is a C Program to 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.
1. Take a string and a character as input.
2. Using for loop search for the input character.
3. When the character is found, then print its corresponding position.
4. Again keep on searching for the input character. Now keep on incrementing a variable whenever the input character encounters.
5. Do step-4 until the end of string. when it is done, print the value of the variable.
Here is source code of the C Program to find first and last occurrence of given character in a string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
* C Program to find First and Last Occurrence of given
* Character in a String
int i, count = 0, pos1, pos2;
char str, key, a;
printf("enter the string\n");
scanf(" %[^\n]s", str);
printf("enter character to be searched\n");
scanf(" %c", &key);
for (i = 0;i <= strlen(str);i++)
if (key == str[i])
if (count == 1)
pos1 = i;
pos2 = i;
printf("%d\n", pos1 + 1);
pos2 = i;
printf("%d\n", pos2 + 1);
1. Take a string and a character as input and store it in the array str and variable key respectively.
2. Using for loop search for the variable key. If it is found then increment the variable count.
3. If the value of count is equal to 1, then copy the value of i into the variables pos1 and pos2 and print the value (pos+1) as the first position.
4. If the value of count is not equal to 1, then just copy the value of i into the variable pos2. Do this step until the end of string.
5. Print the value (pos2+1) as the last position and exit.
enter the string welcome to sanfoundry's c programming class! enter character to be searched m 6 34
Sanfoundry Global Education & Learning Series – 1000 C Programs.