C program to find the first and the last position of a character in a string

C program to find the first and last position of a character in a string :

In this tutorial, we will learn how to find the first and last position of a character in a given string using C. The program will take the inputs(string and character) from the user and find out the first and last occurance of the given character. Let’s take a look at the program first :

C program :

#include

int main(){
	//1
	char str[100];

	//2
	int firstPosition = -1;
	int lastPosition = -1;
	char ch;
	int i;

	//3
	printf("Enter a string : \n");
	fgets(str,100,stdin);

	//4
	printf("Enter the character to search : ");
	scanf("%c",&ch);

	//5
	for(i=0 ;str[i];i++){
		//6
		if(str[i] == ch){
			//7
			if(firstPosition == -1){
				firstPosition = i;
			}else{
				lastPosition = i;
			}
		}
	}

	//8
	if(firstPosition == -1 && lastPosition == -1){
		printf("Character '%c' is not found in the string\n",ch);
	}else if(lastPosition == -1){
		printf("Character '%c' is found 1 time on position '%d'\n",ch,firstPosition);
	}else{
		printf("Character '%c' is found on position '%d' first,and on position '%d' last\n",ch,firstPosition,lastPosition);
	}

}

Explanation :

The commented numbers in the above program denote the step-number below :

1. Create one character array variable to store the string.
2. Create two integer variables to store the first and the last position of the character. One character variable ch to store the input character and one integer variable i to use in the loop.
3. Ask the user to enter a string. Read the string and save it in variable str.
4. Ask the user to enter the character . Read it and save it in variable ch.
5. Run one for-loop to scan all the characters of the string.
6. Check for each character if it is equal to the input character or not.
7. If the current character is equal to the input character, check if first position value is still -1 or not. -1 means this is the first occurrence of the chracter. Update the first position variable if it is the first occurrence, else update the second position variable.
8. After all characters are scanned, check if the character is found or not, if it is found one time or multiple time. Print the results accordingly.

Sample Output :

Enter a string :
hello world
Enter the character to search : e
Character 'e' is found 1 time on position '1'

Enter a string :
hello world
Enter the character to search : x
Character 'x' is not found in the string

Enter a string :
hello world
Enter the character to search : l
Character 'l' is found on position '2' first,and on position '9' last

Leave a Reply