user3011390
user3011390

Reputation: 1

C++ Loops & Boolean Expressions

I have an assignment for my Intro to Comp Sci course at college. We are told to use only Loops & Boolean Expressions to create the program. Here is a link to the assignment sheet directly:

http://cs.saddleback.edu/michele/Teaching/CS1A/Assignments/AS8%20-%20Boolean%20Expressions.pdf

I got it working with a bunch of If, Then, Else statements until I read the directions again and had to change it.

I got the 'm' 'f' 'M' 'F' part to work, but I can not get the heightOK or the weightOK (directions #2 and #3) to work out.

Please help, thanks!

PS I am brand new to programming...

Here is what I have so far: `

    char gender;
    int weight;
    int height;
    bool heightOK;
    bool weightOK;

cout << "Please enter the candidate’s information (enter ‘X’ to exit).";

cout << "Gender: ";
cin.get(gender);
cin.getline(100 , '\n');

if (gender == 'm' || 'M' || 'f' || 'F')
{

}
else
{
    cout << "***** Invalid gender; please enter M or F *****";
}

cout << "Height: ";
cin >> height;

cout << "Weight: ";
cin >> weight;`

Upvotes: 0

Views: 1076

Answers (2)

user2986089
user2986089

Reputation: 46

You can do this without if statements. You should use do-while loops for each input, such that you loop while the input is invalid. Then, you can set your bool variables like this:

heightOK = ((gender == 'm' || gender == 'M') &&
(height > MALE_TOO_SHORT && height < MALE_TOO_TALL));

heightOK = (heightOK || (/*same as above, female version*/));

You could do that all in one line, but that gets hard to read, IMO. You should be able to set weightOK the same way.

EDIT: The do-while loop asks for and gets the input. Then, the while statement tests the input for validity.

do {
    cout << "enter gender (m/f)";
    cin  >> gender;
} while ( !(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F') );

If you want to tell the user that the input is invalid, you can use a while loop after getting the input the first time.

Upvotes: 1

Kastor
Kastor

Reputation: 617

Here's the expression showing that the ternary operator is a valid Boolean function with respect to

(p ∧ q) ∨ (¬p ∧ r)

"(p and q) or ((not p) and r))" or "if p then q, else r"

See also: http://en.wikipedia.org/wiki/%3F:, http://en.wikipedia.org/wiki/Conditioned_disjunction

Full disclosure, I didn't read the assignment. I just saw the implication in your post that you're restricted from using "if then else" statements and thought I'd offer a creative way to cheat.

Upvotes: 0

Related Questions