Fix the Program

Fix the program

This program asks for the users age and if he has parents with him to determine access to a movie.

However, it isn't compiling.

Identify the problem and fix the program.

#include <iostream>

int main()
{
    std::cout << "What is your age?\n";

    int age;
    std::cin >> age;

    if (age < 15) {
        bool isParentPresent;
        std::cout << "Is your parent present?\n1 = yes, 0 = no\n";
        std::cin >> isParentPresent;
	}

    if (age >= 15 || isParentPresent) {
        std::cout << "You can watch the movie!\n";
    } else {
        std::cout << "Sorry, you can't watch the movie.\n";
    }
}

Hint

A variable declared inside the if statement's scope can't be reached from outside.

Answer

#include <iostream>

int main()
{
    std::cout << "What is your age?\n";

    int age;
    std::cin >> age;

    bool isParentPresent = false;
    if (age < 15)
    {
        std::cout << "Is your parent present?\n1 = yes, 0 = no\n";
        std::cin >> isParentPresent;
    }

    if (age >= 15 || isParentPresent)
    {
        std::cout << "You can watch the movie!\n";
    }
    else
    {
        std::cout << "Sorry, you can't watch the movie.\n";
    }
}

The variable isParentPresent isn't accessible outside of the scope of the if statement if (age < 15). By moving it out we make it avaliable for later use. We also assign a value to it so that we know what value it holds.

The output for this program won't change even if we don't have control over what isParentPresent holds. We still assign it a value because of best practices.

Questions