Here is the code:
#include<stdio.h>
#include<conio.h>
int main()
{
char string[100]; //for storing character array
char ch; //for storing the character given by user
char temp='!'; //for checking each character with ch
int count=0; //counter for while loop
int flag=0; // becomes 1 after the first occurence of ch in string
// and increases after the subsequent occurences
clrscr(); // used to clear screen(optional)
printf("Enter a string\n");
scanf("%[^\n]",string); // read string from the user
printf("Enter the character: ");
scanf("%c",&ch); // read character from the user
while(temp!='\0') //temp initiated with '!' so a to enter the loop
{
temp=string[count];
if(temp==ch)
{
flag++;
}
else if(flag==1)
{
printf("%c",temp);
}
count++;
}
getch();
return 0;
}
EXPLANATION:
Firstly, I have stored the string and character.
Then, a temporary character variable temp
, to store each character of the string one by one in the loop.
Then, temp
is matched against ch
and when temp
matches ch
, flag
is increased from 0
to 1
for the first time and all the subsequent characters are printed on the console, until the second time temp
matches ch
and then, flag
is further increased, which stops the printing of further characters.