> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/1-5-project-project-bmi-body-mass-index-calculator.md).

# 1/5 project:  Project: BMI (Body Mass Index) Calculator

A small, complete console program that pulls together nearly everything from topics 01–15: variables, `const`, arithmetic, type conversion, user input, math functions, conditionals, `switch`, ternary, and logical operators, all in one real program.

**What it does:** asks for weight and height, calculates BMI, then tells you which category you fall into.

Formula: `BMI = weight (kg) / height (m)²`

***

### The full program

```cpp
#include <iostream>
#include <cmath>

int main() {
    const double UNDERWEIGHT_LIMIT = 18.5;
    const double NORMAL_LIMIT = 24.9;
    const double OVERWEIGHT_LIMIT = 29.9;

    double weightKg, heightM;
    char unit;

    std::cout << "Enter units - (M)etric [kg/m] or (I)mperial [lb/in]: ";
    std::cin >> unit;

    if (unit == 'I' || unit == 'i') {
        double weightLb, heightIn;

        std::cout << "Enter weight (lb): ";
        std::cin >> weightLb;

        std::cout << "Enter height (in): ";
        std::cin >> heightIn;

        // convert imperial to metric
        weightKg = weightLb * 0.453592;
        heightM = heightIn * 0.0254;
    }
    else {
        std::cout << "Enter weight (kg): ";
        std::cin >> weightKg;

        std::cout << "Enter height (m): ";
        std::cin >> heightM;
    }

    double bmi = weightKg / pow(heightM, 2);
    bmi = round(bmi * 10) / 10; // round to 1 decimal place

    std::cout << "\nYour BMI is: " << bmi << '\n';

    std::string category;

    if (bmi < UNDERWEIGHT_LIMIT) {
        category = "Underweight";
    }
    else if (bmi <= NORMAL_LIMIT) {
        category = "Normal weight";
    }
    else if (bmi <= OVERWEIGHT_LIMIT) {
        category = "Overweight";
    }
    else {
        category = "Obese";
    }

    std::cout << "Category: " << category << '\n';

    // quick ternary check for a one-line health tip
    std::cout << "Tip: " << ((bmi >= UNDERWEIGHT_LIMIT && bmi <= NORMAL_LIMIT)
                             ? "Keep up the good work!"
                             : "Consider talking to a doctor about diet and exercise.")
              << '\n';

    return 0;
}
```

**Example run:**

```
Enter units - (M)etric [kg/m] or (I)mperial [lb/in]: M
Enter weight (kg): 70
Enter height (m): 1.75

Your BMI is: 22.9
Category: Normal weight
Tip: Keep up the good work!
```

***

### Full Write-Up: The Formula, Then the Whole Program Explained

#### The math formula first

BMI stands for Body Mass Index. The formula is:

```
BMI = weight (kg) / height (m)²
```

So if someone weighs 70 kg and is 1.75 m tall, you square the height first (`1.75 × 1.75 = 3.0625`), then divide the weight by that number (`70 ÷ 3.0625 ≈ 22.9`). That final number is the BMI. It doesn't have a unit attached to it. It's just a ratio doctors use as a rough screening number to sort people into categories like underweight, normal, overweight, and obese. It's not perfect (it doesn't account for muscle vs fat), but it's simple to calculate, which is exactly why it's a good beginner programming exercise.

#### Now the whole program, paragraph by paragraph

```cpp
#include <iostream>
#include <cmath>

int main() {
```

Every C++ program needs `<iostream>` for input/output (`cin`/`cout`), and here we also need `<cmath>` because we're going to use `pow()` and `round()` later. `int main()` is the entry point. Execution starts here, and the opening `{` marks the beginning of everything the program does.

```cpp
    const double UNDERWEIGHT_LIMIT = 18.5;
    const double NORMAL_LIMIT = 24.9;
    const double OVERWEIGHT_LIMIT = 29.9;
```

These three lines set up the boundaries between BMI categories, using `const` because these numbers are fixed medical thresholds that should never change while the program runs. Anyone reading the code later instantly understands what `24.9` means without having to guess.

```cpp
    double weightKg, heightM;
    char unit;

    std::cout << "Enter units - (M)etric [kg/m] or (I)mperial [lb/in]: ";
    std::cin >> unit;
```

Here we declare the variables we'll need. `weightKg` and `heightM` will eventually hold the numbers used in the formula, and `unit` stores a single character telling us which measurement system the user wants to use. We ask the user to type `M` or `I`, and `cin >> unit` reads exactly one character from what they type.

```cpp
    if (unit == 'I' || unit == 'i') {
        double weightLb, heightIn;

        std::cout << "Enter weight (lb): ";
        std::cin >> weightLb;

        std::cout << "Enter height (in): ";
        std::cin >> heightIn;

        weightKg = weightLb * 0.453592;
        heightM = heightIn * 0.0254;
    }
```

