Saturday 11 November 2017

C Program to find First and Last Occurrence of given Character in a String


Code:

#include  stdio.h>
#include  string.h>

void main()
{
    int i, count = 0, pos1, pos2;
    char str[50], key, a[10];

    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])
        {
            count++;
            if (count  == 1)
            {
                pos1 = i;
                pos2 = i;
                printf("%d\n", pos1 + 1);
            }
            else 
            {
                pos2 = i;
            }
        }
    }
    printf("%d\n", pos2 + 1);
}


Output:

enter the string
welcome to executecod c programming class!
enter character to be searched
m

34


More C Programs:











100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...