Ex: Write a C program to toggle case of each character of a string. How to write a C program to toggle case of each character of a string. C program to toggle case of each character of a string.
Input from user:
Enter the string:
welcome To Codeforhunger.Com
Expected output:
Toggled string:
WELCOME tO cODEFORHUNGER.cOM
1. Accept string from user declare varible say str.
2. After that calculate length of string using strlen() function and store it in variable say len.
3. Run for loop from 0 to length-1 of string, as follows:
for(i=0;i<len;i++)
4. Inside the body of loop check condition if character is lowercase alphabet then subtract 32 to make it capital and character is Capital alphabet then add 32 to make it small(lowercase), as follows:
if(str[i]>='a'&&str[i]<='z')
{
str[i]-=32;
}
else if(str[i]>='A'&&str[i]<='Z')
{
str[i]+=32;
}
5. Last outside the block of for loop print toggled string.
Input from user:
Enter the string:
welcome To Codeforhunger.Com
Expected output:
Toggled string:
WELCOME tO cODEFORHUNGER.cOM
Step by step logic of the given program:
1. Accept string from user declare varible say str.
2. After that calculate length of string using strlen() function and store it in variable say len.
3. Run for loop from 0 to length-1 of string, as follows:
for(i=0;i<len;i++)
4. Inside the body of loop check condition if character is lowercase alphabet then subtract 32 to make it capital and character is Capital alphabet then add 32 to make it small(lowercase), as follows:
if(str[i]>='a'&&str[i]<='z')
{
str[i]-=32;
}
else if(str[i]>='A'&&str[i]<='Z')
{
str[i]+=32;
}
5. Last outside the block of for loop print toggled string.
Program to toggle case of each character of a string:
#include<stdio.h>
#include<string.h>
void main()
{
char str[100];
int i,len;
printf("Enter the string:\n");
gets(str);
len=strlen(str);//calculate length of string
for(i=0;i<len;i++)
{
if(str[i]>='a'&&str[i]<='z')
{
str[i]-=32;//subtract 32 to make it capital
}
else if(str[i]>='A'&&str[i]<='Z')
{
str[i]+=32;//add 32 to make it small
}
}
printf("Toggled string:\n%s",str);
}
Above program shows the following output: