IN C PROGRAMMING REWRITE THE CODE USING A POINTER *pClock INSTEAD OF CLOCK clock
ID: 3874501 • Letter: I
Question
IN C PROGRAMMING
REWRITE THE CODE USING A POINTER *pClock INSTEAD OF CLOCK clock = {14, 38, 56}
#include<stdio.h>
typedef struct(
int hr, min, sec;
) CLOCK;
void increment (CLOCK *pClock);
void show (CLOCK *pClock);
int main (void) {
int i = 0;
CLOCK clock = {14, 38, 56};
for(i = 0; i < 6; ++1) {
increment (&clock);
show (&clock);
}
return 0;
}
#include<stdio.h>
typedef struct(
int hr, min, sec;
) CLOCK;
void increment (CLOCK *pClock);
void show (CLOCK *pClock);
int main (void) {
int i = 0;
CLOCK clock = {14, 38, 56};
for(i = 0; i < 6; ++1) {
increment (&clock);
show (&clock);
}
return 0;
}
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
typedef struct {
int hr, min, sec;
}CLOCK;
void increment (CLOCK *pClock);
void show (CLOCK *pClock);
int main(void) {
int i = 0;
// CLOCK clock = {14, 38, 56};
CLOCK *pClock = calloc(1, sizeof(CLOCK)); /* Allocate memory to the structure clock. */
if(pClock == NULL) return 0; /*If memory allocation failed, return from execution. */
/* Initialize the hour, min and second */
pClock->hr = 14;
pClock->min = 38;
pClock->sec = 56;
for(i=0; i<6; ++i) {
increment(pClock);
show(pClock);
}
return 0;
}
void increment (CLOCK *pClock)
{
/*In increment function, you have not mentioned whether to increment hour or minutes or secods. I am incrementing seconds. Change the code if you need any other params to be incremented. */
pClock->sec +=1;
if(pClock->sec >= 60)
{ /* If the seconds crossed past 60, increment the minutes and make seconds back to zero. */
pClock->sec -=60; /* pClock->sec = pClock->sec - 60 ; */
pClock->min +=1; /* pClock->min = pClock->min + 1 ; */
}
if(pClock->min >= 60)
{ /* If the minutes crossed past 60, increment the hours and make minutes back to zero. */
pClock->min -=60;
pClock->hr +=1;
}
if(pClock->hr >=24)
{ /*If hours crossed past 24, then make hrs back to zero. */
pClock->hr -= 24;
}
}
void show (CLOCK *pClock)
{
printf("Time = %d hours %d minutes %d seconds ", pClock->hr, pClock->min, pClock->sec);
}