C Online Compiler
Example: Temperature Converter & Water State Identifier in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Temperature Converter & Water State Identifier #include <stdio.h> // Function to convert Celsius to Fahrenheit float celsiusToFahrenheit(float celsius) { return (celsius * 9 / 5) + 32; } // Function to convert Fahrenheit to Celsius float fahrenheitToCelsius(float fahrenheit) { return (fahrenheit - 32) * 5 / 9; } // Function to convert Celsius to Kelvin float celsiusToKelvin(float celsius) { return celsius + 273.15; } // Function to convert Kelvin to Celsius float kelvinToCelsius(float kelvin) { return kelvin - 273.15; } // Function to determine the state of water void determineWaterState(float tempCelsius) { if (tempCelsius <= 0) { printf("At %.2f Celsius, water is in a Solid (Ice) state.\n", tempCelsius); } else if (tempCelsius < 100) { printf("At %.2f Celsius, water is in a Liquid state.\n", tempCelsius); } else { printf("At %.2f Celsius, water is in a Gaseous (Steam) state.\n", tempCelsius); } } int main() { float temperature; char scale_char; // 'C' for Celsius, 'F' for Fahrenheit, 'K' for Kelvin int choice; // Step 1: Get user input for temperature and initial scale printf("Enter temperature value: "); scanf("%f", &temperature); printf("Enter original scale (C for Celsius, F for Fahrenheit, K for Kelvin): "); scanf(" %c", &scale_char); // Note the space before %c to consume newline float tempCelsius; // Store temperature in Celsius for consistent internal calculations // Step 2: Convert input to Celsius for standardized processing switch (scale_char) { case 'C': case 'c': tempCelsius = temperature; break; case 'F': case 'f': tempCelsius = fahrenheitToCelsius(temperature); break; case 'K': case 'k': tempCelsius = kelvinToCelsius(temperature); break; default: printf("Invalid scale entered. Exiting.\n"); return 1; // Indicate an error } // Step 3: Provide options to the user printf("\nChoose an option:\n"); printf("1. Convert to all scales\n"); printf("2. Determine state of water\n"); printf("3. Both (Convert and Determine state)\n"); printf("Enter your choice: "); scanf("%d", &choice); // Step 4: Execute chosen option if (choice == 1 || choice == 3) { printf("\n--- Conversions ---\n"); printf("Original: %.2f %c\n", temperature, scale_char); printf("Celsius: %.2f C\n", tempCelsius); printf("Fahrenheit: %.2f F\n", celsiusToFahrenheit(tempCelsius)); printf("Kelvin: %.2f K\n", celsiusToKelvin(tempCelsius)); } if (choice == 2 || choice == 3) { printf("\n--- Water State ---\n"); determineWaterState(tempCelsius); } // Note: For other substances, you would define their specific freezing/boiling points // and create a similar function to 'determineWaterState'. // E.g., for Ethanol: Freezing point ~ -114.1°C, Boiling point ~ 78.37°C return 0; }
Output
Clear
ADVERTISEMENTS