Jul 11, 2020

C program to capitalize the given string

Ex: Write a C program to capitalize a given string. How to write a C program to capitalize given string. C program to capitalize given string.


Input from user:

Enter the string: 
tHis IS cOdeForhuNger

Expected output:

String after capitalize: 
This Is Codeforhunger



Quick links:







Step by step logic of the given program:

1. Accept input(string) from user store it in some varible say str.

2. Run loop from 0 to end of string.

3. Check if first character is lowercase alphabet then subtract 32 to make it capital and use continue to continue to the loop:
if(i==0)
{
if(str[i]>='a' && str[i]<='z')
{
str[i]-=32;
}
continue;
}

4. After that check space, if space is found check next character (++i) is lowercase alphabet then subtract 32 to make it capital and continue to the loop:
if(str[i]==' ')
{
++i;

if(str[i]>='a' && str[i]<='z')
{
str[i]-=32;
}
continue;
}

5. After that check, if other characters are uppercase alphabet then add 32 in string to make it small/lowercase:
if(str[i]>='A' && str[i]<='Z')
str[i]+=32;

6. In last outside the block of for loop print capitalized string.




Program:

#include<stdio.h>
#define max 100

int main()
{
char str[max];
int i;

//accept string from user
printf("Enter the string:\n");
scanf("%[^\n]s",&str[i]);

for(i=0;str[i]!='\0';i++)
{
/*check first character is lowercase alphabet*/
if(i==0)
{
if(str[i]>='a' && str[i]<='z')
{
str[i]-=32;/*subtract 32 to make it capital*/
}
continue;/*continue to the loop*/
}
//check space
if(str[i]==' ')
{
/*if space founds increament i*/
++i;
/*means check next character is lowercase*/
if(str[i]>='a' && str[i]<='z')
{
str[i]-=32;/*subtract 32 to make it capital*/
}

//continue to the loop
continue;
}
else
 {
  /*all other uppercase characters should be in lowercase*/
if(str[i]>='A' && str[i]<='Z')
str[i]+=32;/*add 32 to make it lowercase*/
}
}

printf("String after Capitalize: %s",str);

return 0;

}


Above program shows the following output:



Share This:    Facebook Twitter

0 comments:

Post a Comment

If you have any doubts, please discuss here...