Skip to main content

Namespace with pass by reference program

Short answer

The program defines namespace convert containing meterToCm(float &value) which multiplies value by 100, modifying the caller's variable via reference. In main(), input meters, call convert::meterToCm(length), output centimeters. E.g., 2.5 m becomes 250 cm.

Write a program that uses pass by reference to change meter to centimeter using pass by reference along with the namespace.

The namespace convert contains the function meterToCm(). It receives the value by reference and changes the original variable from meters to centimeters (1 m = 100 cm).

#include <iostream>
using namespace std;

namespace convert {
    void meterToCm(float &value) {   // pass by reference
        value = value * 100;         // original variable is modified
    }
}

int main() {
    float length;
    cout << "Enter length in meters: ";
    cin >> length;
    convert::meterToCm(length);      // access using namespace name
    cout << "Length in centimeters = " << length << endl;
    return 0;
}

Sample run

Enter length in meters: 2.5
Length in centimeters = 250

Explanation:

  • float &value is a reference: it is another name for length, so no copy is made and the change is visible in main().
  • The function is reached by convert::meterToCm, using the scope resolution operator.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 2 questions →