Write a program to check whether the given time is valid or not.
Valid Time Ranges: ┌─────────────┬─────────────┬─────────────┐ │ Hours │ Minutes │ Seconds │ │ 0 - 23 │ 0 - 59 │ 0 - 59 │ └─────────────┴─────────────┴─────────────┘ Example: 11:45:45 ↓ ↓ ↓ 11 45 45 ✓ ✓ ✓ (0≤11≤23)(0≤45≤59)(0≤45≤59) Result: Valid ✓ Example: 08:60:60 ↓ ↓ ↓ 8 60 60 ✓ ✗ ✗ (0≤8≤23)(60>59)(60>59) Result: Not Valid ✗
Accept three integer as a input as colon(:) separated.
Print the time is "Valid" or "Not Valid"
0 <= INPUT <= 10^15
#include <iostream> using namespace std; int main() { int hours, minutes, seconds; char colon1, colon2; cin >> hours >> colon1 >> minutes >> colon2 >> seconds; // Check if all components are within valid ranges if (hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59 && seconds >= 0 && seconds <= 59) { cout << "Valid" << endl; } else { cout << "Not Valid" << endl; } return 0; }
How does cin
handle "08:60:60"?
// Input: 08:60:60 cin >> hours >> colon1 >> minutes >> colon2 >> seconds; ↓ ↓ ↓ ↓ ↓ 08 : 60 : 60 // Variables after reading: hours = 8 // Leading zero ignored colon1 = ':' // Character variable stores ':' minutes = 60 colon2 = ':' seconds = 60
Why use char
for colons?
':'
is a separator, not a numberchar
variables "consumes" the colons from inputcin
to correctly parse the numbers12-Hour Format | 24-Hour Format | Description |
---|---|---|
12:00 AM | 00:00 | Midnight |
1:00 AM | 01:00 | Early morning |
12:00 PM | 12:00 | Noon |
1:00 PM | 13:00 | Afternoon |
11:59 PM | 23:59 | Last minute of day |
Key Differences:
// The compound condition checks ALL three components: if (hours >= 0 && hours <= 23 && // Hours must be 0-23 minutes >= 0 && minutes <= 59 && // Minutes must be 0-59 seconds >= 0 && seconds <= 59) // Seconds must be 0-59 // This is equivalent to: bool validHours = (hours >= 0 && hours <= 23); bool validMinutes = (minutes >= 0 && minutes <= 59); bool validSeconds = (seconds >= 0 && seconds <= 59); if (validHours && validMinutes && validSeconds) { // All components are valid } // The && operator requires ALL conditions to be true // If even ONE is false, the entire expression is false
1. Using 1-24 instead of 0-23 for hours:
// ❌ WRONG: Hours from 1-24 if (hours >= 1 && hours <= 24) // ✅ CORRECT: Hours from 0-23 if (hours >= 0 && hours <= 23)
2. Using OR (||) instead of AND (&&):
// ❌ WRONG: This would accept if ANY component is valid if (validHours || validMinutes || validSeconds) // ✅ CORRECT: ALL components must be valid if (validHours && validMinutes && validSeconds)
3. Forgetting the lower bound (≥ 0):
// ❌ INCOMPLETE: Doesn't check for negative values if (hours <= 23 && minutes <= 59 && seconds <= 59) // ✅ COMPLETE: Checks both lower and upper bounds if (hours >= 0 && hours <= 23 && ...)