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:
- We include the
stdio.h
header for input and output functions. - We declare two variables:
miles
(to store the distance in miles) andkilometers
(to store the converted distance in kilometers). - We use
printf
to ask the user to enter the distance in miles andscanf
to read the input and store it in themiles
variable. - We convert the distance from miles to kilometers using the conversion factor: 1 mile is equal to approximately 1.60934 kilometers.
- Finally, we use
printf
to display the converted distance in kilometers with two decimal places.
To run this program, follow these steps:
- Open a C compiler (like GCC) on your computer.
- Copy and paste the program into a new C file (e.g.,
mile_to_kilometer.c
). - Compile the program by running
gcc mile_to_kilometer.c -o mile_to_kilometer
in the command prompt or terminal. - 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.