Greetings suptboyr,
Good to see you have an idea of how this process works. Creating a program to use mathematics in C is not difficult what so ever. It's similar to the syntax of how you write it on paper, but with easier calls.
Convert minutes to [hours and minutes]
Creating a function in C for this type of algorithm is not difficult what-so-ever. It's actually very simple if we take a closer look.
Let's take for example you send minutes to a function, say, minutesToTime(). All we would do is create a while loop, find if minutes is greater than 60, add one to our hours variable and remove 60 from our minutes variable.
void minutesToTime(int minutes) {
int hours = 0; // Be sure to initialze to 0
// If our variable is greater than 60
while (minutes > 60) {
// Remove 60 from our variable
minutes -= 60;
// Add 1 to our hours [as 60 minutes is equivelant to one hour]
hours++;
}
// Just print our new calculation
printf("%d:%d\n", hours, minutes);
}
This is simple. We know thatwhile loops continue again as our expression is true. As long as minutes is greater than 60, our while loop will continue. The reason this loop will break after a period of time is because we subtracted 60 every time our loop was called. Analogy:
As long as there are 3 pies then...
ยป Eat one
You will probably say our loop will break after the 3rd time. Our -= call was put there to eat 60 minutes if there were over 60 minutes originally.
So if we sent 200 minutes to our function, it would produce an answer of 3 hours and 20 minutes. Now of course we would need to increase the current time set.
Get time set by user
This is not hard what so ever. Just a few function calls, and we can get what a user entered in. In this case we can use scanf() , as it reads data from the standard input (stdin) and stores it into the locations given by argument(s).
We could probably write a function called getInput() for simplicity:
void getInput(void) {
int hour, minute;
char c;
// Ask for input
printf("Enter hours, minutes, and (A)m or (P)m: ");
// Get input
if (scanf("%d %d %c", &hour, &minute, &c) == 3) {
// Send data to global variable
}
}
The context of this is also quite simple. scanf() is similar to the printf syntax, though with different rules. As scanf() returns the value of successfully read arguments, and preceding the reference operator (&) on standard variables, it should work appropiately.
Once we send our data from getInput() to the global variable, it will not be hard to add our new numbers from minutesToTime(). Of course, I did not add any checking if the hours combined would be greater than 12 and if so to change PM to AM or vice versa, but that in itself will not be difficult.
Conclusion
Using the C language is not difficult for simple tasks. Once you understand the syntax, everything else should make sense. Using the printf() and scanf() calls require the include of . If you have further questions, please feel free to ask.
- Stack Overflow