C program that converts miles to kilometers

Certainly! Here’s a simple C program that converts miles to kilometres, along with an explanation of each part of the program:

#include <stdio.h>

int main() {
    // Declare variables
    double miles, kilometers;

    // Ask the user to enter the distance in miles
    printf("Enter the distance in miles: ");
    scanf("%lf", &miles);

    // Convert miles to kilometers using the conversion factor: 1 mile = 1.60934 kilometers
    kilometers = miles * 1.60934;

    // Display the converted distance in kilometers
    printf("The distance in kilometers is: %.2lf kilometers\n", kilometers);

    return 0;
}

Here’s a breakdown of the program:

  1. We include the stdio.h header for input and output functions.
  2. We declare two variables: miles (to store the distance in miles) and kilometers (to store the converted distance in kilometers).
  3. We use printf to ask the user to enter the distance in miles and scanf to read the input and store it in the miles variable.
  4. We convert the distance from miles to kilometers using the conversion factor: 1 mile is equal to approximately 1.60934 kilometers.
  5. Finally, we use printf to display the converted distance in kilometers with two decimal places.

To run this program, follow these steps:

  1. Open a C compiler (like GCC) on your computer.
  2. Copy and paste the program into a new C file (e.g., mile_to_kilometer.c).
  3. Compile the program by running gcc mile_to_kilometer.c -o mile_to_kilometer in the command prompt or terminal.
  4. Run the program by typing ./mile_to_kilometer and providing the distance in miles when prompted.

The program will then calculate and display the distance in kilometers based on the miles input you provide.

Leave a Reply

Your email address will not be published. Required fields are marked *