C++ | Timer

Hello peeps! Lord Hypersonic greets you. Today I am presenting you a timer in c++. Just like any other timer, you have to set hours, minutes and seconds and it will start the timer.

Algorithm

The algorithm is very simple. We need 3 integer type variables for hours, minutes and seconds. 
1. Start an infinite loop.
2. Under infinite loop, check the values of three integer variables.
    2.1. If the value of all variables if zero then break the loop.
    2.2. If the value of seconds and minutes is zero then make the value of minutes equal to 60 and reduce the value of hours by 1.
    2.3. If the value of seconds is only zero then make seconds equal to 60 and reduce the value of minutes by 1.
3. Now clear the screen.
4. Reduce the values of seconds by one.
5. Print the values of hours minutes and seconds like real time.
6. Pause the program for one second and continue with the loop.

Let's understand it with an example.

Let's say, you want to set the timer for 5 minutes.
Then enter 0 at hours, 5 at minutes and 0 at seconds to set the timer for 5 minutes.

So the value of seconds is zero therefore, it will reduce the value of minutes by one and change the value of seconds to 60. It looks like this:    0:4:59

After each iteration, it will reduce the value of seconds by 1. So, when seconds again become 0, it will reduce the value of minutes by 1 and change the value of seconds to 60. 
Following this, when the value of minutes become zero and the value of seconds also become zero and the value of hours was already zero, hence it will quit the timer. You can add any message like "Time Completed" after the timer is completed or you can add any sound like I have added 😜.

Source Code

/*
Program: Timer
Description: Sets timer according to the time provided by the user.
Author: Lord Hypersonic
Email: lordhypersonic.522@gmail.com
Website: www.lordhypersonic.blogspot.com
*/
#include <iostream>
#include <stdlib.h> //for system()
#include <windows.h> //for Sleep() and Beep()

using namespace std;

//timer function
void timer(int h, int m, int s)
{
    for(;;)
    {
        if (h == 0 && m == 0 && s == 0)
        {
            break;
        }
        if (s == 0 && m ==0)
        {
            m = 60;
            h--;
        }
        if (s == 0)
        {
            s = 60;
            m--;
        }
        system("cls");
        cout<<h<<":"<<m<<":"<<s--;
        Sleep(1000);
    }
}

int main()
{
    int h, m, s;
    cout<<"Hours: "; cin>>h;
    cout<<"Minutes: "; cin>>m;
    cout<<"Seconds: "; cin>>s;
    timer(h,m,s);
    for (int i = 100; ; i = i + 50)
        Beep(i,1000);
}


1 comment:

Powered by Blogger.