Write a C++ Program to convert centimeter into meter and kilometer using the user define functions. Program of centimeter into meter and kilometer

Program Overview

The program performs the following tasks:

  1. Pass-by-Value Conversion:
    • Takes the length in centimeters as input.
    • Converts centimeters to meters and kilometers within the function.
    • Displays the converted values inside the function.
    • Original value in main remains unchanged.
  2. Pass-by-Reference Conversion:
    • Takes the length in centimeters as input.
    • Converts centimeters to meters and kilometers within the function.
    • Updates the original variables in main with the converted values.
    • Original variables reflect the changes after the function call.

C++ Program Implementation

Explanation

1. Pass-by-Value (convertByValue Function)

  • Definition:


    • Parameters: The function receives the length in centimeters as a copy of the actual argument.
    • Operation:
      • Converts centimeters to meters by dividing by 100.0.
      • Converts centimeters to kilometers by dividing by 100,000.0.
      • Displays the converted values inside the function.
    • Effect:

Since the function uses pass-by-value, the original cm variable in main remains unchanged after the function call.

Inside main:



  • Displays the value of cm before and after calling convertByValue.

Observes that cm remains the same after the function call.

Pass-by-Reference (convertByReference Function)

  • Definition:
    • Parameters:
      • centimeters: Takes the length in centimeters.
      • meters: Reference to a double variable to store meters.
      • kilometers: Reference to a double variable to store kilometers.
    • Operation:
      • Converts centimeters to meters by dividing by 100.0 and updates meters.
      • Converts centimeters to kilometers by dividing by 100,000.0 and updates kilometers.
      • Displays the converted values inside the function.
    • Effect:
      • Since the function uses pass-by-reference, the original meters and kilometers variables in main are updated with the converted values after the function call.

Inside main:



  • Displays the values of cm, meters, and kilometers before and after calling convertByReference.
  • Observes that meters and kilometers are updated with the converted values after the function call.

Sample Output:

Key Points

  • Pass-by-Value:
    • The function receives a copy of the actual argument.
    • Changes made inside the function do not affect the original variable.
    • Useful when you want to ensure that the original data remains unchanged.
  • Pass-by-Reference:
    • The function receives references (aliases) to the actual arguments.
    • Changes made inside the function directly affect the original variables.
    • Useful when you need the function to modify the original data or when you want to avoid copying large amounts of data.

 

 

All Copyrights Reserved 2025 Reserved by T4Tutorials