Distance conversion program in C

Here’s an example of a distance conversion program in C that converts kilometers to miles and vice versa:

#include <stdio.h>

float convertKilometersToMiles(float kilometers) {
    return kilometers * 0.621371;
}

float convertMilesToKilometers(float miles) {
    return miles * 1.60934;
}

int main() {
    float distance;
    int choice;

    // Prompt the user to enter the distance
    printf("Enter the distance: ");
    scanf("%f", &distance);

    // Prompt the user to select the conversion type
    printf("Select conversion:\n");
    printf("1. Kilometers to Miles\n");
    printf("2. Miles to Kilometers\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);

    // Perform the conversion based on user choice
    switch(choice) {
        case 1:
            printf("%.2f kilometers is equal to %.2f miles.\n", distance, convertKilometersToMiles(distance));
            break;
        case 2:
            printf("%.2f miles is equal to %.2f kilometers.\n", distance, convertMilesToKilometers(distance));
            break;
        default:
            printf("Invalid choice. Please try again.\n");
            break;
    }

    return 0;
}

To compile and run the program, follow these steps:

  1. Save the code in a file with a .c extension, such as distance_conversion.c.
  2. Open a terminal or command prompt and navigate to the directory where the file is saved.
  3. Compile the program using a C compiler (e.g., GCC) by running the following command: gcc -o distance_conversion distance_conversion.c
    This will create an executable file named distance_conversion.
  4. Run the program by executing the following command: ./distance_conversion

The program prompts the user to enter a distance value and then asks for the conversion type: either kilometers to miles or miles to kilometers. Based on the user’s choice, the program performs the appropriate conversion and displays the converted value on the screen.

Feel free to modify and enhance the program as per your specific requirements.