Programming C++  «Prev 

Adding Rest-of-line Comments in C++ – Exercise

Objective: Add rest-of-line comments to as many lines of the following program as necessary to fully document the program's logic.

Background

In modern C++, the preferred comment style is the rest-of-line comment using //. Everything after // on a line is treated as a comment and ignored by the compiler. Well-written comments explain why the code does something, not just what it does. In this exercise, you will practice adding helpful // comments to a short C++ program.

Instructions

  1. Read the entire program first and make sure you understand what it does.
  2. Add rest-of-line comments using // wherever they genuinely help a novice programmer understand the logic.
  3. Focus on explaining intent, units (miles vs. kilometers), and the role of each variable, not just restating the code.
  4. Do not use block comments (/* ... */) for this exercise—use rest-of-line comments only.
  5. When you are finished, paste your commented version of the program into the text area and click Submit.

The program

#include <iostream>

int main()
{
    const int moonMiles = 238857;
    std::cout << "The moon's distance from the Earth is "
              << moonMiles;
    std::cout << " miles." << std::endl;

    int moonKilometers;
    moonKilometers = static_cast<int>(moonMiles * 1.609);
    std::cout << "In kilometers, this is "
              << moonKilometers;
    std::cout << " km." << std::endl;

    return 0;
}

Paste the source code of your commented program below, then click the Submit button when you are ready to submit this exercise.