In: Computer Science
I've written three functions to increase the value of a counter in an increment of one, but when I call the functions and then try to print out their values (which should have been updated) I get the values they were originally intialized to which was 0. Below is my code for the 3 functions and where I call them in my main. Can someone please tell me where I'm going wrong?
void addsec(int hr, int min, int sec){
++sec;
if(sec==60){
++min;
sec=0;
if(min==60){
++hr;
min=0;
if(hr==24){
hr=0;
}
}
}
return;
}
void addmin(int hr, int min){
++min;
if(min==60){
++hr;
min=0;
if(hr==24){
hr=0;
}
}
return;
}
void addhour(int hr){
++hr;
if(hr==24){
hr=0;
}
return;
}
int main(int argc, char* argv[]){
int sec=0;
int min=0;
int hr=0;
printf("the current value of hour is %d\n", hr);
printf("\n");
printf("the current value of minute is %d\n", min);
printf("\n");
printf("the current value of second is %d\n", sec);
printf("\n");
/*test that add one to hr, min, sec works, then print military
and standard time*/
addsec(hr, min, sec);
printf("the updated value of second is %d\n",
sec);
printf("\n");
addmin(hr, min);
printf("the updated value of minute is %d\n",
min);
printf("\n");
addhour(hr);
printf("the updated value of hour is %d\n", hr);
printf("\n");
...
#include <stdio.h>
void addsec(int hr, int min, int *sec){
++(*sec);
if(*sec==60){
++min;
sec=0;
if(min==60){
++hr;
min=0;
if(hr==24){
hr=0;
}
}
}
return;
}
void addmin(int hr, int *min){
++(*min);
if(*min==60){
++hr;
min=0;
if(hr==24){
hr=0;
}
}
return;
}
void addhour(int *hr){
++(*hr);
if(*hr==24){
hr=0;
}
return;
}
int main(int argc, char* argv[]){
int sec=0;
int min=0;
int hr=0;
printf("the current value of hour is %d\n", hr);
printf("\n");
printf("the current value of minute is %d\n", min);
printf("\n");
printf("the current value of second is %d\n", sec);
printf("\n");
addsec(hr, min, &sec);
printf("the updated value of second is %d\n", sec);
printf("\n");
addmin(hr, &min);
printf("the updated value of minute is %d\n", min);
printf("\n");
addhour(&hr);
printf("the updated value of hour is %d\n", hr);
printf("\n");
}
// The issue we need pass use call by reference to effect changes
// so you have used call by value because of that changes did't had any impact
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me