The If statement can be used to change the value of a string, which in turn can affect the output that the user sees. In this program, you will set your favorite letter to ‘m’. You will also set a string to initially store the word “was”.
Ask the user to guess your letter. If it is guessed incorrectly, modify the string to store the words “was not”. If guessed correctly, don’t change the string.
Output 1:
Guess my favorite lowercase letter: [assume user types: m]
My favorite letter was guessed
Output 2:
Guess my favorite lowercase letter: [assume user types: a]
My favorite letter was not guessed
Hints and Notes:
1) Do NOT use an ELSE for this question. You only need one IF statement and one output statement for the was / was not guessed part.
2) As you probably noticed, the only words that change in the output are “was” and “was not”. The rest of the output is always the same.
#include <iostream>
using namespace std;
int main(){
//initializing favorite letter as m
string letter="m";
//initializing word as was
string word="was";
//initializing guess
string guess;
//asking to Guess favorite letter
cout<<"Guess my favorite lowercase letter: ";
//acccepting guess
cin>>guess;
//checking if guess is not "m"
if(guess!=letter)
//changing word to "was not"
word="was not";
//printing the output
cout<<"My favorite letter "<<word<<" guessed"<<endl;
return 0;
}
Comments
Leave a comment