This block only runs if the user typed `I` or `i`. The `||` (OR) makes sure both the uppercase and lowercase versions count as a match. If it's true, we grab weight in pounds and height in inches, then convert them into kilograms and meters using standard conversion factors, since the BMI formula only works with metric units. The results get stored back into `weightKg` and `heightM`, the same variables we'll use no matter which path the user took.

```cpp
    else {
        std::cout << "Enter weight (kg): ";
        std::cin >> weightKg;

        std::cout << "Enter height (m): ";
        std::cin >> heightM;
    }
```

If the condition above was false (meaning the user picked metric, or typed something else entirely), this `else` block runs instead, and we just read the weight and height directly since they're already in the right units.

```cpp
    double bmi = weightKg / pow(heightM, 2);
    bmi = round(bmi * 10) / 10;
```

This is the formula itself in code form. `pow(heightM, 2)` squares the height, and dividing `weightKg` by that gives the raw BMI. The second line is a small rounding trick: multiplying by 10, rounding to the nearest whole number, then dividing by 10 again. This keeps exactly one decimal place instead of a long ugly number like `22.857142`.

```cpp
    std::cout << "\nYour BMI is: " << bmi << '\n';

    std::string category;

    if (bmi < UNDERWEIGHT_LIMIT) {
        category = "Underweight";
    }
    else if (bmi <= NORMAL_LIMIT) {
        category = "Normal weight";
    }
    else if (bmi <= OVERWEIGHT_LIMIT) {
        category = "Overweight";
    }
    else {
        category = "Obese";
    }
```

After printing the raw number, this `if / else if` chain checks the BMI against the three thresholds we set at the top, one by one, from lowest to highest. The first condition that matches "wins" and everything below it gets skipped. So if BMI is `22.9`, it fails the first check (not under `18.5`), passes the second (`22.9` is `≤ 24.9`), and stores `"Normal weight"` into `category`, then stops there without checking the remaining conditions.

```cpp
    std::cout << "Category: " << category << '\n';

    std::cout << "Tip: " << ((bmi >= UNDERWEIGHT_LIMIT && bmi <= NORMAL_LIMIT)
                             ? "Keep up the good work!"
                             : "Consider talking to a doctor about diet and exercise.")
              << '\n';

    return 0;
}
```

Finally, we print the category, then use a ternary operator to squeeze a quick health tip into one line, checking with `&&` (AND) whether the BMI falls in the healthy range on both ends, and picking one of two short messages depending on the answer. `return 0;` at the very end tells the operating system the program finished without errors, and the final `}` closes `main()`, matching the opening brace all the way back at the top.

***

### Which topics this project uses (and where)

| Concept                     | Topic | Where it shows up                                      |
| --------------------------- | ----- | ------------------------------------------------------ |
| Variables & data types      | 04    | `double weightKg`, `char unit`, `std::string category` |
| `const`                     | 02    | The three BMI category thresholds                      |
| Arithmetic operators        | 06    | `weightKg / pow(heightM, 2)`, unit conversions         |
| Type conversion             | 07    | Mixing `int`/`double` math implicitly throughout       |
| User input                  | 08    | `std::cin >> unit`, `std::cin >> weightKg`, etc.       |
| Math functions              | 09    | `pow()` for height squared, `round()` for tidy output  |
| Conditionals (`if/else if`) | 11    | Deciding the BMI category                              |
| Logical operators (\`       |       | `,` &&\`)                                              |
| Ternary operator            | 14    | The one-line health tip at the end                     |

This is exactly the kind of program these topics are building toward. None of it is new syntax, just combining tools you already have.

***

### Extending it further (optional practice ideas)

#### 1. Add a `switch`-based menu so the user can run it repeatedly

```cpp
#include <iostream>

int main() {
    char choice;

    do {
        std::cout << "\n--- BMI Calculator ---\n";
        std::cout << "1. Calculate BMI\n";
        std::cout << "2. Exit\n";
        std::cout << "Choose an option: ";
        std::cin >> choice;

        switch (choice) {
            case '1':
                std::cout << "(run the BMI calculation here)\n";
                break;
            case '2':
                std::cout << "Goodbye!\n";
                break;
            default:
                std::cout << "Invalid option\n";
        }

    } while (choice != '2');

    return 0;
}
```

#### 2. Guard against impossible input (0 or negative height/weight)

```cpp
if (heightM <= 0 || weightKg <= 0) {
    std::cout << "Height and weight must be positive numbers!\n";
    return 1;
}
```

#### 3. Use `enum` instead of raw strings for the category (a preview of a later topic)

```cpp
enum BmiCategory { UNDERWEIGHT, NORMAL, OVERWEIGHT, OBESE };
```

This keeps categories as fixed, named options instead of freely-typed strings. It's something the course covers a bit later.

***

### Quick Recap

* This project combines: variables, `const`, arithmetic, type conversion, user input, `<cmath>` functions, `if/else if`, logical operators, and the ternary operator.
* Formula used: `BMI = weight (kg) / height (m)²`
* Good practice extensions: add a repeatable menu with `switch`, validate input, or explore `enum` for fixed categories.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/1-5-project-project-bmi-body-mass-index-calculator.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
