2

I'm a beginner to programming and Stackoverflow. I'm sorry for my bad formatting and my English. My question is if I can do the thing in the if brackets. Thank you :)

for(int i=0;i<A.size();++i)
{
     if(Alphabet[i]==false)
            cout<<A[i];
     else if(Alphabet[i]==true)
     {
         cout<<endl<<A[i];
     }
  }
1
  • Your title will not help anyone who's having the same problem find this question. Commented Jun 20, 2015 at 19:41

3 Answers 3

2

Yes. You can compare boolean value to a boolean literal. It is, however, easier to simply use the bool value for the if statement. Doing that would look like this

if(!Alphabet[i]) // Originally if(Alphabet[i]==false)

and like this

else if(Alphabet[i]) // Originally else if(Alphabet[i]==true)

You don't even have to test for the second condition. Since it will always execute if the first statement doesn't you can replace it with an else statement. This would change your else if statement to just an else. Like this

else
{
    cout<<endl;
    cout<<A[i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

...and in fact you can remove the second if completely.
1

Assuming Alphabet is an array of bool, you're just testing the value of an element of that array. It's perfectly safe -- and it can be done much more simply than what you've written:

if (Alphabet[i]) {
    std::cout << A[i] << std::endl;
}
else {
    std::cout << A[i];
}

The only values a bool can have are true and false. Explicitly comparing a bool value for equality to true or false is needlessly redundant (and such comparisons can be dangerous in some contexts); just test the value of the value itself. Once you've tested whether it's true, there's no need to test again whether it's false; just use an else clause. If you need to test whether it's false, use the ! (logical "not") operator: if (! Alphabet[i]).

Finally, you're printing the value of A[i] unconditionally, so that part doesn't need to be inside either the if or the else:

std::cout << A[i];
if (Alphabet[i]) {
    std::cout << std::endl;
}

Comments

0

Try to optimize the code as

If(Alphabet[I])

Or

If(!Alphabet[I])

Yes you can compare it the way you did,nothing wrong.

Thanks

1 Comment

C++ is case sensitive

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.