In this article, we are going to write a  program to find the first capital letter in a string using recursion in C programming language.

First of all, we included ctype.h header file in our program. ctype.h header file contains many functions, such as the function, which will be used in our program. If the passing character is in uppercase, then the function isupper() will return 1 and return 0 if the passing character is in lowercase.


Here is the program source code to find the first capital letter in a string in C using recursion. This program is successfully compiled, and the output is also given below.

C Program to Find the First Capital Letter in a String

#include <string.h>
#include <ctype.h>
#include <stdio.h>

char capitalChaker (char *Str);

int
main ()
{
  char Str[30];

  printf ("Please Enter Any String To Find First Capital Letter in it: ");
  scanf ("%s", Str);

  char Letter;

  Letter = capitalChaker (Str);

  if (Letter == 0)
    {
      printf ("No Capital Letter is Found in String %s.\n", Str);
    }
  else
    {
      printf ("First capital letter in String %s is %c.\n", Str, Letter);

    }

  return 0;
}

char capitalChaker (char *Str)
{
  static int count = 0;

  if (count < strlen (Str))
    {
      if (isupper (Str[count]))
	{
	  return Str[count];
	}
      else
	{
	  count = count + 1;
	  return capitalChaker (Str);
	}
    }
  else
    {
      return 0;

    }
}

Output

Result of the program

Program Explanation

In the above program. the ctype.h header file is included. In this file, many built-in functions have been defined. We have taken an array Str[] of type char to read a string from the user.
We declare and define a function capitalChaker(), which will find the first capital letter in a string using recursion.

Nested if else statement is used to check the value of count variable. If the value of the count variable is less than the string length, then execute the statement. Now another if statement which is used to check the if the character, is in uppercase or not using isupper() function. If the condition is false then executing the else statement, making increment in count variable to check the next letter if it’s in uppercase or not, and then again capitalChaker() function is called until an uppercase letter is found or end of the string. If the condition is true, then return the letter which is in uppercase.

Now the compiler will move back to the main method where the return value is assigned to Letter variable. If else statement is used to check the value of Letter variable equal to 0, if the condition is true, then print “No Capital Letter is Found in String”. Otherwise, else condition statement will execute and write the first capital letter in the entered string.

Related Articles

Last modified: April 29, 2019