C program to find the last occurrence of a character in a string using while loop.
C program to find the last occurrence of a character in a string using while loop.
#include <stdio.h>
#include <string.h>
#define MAX 100
int lastIndex(const char * text, const char find);
int main()
{
char text[MAX];
char find;
int index;
printf("\n Enter any string: ");
gets(text);
printf("\n Enter any character to find in the string: ");
find = getchar();
index = lastIndex(text, find);
printf("\nLast index of '%c' is %d", find, index);
return 0;
}
int lastIndex(const char * text, const char find)
{
int index = -1;
int i = 0;
while(text[i] != '\0')
{
if(text[i] == find)
{
index = i;
}
i++;
}
return index;
}
Output:
Enter any string: computer
Enter any character to find in the string: r
Last index of 'r' is 7