# Aid in making a clock code more modular

Can someone help in making this clock code more modular so I will be able to use it in other bigger projects for example: turn into a c function. Here is the code:

#include <stdio.h>
#include <time.h>
#include <windows.h>
COORD coord = {0, 0};
void gotoxy (int x, int y)
{
coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void delay(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
void showClock(int x_1, int x_2, int x_3,int y){
long i = 0;
clock_t now = 0;                 int interval = 1;
int elapsed = 0;
int min=0,MIN=0,hrs=0,sec=0;
int d=0,f=0;
now = clock();
for(i = 0L ;  ; i++){
elapsed = (clock()-now)/CLOCKS_PER_SEC;
if(elapsed>=interval){
interval += 1;
if(elapsed%60==0){
min=elapsed/60;
d=60*min;
if(min%60==0){
hrs=min/60;
f=60*hrs;
}
}
sec=elapsed-d;
MIN=min-f;
if(hrs<10){
gotoxy(x_1,y);printf("0%d",hrs);
}else{
gotoxy(x_1,y);printf(":%d",hrs);
}
if(min<10){
gotoxy(x_2,y);printf(":0%d",MIN);
}else{
gotoxy(x_2,y);printf(":%2d",MIN);
}
if(sec<10){
gotoxy(x_3,y);printf(":0%d",sec);
}else{
gotoxy(x_3,y);printf(":%2d",sec);
}
}
}
}
int main()
{
showClock(2,4,7,4);
return 0;
}


You should read the manual pages on time(), which gives you the time in seconds since 1970, library functions such as localtime, strftime and ctime that can be used to present time values and the sleep() function, which sleeps the process for a specified number of seconds.

Also:

• variables and structure fields are normally not all-uppercase (X,Y,MIN)

• put a single definition or expression on each line

• leave a blank line between functions.

• printf has many formatting options. Of relevance here is the "%02d" format string which prints an integer in 2 places, zero-padded if necessary

So for 1, it prints '01' and for 10 it prints '10'.

• I prefer to see a space after while and if etc. and spaces around operators (!=, %, / etc)

• make all functions static where possible (in this program, all except main)

- your function delay is not a good way of delaying, as it ties up the processor. Better use sleep

## Function showClock

• I presume you wanted to call delay, but you didn't. This function loops continually using 100% of CPU time. Better would be to use sleep() which lets other processes run. So sleep(1) would sleep for 1 second.

• using time() would be better than clock(), as you want intervals in seconds

• the single printf format "%02d:%02d:%02d" does what you want without pasing three x-coordinates to the function

• most of the rest is unnecessary if you use sleep and time and the other library functions to present the time interval

• Note that sleep is not ideal for more precise timing, because the thread may sleep longer than your delay. If you want something to happen after a specific amount of time, you usually need OS-specific code (e.g., Waitable Timer Objects in Windows). – Brian Mar 8 '13 at 15:55