• Register
100 points
5 1

In order to code the program, we have to understand question properly.Here, question wants that we have to capitalize the each word’s first letter in a given string or entered string.Example:”all the best” is converted into “All The Best” after the execution of code.

Algorithm

  • First get the string which entered by user.
  • Iterate overall string using for loop
  • Take first letter of the string i.e i=0 and convert it into captical form by substracting with 32.
  • Then check the spaces and increment i so that it would point first letter after space of word.
  • Apply same conditions just like you did for first letter of a string
  • Lastly,check if any letter in captial form then convert it into lower case by adding 32.(Optional not required as such)

 

Code

#include <stdio.h>
int main()
{
	char str[100];	
	int i;
	
	
	printf("Enter a string: ");
	scanf("%[^\n]s",str); //kind of regular expression .It takes input until new line
	
	for(i=0; str[i]!='\0'; i++)
	{
		
		if(i==0)//check first character is lowercase alphabet
		{
			if((str[i]>='a' && str[i]<='z'))
				str[i]=str[i]-32; //subtract 32 to make it capital(Please go through ASCII table you will get to know why 32)
			continue; //a->97and A->65 so 97-32=65(capital A)
		}
		if(str[i]==' ')//check space
		{
			
			++i;//increment i which points first letter after the space.
			
			if(str[i]>='a' && str[i]<='z')
			{
				str[i]=str[i]-32; 
				continue; 
			}
		}
		else
		{
			
			if(str[i]>='A' && str[i]<='Z')//optional no required as such
				str[i]=str[i]+32; 
		}
	}
	
	printf("First word capitalize string: %s\n",str);
	
	return 0;
}