C Online Compiler
Example: General Time Calculator (Total Minutes) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// General Time Calculator (Total Minutes) #include <stdio.h> // Function to convert hours and minutes to total minutes int toTotalMinutes(int hours, int minutes) { return hours * 60 + minutes; } // Function to convert total minutes back to hours and minutes void fromTotalMinutes(int totalMinutes, int *hours, int *minutes) { *hours = totalMinutes / 60; *minutes = totalMinutes % 60; } int main() { // Step 1: Declare variables for input and intermediate total minutes int h1, m1, h2, m2; int total_min1, total_min2, result_total_minutes; int result_h, result_m; char operation; // Step 2: Get first time duration printf("Enter first duration (hours minutes): "); scanf("%d %d", &h1, &m1); total_min1 = toTotalMinutes(h1, m1); // Step 3: Get operation (+ or -) printf("Enter operation (+ or -): "); scanf(" %c", &operation); // Note the space before %c to consume newline // Step 4: Get second time duration printf("Enter second duration (hours minutes): "); scanf("%d %d", &h2, &m2); total_min2 = toTotalMinutes(h2, m2); // Step 5: Perform calculation based on operation if (operation == '+') { result_total_minutes = total_min1 + total_min2; printf("Result of addition: "); } else if (operation == '-') { result_total_minutes = total_min1 - total_min2; // Ensure non-negative result for simplicity, or handle negative as duration if (result_total_minutes < 0) { printf("Result is negative (second duration was larger). Absolute difference: "); result_total_minutes = -result_total_minutes; } else { printf("Result of subtraction: "); } } else { printf("Invalid operation.\n"); return 1; // Indicate an error } // Step 6: Convert result back to hours and minutes fromTotalMinutes(result_total_minutes, &result_h, &result_m); // Step 7: Print the final result printf("%d hours %d minutes\n", result_h, result_m); return 0; }
Output
Clear
ADVERTISEMENTS