I want to make a function to add ":" to my alarm clock

Viewed 82

I'm making an alarm clock in C and it works fine right now. Only problem is that if I put in the time 12:00:21, it prints it out like a number, so like this 120021. I want to make a function that adds the : between the hours, minutes and seconds but I don't know how I am supposed to do it.

Here is the code

/*
*/

#include <stdio.h>

int update_time(int);
int main()
{
    int current_time;
    int alarm_time;
    
    printf("Enter current time \n"); //enter the time like a number. Ex: if the time is 12:00:21 enter it as 120021
    scanf("%d", &current_time);
    printf("Enter time for alarm \n");
    scanf("%d", &alarm_time);
    
    while(current_time != alarm_time)
    {
        printf("%06d \n", current_time);
        current_time = update_time(current_time);
    }
    
    printf("Alarm!");
}


int update_time(int c_time)
{
    int H, M, S;
    H = c_time/10000;
    M = (c_time/100) %100;
    S = c_time%100;
    S++;
  
    if (S == 60)
    {
        M = M + 1;
        S = 0;
    }
 
    if (M == 60)
    {
        H = H + 1;
        M = 0;
    }

    if (H == 24)
    {
        H = 0;
        M = 0;
        S = 0;
    }

    return H*10000 + M * 100 + S;
}

2 Answers

For example:

int H, M, S;
H = current_time/10000;
M = (current_time/100) %100;
S = current_time%100;
printf("%02d:%02d:%02d\n", H, M, S);

But in general I would advise to use seconds (or milliseconds) as unit of your variable and then do proper calculations for minutes and hours. This will then allow you to know more from the variable itself, for example you will be able to calculate time interval substrating two variables.

There are a couple of ways to achieve this.

  1. You can format a string in the sub-function and return that string.
  2. You can pass H, M, S by reference (I think this is easier).
  3. ... (some other ways I can't imagine now).
int main(...) {
    int H = 0, M = 0, S = 0;
    ...
    update_time(current_time, &H, &M, &S);
    ...
    printf("%02d:%02d:%02d\n", H, M, S);
}
 
void update_time(int c_time, int *H, int *M, int *S)
{
    // int H, M, S; <=== you do not need this line anymore 
    ...
    // do the calculation stuff
    ...
    return;
}
Related