C program to capitalize the first and last letter of each word of a string

Capitalizing first and last letter of each word of a string.

In this article we will learn how to code a C program to capitalize the first and last letter of each word of a string i.e. to convert first and last letter of each word into uppercase . We will use toupper() function in the process. The toupper() function is used to convert lowercase alphabet to uppercase.

C program to capitalize first and last letter of each word of a string

Algorithm:

  • Initialize the variables.
  • Accept the input.
  • Calculate the length of input.
  • Initialize a for loop and terminate it at the end of string. 
  • Convert first and last index of the string to uppercase using toupper() function.
  • Check for space and if space found convert the element present at index before space and after space to uppercase using the same function.
  • Print result. 

C programming code to capitalize the first and last letter of each word of a string

Competitive Coding Techniques
#include <stdio.h>
#include <string.h>
 
int main() 
{
 
  //Initializing variables.
  char str[100];
  int length = 0;
 
  //Accepting inputs.
  printf("Enter a string:\n");
  gets(str);
  
  //Calculating length.
  length = strlen(str);
  
  for(int i=0;i<length;i++)
  {
      if(i==0||i==(length-1)) //Conerting character at first and last index to uppercase.
      {
          str[i]=toupper(str[i]);
      }
      else if(str[i]==' ')//Conerting characters present before and after space to uppercase.
      {
          str[i-1]=toupper(str[i-1]);
          str[i+1]=toupper(str[i+1]);
          
      }
  }
  
  //Printing result.
  printf("String after capitalizing first and last letter of each word:\n%s", str);
 
  return 0;
}
Output:
Enter a string:
prep insta
String after capitalizing first and last letter of each word: 
PreP InstA

2 comments on “C program to capitalize the first and last letter of each word of a string”