Hi below is the program for implementing toggle case. I have a doubt in this one. | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Hi below is the program for implementing toggle case. I have a doubt in this one.

//The program is working fine. Except i have a doubt. In the toggle case function, i tried doing it using multiple if statements rather than if and else if statement and it didnt work. can someone explain why? #include<iostream> using namespace std; void togglecase(char a[]) { for(int i =0;a[i]!='\0';i++) { if (a[i]>=65&&a[i]<=90) { a[i]= a[i]+32; } else if(a[i]>=97&& a[i]<=122) // tried writing if(a[i]>=97.....) and it didn't work. { a[i]=a[i]-32; } } for(int i =0;a[i]!='\0';i++) { cout<<a[i]; } } int main(void) { char a[100]; cout<<"Enter the string"<<endl;cin.getline(a,100); togglecase(a); return 0; }

2nd Dec 2017, 3:02 PM
RR2001
RR2001 - avatar
2 ответов
+ 3
You need to use else if, otherwise your program won't work. Consider a simple input Hello. The program was supposed to return hELLO, but when you use if's instead of if...else if, the program returns HELLO. This is because the first if converts your H to h, but then the second if becomes true, and then, it will revert your h to H. Thus, the change never occurs, and the output fails. The change however will revert only for variables which have the first if as true, ie Capital Letters. So you need an if...else if, which runs particular code only once for a particular character, and ignores the other cases.
2nd Dec 2017, 3:18 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 2
You probably want to implement nested if-else statements https://www.programiz.com/cpp-programming/if-else
2nd Dec 2017, 3:14 PM
Cristian Stollberg
Cristian Stollberg - avatar