0

Can anyone help me break this down and tell.me what the output is for some reason it wont compile.its a question for study guide

bool contains(string s, char c) // This code is suspect { for (int k = s.size()-1; k >= 0; k--) { if (s[k] == c) return true; else return false; } } int main() { if (contains("xyz", 'x')) cout << "x" << endl; else cout << "no x" << endl; if (contains("xyz", 'y')) cout << "y" << endl; else cout << "no y" << endl;; }

8th Nov 2020, 3:01 PM
boba
boba - avatar
4 Réponses
+ 4
You have a function contains() which takes a string and a character as parameters. It is used to check whether the character passed is present in the string or not. If present it returns true and if not it returns false. This will not work as desired because of the else clause. You must say return false outside the for loop.
8th Nov 2020, 3:16 PM
Avinesh
Avinesh - avatar
0
C++ btw
8th Nov 2020, 3:01 PM
boba
boba - avatar
0
Maybe this is what you are looking for? bool contains(string s, char c) // This code is suspect { for (int k = s.size()-1; k >= 0; k--) { if (s[k] == c) return true; else continue; } return false; }
8th Nov 2020, 3:15 PM
Abhay
Abhay - avatar
0
i will just add on what you have been told it will be good i you declare a bool variable inside the for method then instead of returning values in the loop you assign your the values to the variable then outside the loop you return the variable in other words bool contains(string s, char c) // This code is suspect { bool result =false; for (int k = s.size()-1; k >= 0; k--) { if (s[k] == c) result true; } return result; }
8th Nov 2020, 4:23 PM
Sacalivin Obiri
Sacalivin Obiri - avatar