Write a C# program named InchesToCentimeters that declares a named constant that holds the number of centimeters in an inch: 2.54. Also declare a variable to represent a measurement in inches, and assign a value. Display the measurement in both inches and centimeters—for example, if inches is set to 3, the output should be: 3 inches is 7.62 centimeters. Note: For final submission, set the number of inches equal to 3.

Respuesta :

Answer:

The C# program for the scenario is given below.

using System;

class InchesToCentimeters

{

   static void Main() {

       // const is used to declare constant variable of any data type

       const double CentimeterInInch = 2.54;

       double inch = 3;

       double centimeter;

       centimeter = inch*CentimeterInInch;

       Console.WriteLine( inch + " inches is " + centimeter + " centimeters." );

   }

}

OUTPUT

3 inches is 7.62 centimeters.

Explanation:

The program is named InchesToCentimeters. As per the question, this program converts inches into centimeters.

The program is not designed to take any user input. All the variables are assigned values inside the program itself. Hence, no validation is implemented.

All the variables are declared as double as per the conversion factor, 2.54, mentioned in the question.

1. As mentioned, a constant double variable is declared and initialized. The variable is declared using keyword, const. This keyword instructs the compiler that the value of variable will not change. Any variable declared with const keyword is also initialized simultaneously.

2. This variable holds the number of centimeters present in one inch.

const double CentimeterInInch = 2.54;

3. Next, a double variable is declared to hold value of inches to be converted.

double inch = 3;

4. Another double variable is declared to hold value of centimeters.

double centimeter;

5. The value assigned to the variable, centimetre, is computed using the previously declared variables.

centimeter = inch*CentimeterInInch;

6. Lastly, the value of inches and the corresponding value of centimeters is displayed on the output.

Console.WriteLine( inch + " inches is " + centimeter + " centimeters." );

7. The function, Console.WriteLine, inserts a new line at the end after the message is displayed.

8. Another function, Console.Write, can also be used to display the message. This function does not inserts a new line at the end after the message is displayed.

C# is a purely object-oriented programming language and hence, all the code is written inside the class.

The program can be tested for positive double values for inches.

ACCESS MORE