HomeAbout UsContact Us

Angle between hour and minute hands of analogue clock using C

By embeddedSoft
Published in Embedded C/C++
September 22, 2022
1 min read
Angle between hour and minute hands of analogue clock using C

Table Of Contents

01
Calculation theory
02
Code
03
Code walk-through

This is a very interesting clock angle problem where the C program described in this article calculates the angle between the hour-hand and the minute-hand of an analog clock. In this example program if the user enters the hour and minute, then it should output the angle between the hour-hand and the minute-hand.

Example:

Input: hour = 10 and minute = 10

Output: 115 degree

Calculation theory

The hour hand of a 12-hour analog clock turns 360° in (12 x 60) minutes; in other words 0.5° per minute. Similarly, the minute hand would take 60 minutes to turn a complete 360° (which is 6° per minute). The angle between the hour hand and minute hand is obtained by the difference between these angles.

Code

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
unsigned int hour;
unsigned int minute;
float hAngle;
float mAngle;
float angle;
printf("Enter hour (12h format): ");
scanf("%u", &hour);
printf("Enter minute: ");
scanf("%u", &minute);
if (hour > 12u || minute > 60u)
{
printf("Invalid input!\n");
}
else
{
if (hour == 12u)
{
hour = 0;
}
if (minute == 60u)
{
minute = 0;
hour += 1u;
}
hAngle = 0.5f * ((hour * 60.0f) + minute); // Hour hand angle with respect to 12:00
mAngle = 6.0f * (float)minute; // Minute hand angle with respect to 12:00
angle = fabsf(hAngle - mAngle);
if (angle > (360.0f - angle))
{
angle = 360.0f - angle; // Getting the smaller angle value
}
printf("Angle between hour hand and minute hand is %.1f\n", angle);
}
return 0;
}

Code walk-through

The code is simple and self explanatory. Angle between the hour hand and the minute hand is calculated at the below lines,

hAngle = 0.5f * ((hour * 60.0f) + minute); // Hour hand angle with respect to 12:00
mAngle = 6.0f * (float)minute; // Minute hand angle with respect to 12:00

fabsf() library function (from <math.h>) is used to get the absolute float value of the angle difference in angle = fabsf(hAngle - mAngle);

The below code section selects the smaller angle value from the two possible angle values,

if (angle > (360.0f - angle))
{
angle = 360.0f - angle; // Getting the smaller angle value
}

Tags

#c#embedded#clock-angle-problem

Share


Previous Article
Reverse order of words in a string using C language
embeddedSoft

embeddedSoft

Embedded Systems Articles by Jithin Tom & Hermes (AI Agent)

Related Posts

Implementation of Singly Linked List in C
Implementation of Singly Linked List in C
September 22, 2022
2 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media