- 2070 Asar · 6 marks
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 &valueis a reference: it is another name forlength, so no copy is made and the change is visible inmain().- The function is reached by
convert::meterToCm, using the scope resolution operator.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Program using static members · Object Oriented Programming, chapter 4
- Relational operators comparing lengths · Object Oriented Programming, chapter 5
- mdistance and edistance addition via friend · Object Oriented Programming, chapter 4
- Pointers in pass by reference; 2D array · Computer Programming, chapter 9
- Uses of an all-pass filter · Filter Design, chapter 2
- Call by value versus call by reference · Computer Programming, chapter 6 · asked 8×
- CNC lathe part program with G and M codes · Manufacturing and Production Processes, chapter 9