I have been trying to write a simple program to switch cases of given character in c++. Even though the program doesn’t show any errors i am not getting the desired output.
Please checkout the below given program.
#include<iostream>
using namespace std;
int main()
{
char ch;
cout<<"Enter the character";
cin >>ch;
while(ch!=0)
{
if(ch>=65||ch<=90)
{
ch+=32;
}
else if(ch>=97||ch<=122)
{
ch-=32;
}
}
cout<<ch;
}
Hi,
First of all their are logical mistakes in your program. The while loop is always true, its an infinite loop. Secondly their is a bug in both the if condition. All the characters you enter will only end up in the first if condition. Make following marked changes to code and update us,
#include<iostream>
using namespace std;
int main() {
char ch;
cout<<"Enter the character";
cin >>ch;
while(ch!=0) // <----- Condition always true
{
if(ch>=65||ch<=90) //<-----Bug: All character end up in this condition. Logic error
{
ch+=32;
}
else if(ch>=97||ch<=122) //<----- Logic error
{
ch-=32;
}
}
cout<<ch;
}
1 Like
Thanks for the help.
I have made the necessary change as per your suggestion and it worked!!!
The corrected code is given below.
#include<iostream>
using namespace std;
int main()
{
char ch;
cout<<"Enter the character"<<"\n";
cin >>ch;
while(ch>0)
{
if(ch>=65 && ch<=90)
{
ch+=32;
cout<<ch;
cout<<endl;
}
else if(ch>=97 && ch<=122)
{
ch-=32;
cout<<ch;
cout<<endl;
}
ch=0;
}
}