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 <stdio.h>
#include <string.h>

int getFirstCapital(char *str, int position, int length)
    if (position == length)
        return -1;

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

    return getFirstCapital(str, position + 1, length);

int main()
    char inputString[100];

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

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

    if (position == -1)
        printf("No capital letter found in the string.");
        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