Question about Boolean Operatios in C++

I am learning C++ through a book I downloaded, Jumping Into C++ by Alex Allain, and I am currently doing practice problems for a lesson on Boolean operations in C++.

The problems are as follows:

1. Ask the user for two users' ages, and indicate who is older; behave differently if both are over
100.
2. Implement a simple "password" system that takes a password in the form of a number. Make it
so that either of two numbers are valid, but use only one if statement to do the check.
3. Write a small calculator that takes as input one of the four arithmetic operations, the two
arguments to those operations, and then prints out the result
4. Expand the password checking program from earlier in this chapter and make it take multiple
usernames, each with their own password, and ensure that the right username is used for the
right password. Provide the ability to prompt user's again if the first login attempt failed. Think
about how easy (or hard) it is to do this for a lot of usernames and passwords.
5. Think about what kind of language constructs or features would make it easier to add new users
without recompiling the password program. (Note: don't feel like you need to solve these
problems with the C++ you've learned so far, the goal is to think about how you might use tools
we'll pick up in future chapters.)

I've done the first one, but I'm having trouble with the case where both users are over 100 years old.

I'm thinking of using a while loop for the 4th one, but I don't really get how I should make my condition such that it'd do the checks I need.

This is the code I currently have for the first problem's solution program:

#include <iostream>

using namespace std;

int main()
{
int first_age, second_age;

cout << "Provide first person's age: ";
cin >> first_age;
cout << "Provide second person's age: ";
cin >> second_age;

if (first_age > second_age)
{
cout << "First person is older!\n";
}
else if (first_age < second_age)
{
cout << "Second person is older!\n";
}
else if ((first_age > 100) && (second_age > 100))
{
cout << "Both users are too old for this!\n";
}
}
An else statement will only execute if the previous if condition was false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// The first 'if' condition:
if (first_age > second_age)
{ ... }

// The second 'if' condition.  Since this has an 'else', the else ensures that the first if condition
//  was false.  Therefore, without even having an if here, the else means we already know
//  that first_age is not greater than second_age (it is less or equal)
else if (first_age < second_age)
{ ... }

// The third 'if'.  Again, since we have an else, it means the first and second ifs were false.
//  This means that we know that:
//   - first_age is not greater than second_age (ruled out by first if)
//   - first_age is not less than second_age (rule out by second if)
//  Therefore, the only way this if block can run is if first_age == second_age (which is
//   the only way the 1st and 2nd ifs could be false)
else if((first_age > 100) && (second_age > 100))
{
   // Finally, this means that this block of code will only run if both ages are over 100.. AND
   //  if they are both equal.
}
So I should leave the other conditions as if-statements only and maybe leave the check for 100 years old as is? Or do I have to do something to that last one, too?
If you place your boolean check as the first if statement it will work becausse it will check from the top down until a check is true then do what you tell it to do.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
 {
 int first_age, second_age;
 
cout << "Provide first person's age: ";
 cin >> first_age;
 cout << "Provide second person's age: ";
 cin >> second_age;
 
if ((first_age > 100) && (second_age > 100))
 {
 cout << "Both users are too old for this!\n";
 }
 else if (first_age < second_age)
 {
 cout << "Second person is older!\n";
 }
 else if (first_age > second_age)
 {
 cout << "Firsst person is older!\n";
 }
 return 0;
 } 
Thanks.

Now, for the calculator one, how do I take the operations the user would type in? Help me on that as well, please.
For the calculator, this is what I got
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <string>
using namespace std;

int calculator(int operand)
{
	float value_1;
	float value_2;
	cout << "Please input value 1: ";
	cin >> value_1;
	cout << "\nPlease input value 2: ";
	cin >> value_2;
	float result;
	if(operand == 1)
	{
		result = value_1 + value_2;
	}
	else if(operand == 2)
	{
		result = value_1 - value_2;
	}
	else if(operand == 3)
	{
		result = value_1 * value_2;
	}
	else if(operand == 4)
	{
		result = value_1 / value_2;
	}
	return result;
}

void calc_menu()
{
	float answer;
	bool exit;
	while(exit != true)
	{
		cout << "What kind of operation? (+, -, * or /)\n";
		string action;
		cin >> action;
		if(action == "*")
		{
			answer = calculator(3);
			cout << "\nThe result is " << answer;
		}
		else if(action == "/")
		{
			answer = calculator(4);
			cout << "\nThe result is " << answer;
		}
		else if(action == "+")
		{
			answer = calculator(1);
			cout << "\nThe result is " << answer;
		}
		else if(action == "-")
		{
			answer = calculator(2);
			cout << "\nThe result is " << answer;
		}
		cout << endl;
	}
}

int main()
{
	calc_menu();
}
Took me a bit but you need to define exit so you need a
1
2
bool exit =true
while(exit)
also under each operation in the if statements you should but a
1
2
3
4
5
6
7
8
if (choice == 'Y' || choice =='y')
			{
				exit = true;
			}
			else
			{
				exit = false;
			}

with a continue or quit output for the user
and new to programing so havent done much with multiple functions but do you not need a return 0; at the end of the program?
Last edited on
@Sly, fair enough :P. I just quickly got this up to solve the solution really, if they wanted to use it I'm sure they could tune that stuff in easily. You don't HAVE to return 0 in the main function, but you probably should.
Starting from the c99 specification of C, the "return 0;" statement was included in the main function by default which meant there was no longer any need to type it in. But yeah, it's probably good to still type it in. I don't, though.

Also, shouldn't we also include a prompt that tells the user which number, from 1 to 4, corresponds with which operand? If we don't tell them that, they wouldn't know to, for example, press 1 if they need to add. We should ask them to provide a number, 1 to 4, and tell them which number corresponds to which operand, right after taking in the inputs for the two numbers they want to use the operand on.
pet peeve, but...

1
2
3
4
5
6
7
8
if( boolean )
{
    y = true;
}
else
{
    y = false;
}


can be shortened to:

 
y = boolean;


IE:

 
exit = (choice == 'Y' || choice =='y');
Okay, now how about problems 2, 4, and 5? On those, just help me out through hints and and a bit help in figuring out what structure to use and by helping me remember it if it's something I've forgotten how to do.

I also need to do menu programs later and for that, I'm thinking I'll need a switch-case construct. I don't really remember everything about how to do it, so it'd be appreciated if I could also get help with that.

This is the problem: "Write a menu program that lets the user select from a list of options, and if the input is not one
of the options, reprint the list".

The rest of the problems are like this: "Write a program that prints out the entire lyrics to a full rendition of '99 bottles of beer'
Write a program that computes a running sum of inputs from the user, terminating when the
user gives an input value of 0
4. Write a password prompt that gives a user only a certain number of password entry attempts—
so that the user cannot easily write a password cracker.
5. Try writing each practice problem with each kind of loop—notice which loops work well for each
kind of problem.
6. Write a program that displays the first 20 square numbers.
7. Write a program that provides the option of tallying up the results of a poll with 3 possible
values. The first input to the program is the poll question; the next three inputs are the possible
answers. The first answer is indicated by 1, the second by 2, the third by 3. The answers are
tallied until a 0 is entered. The program should then show the results of the poll—try making a
bar graph that shows the results properly scaled to fit on your screen no matter how many
results were entered."

I already did the 6th one, by the way. I'll bring the code here if you guys want me to.
Last edited on
As for number 4 I would check out for loops is what I would attempt unless you need a pop up box then that is way beyond my experience. And for number 5 just test switching out loops in the programs you already wrote
Alright, I'll try writing a for-loop for number 4. I forgot to say so, but I could also use the same kind of help with number 7, as well. Thanks.

Edit: I tried doing it, but I'm getting a weird result; please help me here.

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

using namespace std;

int main()
{
    int password;
    int dragons;

    cout << "Input the password, please: ";
    cin >> password;

    if (password == dragons)
    {
        cout << "Access granted! Welcome.\n";
    }
    for (int i = 0; i < 11; i++)
    {
        if (password != dragons)
        {
            cout << "Access denied! Please try again.\n";
            cin >> password;
        }
    }
}
Last edited on
ints only hold integers. You cannot have a word (like "dragons") in an int.

For that, you'd need a string.

Also:

1
2
3
int dragons;
//...
if (password != dragons)


This creates a variable named dragons (much like how your variable is named "password". It does not mean that variable actually contains the word "dragons". You want to compare the password to the word dragons, and not a variable that happens to be named dragons.

So:

1
2
3
4
5
6
7
8
9
10
#include <string>

// ...

string password;  // <- make the password a string so it can contain text

//...

if(password == "dragons") // <- put dragons in quotes, so you compare to the actual
   // text, and not just to another variable 
Also since you want the user to only be able to input a set number of times you will need the for loop before the cout line. As for 7 not sure about the graph part but the code part I believe you can get it done with a while loop with a for statment using a += to add up and keep a value to display at end.
It seems to work best for me when I have the cout and cin asking for the password before the for loop and the if-condition.

If I want to make a specific condition that checks how many attempts the user has already had and give an error message and shut down the program at ten attempts if he/she still hasn't managed to input the correct password, what do I do for that?

Also, how do I set it up when I want to make it so that it prints out "Access granted! Welcome" when the user enters the correct password after getting it wrong, as well?

This is what I have right now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

int main()
{
    string password;

    cout << "Input the password, please: ";
    cin >> password;

    if (password == "dragons")
    {
        cout << "Access granted! Welcome.\n";
    }
    for (int i = 0; i < 11; i++)
    {
        if (password != "dragons")
        {
            cout << "Access denied! Please try again: ";
            cin >> password;
        }
    }
}


Okay, never mind; I think I have it now:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

int main()
{
    string password;

    cout << "Input the password, please: ";
    cin >> password;

    if (password == "dragons")
    {
        cout << "Access granted! Welcome.\n";
    }
    for (int i = 0; i < 11; i++)
    {
        if (password != "dragons")
        {
            cout << "Access denied! Please try again: ";
            cin >> password;

            do
            {
                if (password == "dragons")
                {
                    cout << "Access granted! Welcome.\n";
                }
            } while (password != "dragons");
        }
    }
}


Edit: Password-checking logic is in another function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>

using namespace std;

int checkPassword(string password);

int main()
{
    string password;

    cout << "Input the password, please: ";
    cin >> password;
    checkPassword(password);
}

int checkPassword(string password)
{
    if (password == "dragons")
    {
        cout << "Access granted! Welcome.\n";
    }
    for (int i = 0; i < 11; i++)
    {
        if (password != "dragons")
        {
            cout << "Access denied! Please try again: ";
            cin >> password;


            if (password == "dragons")
            {
                cout << "Access granted! Welcome.\n";
            }
        }
    }
    return 0;
}
Last edited on
Sorry the for the double-post, but since I don't really remember that well how to make the switch-case construct, I think I should ask about that here first. I get the feeling I should do problem number 7 with a number of switch-case statements, same for the menu problem from one of the earlier practice problems. Thanks in advance, guys.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
cin >> Choice
switch (Choice)
{
case 'string or char':
do this;
break;
case any numerical value:
do this
break;
etc .. 
}

I am pretty sure it is ' x' for char and string if that gives you and error use "x"
Last edited on
Topic archived. No new replies allowed.