Lesson 5 of 20Getting Started20 min

Decision Making with if and switch

Decision statements let a program choose what to do. Use if when conditions may involve ranges or several tests, and use switch for a clear set of fixed choices.

Using if, else if, and else

Grade checker
#include <iostream>
using namespace std;

int main()
{
    int mark;
    cout << "Enter your mark: ";
    cin >> mark;

    if (mark >= 80)
        cout << "Grade A" << endl;
    else if (mark >= 65)
        cout << "Grade B" << endl;
    else if (mark >= 50)
        cout << "Grade C" << endl;
    else
        cout << "Fail" << endl;

    return 0;
}

Using switch

Menu choice
#include <iostream>
using namespace std;

int main()
{
    int choice;
    cout << "1. Add record
2. View records
3. Exit
";
    cout << "Choose an option: ";
    cin >> choice;

    switch (choice)
    {
        case 1:
            cout << "Add record selected.";
            break;
        case 2:
            cout << "View records selected.";
            break;
        case 3:
            cout << "Goodbye.";
            break;
        default:
            cout << "Invalid choice.";
    }

    return 0;
}
Practice task

Create a simple ticket-price program that gives a child, adult, or senior price based on age.

Lesson Summary

Control program behaviour with conditions and menu-style choices.