Creating a Timer in C++

0
689
Program for Palindrome in C++
C++ inheritance

Creating a timer means creating a digital watch, simply. A Digital watch is the one that counts and shows the time in form of digits, In our daily bases software Programming sometimes we need timers or time calculators, for which we have to create a Digital watch in C or C++ or whatever other language. Now we can do it either through structures or simply by defining our variables in our main() function. Lets have a look at digital watch C++ code:

  1. //Creating Digital Watch in C++
  2. #include<iostream>
  3. #include<Windows.h>
  4. using namespace std;
  5.  
  6. struct time{
  7.  
  8.     int hr,min,sec;
  9. };
  10. int main()
  11. {
  12.     time a;
  13.     a.hr = 0;
  14.     a.min = 0;
  15.     a.sec = 0;
  16.  
  17.     for(int i = 0; i<24; i++)
  18.     {
  19.         if(a.hr == 23)
  20.         {
  21.             a.hr = 0;
  22.         }
  23.  
  24.         for(int j = 0; j<60; j++)
  25.         {
  26.             if(a.min == 59)
  27.             {
  28.                 a.min = 0;
  29.             }
  30.  
  31.             for(int k = 0; k<60; k++)
  32.             {
  33.                 if(a.sec == 59)
  34.                 {
  35.                     a.sec = 0;
  36.                 }
  37.  
  38.                 cout<<a.hr<<” : “<<a.min<<” : “<<a.sec<<endl;
  39.                 a.sec++;
  40.                 Sleep(1000);
  41.                 system(“Cls”);
  42.             }
  43.         a.min++;
  44.  
  45.     }
  46.  
  47.         a.hr++;
  48.     }
  49.  
  50. }

Now in the above code we declared a structure “time”, in which we defined variables for counting hours, minutes and seconds for our digital watch. Now in our main() function we defined a variable of datatype “time” and initialized the three variables for hours, minutes and seconds from 0 as in a digital watch or timer, Then we used three nested “FOR LOOPS” and inside each for loop we used conditional statements for check that if hours are 23 then start it again from 0, Similarly for minutes we limited it to 59, and inside each “for loop” we incremented our hours, minutes and seconds. And here is our digital watch.

Program for Palindrome in C++
C++ inheritance

Leave a Reply