Program to determine when the hands of a clock align

Determine the times of the day when the hands of the clock align and only the minutes hand is visible.

Last Reviewed and Updated on May 17, 2017
Posted by Parveen(Hoven),
Aptitude Trainer and Software Developer

Advertisement

Program to determine when the hands of a clock meet and align.

Write a program to determine all times of a day when the hands of a clock meet, i.e., are perfectly aligned at an angle of zero degrees.

Step 1: First create a function that takes hours and minutes, and tells a true or false value whether the hands meet at that moment of time.

bool areAligned(int h, float m)
{
    // first calculate angle for hours clock 
    // The angle is measured in degrees 
    // from the mark of number 12 clockwise.
 
    // so far how many minutes have elapsed?
    float totalMinutes = 60 * h + m;
 
    // hours clock travels (360 / 12 ) / 60 =
    // 0.5 degrees in one minute. so total degrees?
    float angleHours = totalMinutes * 0.5f;
 
    // next take the minutes hand
    // it travels 360 degrees in 60 minutes
    // so in one minute it travels = 
    // 360 / 60 = 6 degrees. total angle?
    float angleMinutes = m * 6.0f;
 
    // the difference 
    float angle = angleMinutes - angleHours;
 
    // if it is negative, make absolute
    if(angle < 0)
    {
        angle *= -1;
    }
 
    return angle < 0.1f;
 

}
 

Step 2: Call the above function from your main. We will have to loop for all the moments of the day and check each point.

int main()
{
    for(int h = 0; h < 12; h++)
    {
        for(int m = 0; m < 59; m++)
        {
            // check for each fractional second
            // at this minute
            for(int inc = 0; inc < 100; inc++)
            {
                float minute = m + (float)(inc/100.0);

                if(areAligned(h, minute))
                {
                    cout << "Aligned at: " << h;

                    cout << ":" << minute;

                    cout << endl;

                    break;
                }
            }
        }
    }
    return 0;
}

My C/C++ Videos on Youtube

Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.



Creative Commons License
This Blog Post/Article "Program to determine when the hands of a clock align" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2017-05-17.


Advertisement