CP 001
CP 001
A digital clock, as opposed to an analog clock, shows the time digitally (in
numbers or other symbols). In this tutorial, we will develop a digital clock using
C++.
Bjarne Stroustrup developed C++ in 1979 while working at Bell Labs. With its mix
of high and low-level language characteristics, C++ is regarded as a medium
language.
…..PROGRAM…..
#include <iostream>
#include <ctime>
#include <windows.h> // For sleep() function
using namespace std;
int main() {
while (true) {
// Get current time
time_t now = time(0);
tm* localTime = localtime(&now);
// Extract and format hours, minutes, and seconds
int hours = localTime->tm_hour;
string amPm = "AM";
if (hours >= 12) {
hours -= 12;
amPm = "PM";
}
int minutes = localTime->tm_min;
int seconds = localTime->tm_sec;
// Format and display time
cout << hours << ":" << setfill('0') << setw(2) << minutes << ":" << setw(2) << seconds <<
" " << amPm << endl;
// Pause for one second
Sleep(1000); // Windows-specific function for pausing
// For cross-platform compatibility, consider using chrono library features
}
return 0;
}
CODE EXPLANATION:
2. Infinite loop:
The while (true) loop ensures continuous time updates.
5. Display time:
cout prints the formatted time to the console.
if...else: Used for tasks like converting 24-hour time to 12-hour time with
AM/PM.
tm: Structure that holds time components like hours, minutes, seconds,
etc.
• Headers and libraries: iostream for input/output, ctime for time-related functions.
• Variables and data types: int for numbers, string for text, tm structure for time
components.
• Time-related functions: time(0) to get the current time, localtime(&now) to
convert to local time.
• Input/output operations: cout to display text on the console.
• Loops: while(true) for continuous time updates.
• Formatting output: setfill('0') and setw(2) for leading zeros and consistent
formatting.
• Pausing execution: this_thread::sleep_for(chrono::seconds(1)) to pause for one
second.
Additional features often included:
1. GUI elements: For visually appealing clock displays.
2. Customizable appearance: To personalize the clock's look and feel.
3. Alarms and reminders: To schedule tasks or events.
4. Different time zones: To display time in various regions.
Conclusion :
• Building a digital clock in C++ is a valuable exercise for beginners, reinforcing core
programming concepts while creating a practical application.
• Its adaptable nature encourages exploration of advanced features, promoting further
learning and creativity in C++ development.