C program to get the first uppercase letter in a string

C program to get the first uppercase letter in a string :

In this tutorial, we will learn how to find the first uppercase letter or capital letter in a string using C programming language. User will enter the string and our program will find the first capital letter and print it out. Let’s take a look at the program first :

C program :

#include
#include

//5
int getFirstCapital(char *str,int position,int length){
	//6
	if(position == length){
		return -1;
	}

	//7
	if(str[position] >= 'A' && str[position] <= 'Z'){
		return position;
	}

	//8
	return getFirstCapital(str,position + 1,length);
}

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

	//2
	printf("Enter your string : ");
	fgets(inputString, 100, stdin); 

	//3
	int position = getFirstCapital(inputString,0,strlen(inputString));

	//4
	if(position == -1){
		printf("No capital letter found in the string.");
	}else{
		printf("First capital letter is %c ",inputString[position]);
	}

}

Explanation :

1. Create one character array inputString to save the user input string.
2. Ask the user to enter the string. Read it and store it in variable inputString variable.
3. Get the position of the first uppercase letter in the string. Save it in variable position.
4. If the value of position is -1, no capital letter is found in the string. Else, print out the capital letter .
5. getFirstCapital function is used to find the first uppercase letter. This function will be called recursively. If any uppercase character found, return its position. Else return -1.
6. If current position is equal to the length of the string, means the whole string is scanned but not uppercase letter found. Return -1.
7. If the current character is upper case, return the position.
8. Call the same function recusively . Increment the current position by 1 each time.

Sample Output :

Enter your string : find one upper cAse letter
First capital letter is A

Enter your string : hello world
No capital letter found in the string.

Enter your string : hello worlD..
First capital letter is D

Enter your string : HELLO WORLD
First capital letter is H

Leave a Reply