C program to search for a character in a string


#include <stdio.h>
int main()
{
    char string[10],search;
    int i,flag=0;
    printf("Enter the string\n");
    scanf("%s",string);
    printf("Enter the element to be searched:");
    scanf(" %c",&search);
    for(i=0;string[i]!='\0';i++)
    {
     if(string[i]==search)
      {
        flag=1;
        printf("\n %c Found at the position %d",search,i+1);
        break;
      }
   }
   if(flag==0)
   printf("\nNot Found");
    return 0;
}

Output:
Enter the string
program
Enter the element to be searched:
g
g found at the position 4

The above program will search the character in the string, and if it is found once flag will become 1, character will be printed with its position and break statement is applied to come out of the loop once the character is found. 


#include <stdio.h>
#include<stdlib.h>
int main()
{
    char *string,search;
    int i,flag=0,size;
    printf("Enter the size of the string\n");
    scanf("%d",&size);
    string=(char*)malloc(size+1);
    printf ("Enter the string:");
    scanf(" %[^\n]%*c",string);
    printf("Enter the element to be searched:");
    scanf(" %c",&search);
    for(i=0;string[i]!='\0';i++)
    {
     if(string[i]==search)
      {
        flag=1;
        printf("\n %c Found at the position %d",search,i+1);
        
      }
   }
   if(flag==0)
   printf("\nNot Found");
    return 0;
}

Output:
Enter the size of the string
12
Enter the string
god is great
Enter the element to be searched:
g
g found at the position 1
g found at the position 8

The above program will take a string as input. The memory allocation for the string is at runtime using malloc function. 
The string will also count the blank spaces using syntax, "%[^\n]%*c", these syntax will consider the blank spaces. When we use "%s", blank spaces are not count and, it will consider blank space as null character, due to which we cannot input string as sentence with spaces. 

Here we haven't used break statement, due to which the entire for loop is iterated, that's why, if the character which we have to search is present in the string more than once, it will be printed that much number of times.