Friday, 7 March 2014

How to make Stopwatch in C language

I have make Stopwatch in C language .The program is small ,simple but effective because there are lots of new things you will learn from it .When you run the program ,it will ask you to press any key to start the stop watch and when stop watch is started it will ask you to press any key to stop it .




 SOURCE CODE OUTPUT EXPLANATION DOWNLOAD


#include <stdio.h>
#include <bios.h>
#include <ctype.h>
#include <time.h>
#include <dos.h>
int main(void)
{
   int hh=0,mm=0,ss=0,ms=0;
   clrscr();
   printf("\n\t\t\t    STOP  WATCH");
   printf("\n\n\n\n\t\t\t%2d  : %02d  : %02d  . %d\n\n",hh,mm,ss,ms);
   printf("\npress any key to start the stop watch");
   getch();
   while(!kbhit())
   {
     delay(100);
     ms++;
     if(ms==10)
     ss++,ms=0;
     if(ss==60)
     mm++,ss=0;
     if(mm==60)
     hh++,mm=0;
     clrscr();
     printf("\n\t\t\t    STOP  WATCH");
     printf("\n\n\n\n\t\t\t%d  : %02d  : %02d  . %d\n\n\npress any key to stop",hh,mm,ss,ms);
   }
   getch();
   getch();
   return 0;
}

SCREENSHOTS

Previous                                                                 Next
First off all I will like to tell you don’t get confused with %02d, you can also use simply %d but to understand the difference between them go through the following program and their output  .
void main()
{
int  a=1;
printf(“%d”,a);
}
Output

void main()
{
int  a=1;
printf(“%02d”,a);
}
Output

In both the above program a is equal to 1 but in 2nd program 0 get’s  also printed with 1.If you write printf(“%03d”,a); than two  0 will get printed with 1.
Here a standard library function kbhit() is used .So long as a key is not hit ,kbhit() keeps returning 0.Since !0 is 1 ,the condition in while keeps getting satisfied .Now when you hit a key two stop the stopwatch kbhit() returns a truth value .!truth becomes falsity ,and hence while loop is terminated .
Now inside while loop I have used delay() function it simply suspend the program execution for the time specified by the argument milliseconds i.e. if I write delay(100) then program execution is suspended for 100 milliseconds or program execution is stop for 100 milliseconds .Similarly if I write 1000 then program execution is stop for 1 second. Now for delay of every 100 millisecond ms value is incremented and when its value get’s equal to 10 then its value is set to 0 and ss value is incremented .Similarly when ss value is equal to 60 than mm value is incremented and ss value is set to 0.In this way our stop watch works .I hope you have learn something new from the program.Any questions regarding to program please write in comments.

No comments:

Post a Comment