C program to toggle characters of a string
This C program is to toggle characters of a string. That means that if a character is in lowercase then it will be converted(toggled) to uppercase and vice versa.For example, JuSt CoDe will be toggled to jUsT cOdE.
Logic
We just use a simple logic that is we know lowercase letter ‘a’ starts from 97 and uppercase letter ‘A’ starts from 65.So if we want to convert from lowercase to uppercase then we subtract 32(92-65=32) and add 32 to convert a character from uppercase to lowercase.
Dry Run of the Program
Take input string ‘a’. Let us take a[]=cODE
1st iteration for(c=0;a[c]!=’\0′;c++) i.e. for(c=0;a[0]!=’\0′;c++)
if(a[c]>=’A’ && a[c]<=’Z’) i.e. if(a[0]>=’A’ && a[0]<=’Z’) false as a[0]=’c’ ASCII VALUE of ‘c’=99 so we go to else if
else if(a[c]>=’a’ && a[c]<=’z’) i.e. else if(a[0]>=’a’ && a[0]<=’z’) true so execute statement inisde else if
a[c]=a[c]-32; i.e. a[0]=a[0]-32; i.e. a[0]=99-32; a[0]=67 ASCII VALUE OF ‘C’ =67
2nd iteration for(c=1;a[c]!=’\0′;c++) i.e. for(c=1;a[1]!=’\0′;c++)
if(a[c]>=’A’ && a[c]<=’Z’) i.e. if(a[1]>=’A’ && a[1]<=’Z’) true as a[1]=’O’ ASCII VALUE of ‘O’=79 so execute stmts
a[c]=a[c]+32; i.e. a[1]=a[1]+32; i.e. a[1]=79+32; a[1]=111 ASCII VALUE OF ‘o’ =111
3rd iteration for(c=2;a[c]!=’\0′;c++) i.e. for(c=2;a[2]!=’\0′;c++)
if(a[c]>=’A’ && a[c]<=’Z’) i.e. if(a[2]>=’A’ && a[2]<=’Z’) true as a[2]=’D’ ASCII VALUE of ‘D’=68 so execute stmts
a[c]=a[c]+32; i.e. a[2]=a[2]+32; i.e. a[2]=68+32; a[2]=100 ASCII VALUE OF ‘d’ =100
4th iteration for(c=3;a[c]!=’\0′;c++) i.e. for(c=3;a[3]!=’\0′;c++)
if(a[c]>=’A’ && a[c]<=’Z’) i.e. if(a[3]>=’A’ && a[3]<=’Z’) true as a[3]=’E’ ASCII VALUE of ‘E’=69 so execute stmts
a[c]=a[c]+32; i.e. a[3]=a[3]+32; i.e. a[3]=69+32; a[3]=101 ASCII VALUE OF ‘e’ =101
For Loop ends here as the next character is null(‘\0’).
We print the output of the toggled string as Code
Progam
#include<stdio.h> void main() { int c; char a[101]; printf("Enter the string to be toggled\n"); gets(a); for(c=0;a[c]!='\0';c++) { if(a[c]>='A' && a[c]<='Z') { a[c]=a[c]+32; } else if(a[c]>='a' && a[c]<='z') { a[c]=a[c]-32; } } printf("Toggled string is\n"); printf("%s",a); }
Output