Introduction
A stopwatch is a useful tool for measuring time intervals. In this tutorial, we will walk you through the process of building a simple stopwatch program using the C programming language. This program will allow users to start, stop, and reset the timer, making it a functional and straightforward stopwatch.
Objective
The objective of this program is to create a simple stopwatch that can be used to track elapsed time. The program will provide basic features like starting the stopwatch, stopping it, and resetting it to zero. Additionally, we will learn how to handle user inputs and work with the system clock to measure time accurately.
Code Implementation
#include
#include
#include
int main() {
int choice;
time_t start, end;
double elapsed;
printf("Simple Stopwatch in C\n");
printf("1. Start Stopwatch\n");
printf("2. Stop Stopwatch\n");
printf("3. Reset Stopwatch\n");
printf("4. Exit\n");
while (1) {
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
start = time(NULL); // Record start time
printf("Stopwatch started. Press 2 to stop.\n");
break;
case 2:
end = time(NULL); // Record end time
elapsed = difftime(end, start); // Calculate elapsed time
printf("Stopwatch stopped. Elapsed time: %.2f seconds.\n", elapsed);
break;
case 3:
printf("Stopwatch reset.\n");
break;
case 4:
printf("Exiting stopwatch program.\n");
exit(0);
break;
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
Explanation of the Program
The program begins by presenting the user with a menu to interact with the stopwatch. The available options are to start the stopwatch, stop it, reset it, or exit the program. The user selects the desired option by entering a number (1-4).
– When the user selects “1” (Start), the program records the current time using the time()
function, which stores the start time in the start
variable.
– When the user selects “2” (Stop), the program records the stop time and calculates the elapsed time using the difftime()
function, then displays the result.
– When the user selects “3” (Reset), the stopwatch simply resets the process, allowing the user to start over.
– The “4” option exits the program and terminates the execution.
The program continues running in a loop until the user chooses to exit (option 4). If an invalid option is entered, the user is prompted to try again.
How to Run the Program
To run this C program on your system, follow these steps:
- Write the code in a C compiler (e.g., Code::Blocks, GCC, or Turbo C).
- Save the file with a .c extension, such as
stopwatch.c
. - Compile the program. If you’re using GCC, you can use the command
gcc stopwatch.c -o stopwatch
. - Run the program using the command
./stopwatch
. - Follow the on-screen instructions to use the stopwatch.