I have a perfect running code, BUT one criteria for this homework is that it has atleast two different functions. How can i devide this code into one more functions?
I want to sort the alarmClock() function into more functions. There's alot going on in there. Maybe a updateTime() function. I tried something like this but this doesn't work:
#include <stdio.h>
void alarmClock(int, int);
void updateTime(int, int, int);
int main() {
int present_time;
int time_for_alarm;
printf("Time indicates in HHMMSS! \nPresent time: ");
scanf("%d", &present_time);
printf("Time for alarm: ");
scanf("%d", &time_for_alarm);
if (present_time == time_for_alarm)
printf("ALARM!");
else
alarmClock(present_time, time_for_alarm);
return 0;
}
void alarmClock(int presT, int alarmT) {
int presentHH = presT / 10000;
int presentMM = (presT / 100) % 100;
int presentSS = presT % 100;
int combineTime;
while (presT != alarmT) {
printf("%02d:%02d:%02d \n", presentHH, presentMM, presentSS);
presentSS++;
updateTime(presentHH, presentMM, presentSS);
combineTime = presentHH * 100 + presentMM;
presT = combineTime * 100 + presentSS;
}
printf("ALARM!");
}
void updateTime(int presentHH, int presentMM, int presentSS) {
if (presentSS > 59) {
presentSS = 0;
presentMM++;
if (presentMM > 59) {
presentMM = 0;
presentHH++;
if (presentHH > 24) {
presentHH = 1;
}
}
}
}
My teacher hinted me saying "you could make on printTime() function and one updateTime() function sending present_time as arguments". But i dont know how...
This is my working code that needs atleast one more function.
#include <stdio.h>
void alarmClock(int, int);
int main() {
int present_time;
int time_for_alarm;
printf("Time indicates in HHMMSS! \nPresent time: ");
/ scanf("%d", &present_time);
/
printf("Time for alarm: ");
scanf("%d", &time_for_alarm);
if (present_time == time_for_alarm)
printf("ALARM!");
else
alarmClock(present_time, time_for_alarm);
return 0;
}
void alarmClock(int presT, int alarmT) {
int presentHH = presT / 10000;
int presentMM = (presT / 100) % 100;
int presentSS = presT % 100;
int combineTime;
while (presT != alarmT) {
printf("%02d:%02d:%02d \n", presentHH, presentMM, presentSS);
presentSS++;
if (presentSS > 59) {
presentSS = 0;
presentMM++;
if (presentMM > 59) {
presentMM = 0;
presentHH++;
if (presentHH > 24) {
presentHH = 1;
}
}
}
combineTime = presentHH * 100 + presentMM;
presT = combineTime * 100 + presentSS;
}
printf("ALARM!");
}
The working code gives this output (correct output);
if present_time = 115957
and time_for_alarm = 120001
output is
11:59:57
11:59:58
11:59:59
12:00:00
ALARM
but when i created the updateTime() function the code keeps running forever if i have these values:
if present_time = 115957
and time_for_alarm = 120001
output is
11:59:57
11:59:58
11:59:59
11:59:60
11:59:61
11:59:62
11:59:63
... and so on and on (presentSS keeps going +=1 forever)
The variables presentHH, presentMM, and presentSS in the function updateTime are distinct from the ones in alarmClock, so changes to those variables in updateTime are not visible in the calling function.
You need to pass the address of each of these variables and dereference those pointers in updateTime. Then you're actually changing the variables defined in alarmClock.
So change the definition of updateTime to:
void updateTime(int *presentHH, int *presentMM, int *presentSS);
And call it like this:
updateTime(&presentHH, &presentMM, &presentSS);
You'll also need to change the body of updateTime to reflect that the parameters are now pointers and to dereference them. I'll leave that as an exercise to the reader.
dbush shows a good way to solve the problem with not many changes to the general structure. I would suggest a different approach to the task. Instead of passing the addresses of these values, you could restructure your code to pass the composite time and return the updated time. Similiar to this
int updateTime(int presT){
//seperate, update and combine the time value
return updatedTime;
}
this would reduce the interface and would also enable you to write even more functions that can be reused. As you now will have to seperate and combine the time in updateTimeand alarmClock you can write functions that do this instead of writing the same code twice.
example:
int getHours(int time){
return time / 10000;
}
and:
int combineTime(int hours, int minutes, int seconds){
combinedTime = (presentHH * 100 + presentMM)* 100 + presentSS;
return combinedTime;
}
This will help you get more expierience with functions and also helps to let you see one big benefit of functions (having reusable code).
Related
I am having problems with the while function on the C programming language. It runs too many times, Ignoring the end condition.
#include <stdio.h>
int main()
{
long long int lenX,lenY,cube,needX,needY,i,t = 0;
scanf("%lld%lld%lld", &lenX,&lenY,&cube);
while (needX <= lenX)
{
needX + cube;
i++;
}
while (needY <= lenY)
{
needY + cube;
t++;
}
printf("%lld\n",i*t);
return 0;
}
When inputting 6 6 4(the answer should be 4) the output ranges from -8519971516809424873 to 0.
I'm sorry if I missed something obvious. I'm new to the C programming language
EDIT: It doesn't care about the numbers
#include <stdio.h>
int main()
{
long long int lenX,lenY,cube,needX,needY;
scanf("%lld%lld%lld", &lenX,&lenY,&cube);
while (needX*cube <= lenX)
{
needX = 574973;
}
while (needY*cube <= lenY)
{
needY = 4057348;
}
printf("%lld %lld %lld\n",needX*needY,needX,needY);
return 0;
}
Still outputs:409600 100 4096
These expression statements
needX + cube;
and
needY + cube;
have no effect.
It seems you mean
needX += cube;
and
needY += cube;
Pay attention to that the variables needX, needY i were not initialized that results in undefined behavior..
This declaration
long long int lenX,lenY,cube,needX,needY,i,t = 0;
initializes to zero only the variable t.
You need to rewrite the declaration at least like
long long int lenX,lenY,cube,needX = 0,needY = 0,i = 0,t = 0;
I'm trying to succeed with project euler's 4th problem : What is the biggest palindrome-number you can make by multiplying 2 3-digit numbers ?
( https://projecteuler.net/problem=4 )
I have the following code but it is not working. For some reason it seems like the nested while loop is broken. It only print numbers 10000 to 99900, which means the nested while loop is executed only once...
#include <stdio.h>
#include <string.h>
int is_a_palindrome(int test_number);
int main (void)
{
long result;
long number_x_1;
long number_x_2;
long biggest_pal;
number_x_1 = 100;
number_x_2 = 100;
while (number_x_1 < 1000)
{
while (number_x_2 < 1000)
{
result = number_x_1 * number_x_2;
printf("%li\n", result);
if (is_a_palindrome(result) == 1)
{
biggest_pal = result;
printf("palindrome found : %li", biggest_pal);
}
number_x_2++;
}
number_x_1++;
}
return (biggest_pal);
}
int is_a_palindrome(int test_number)
{
int test_number_unchanged;
int reverse;
reverse = 0;
test_number_unchanged = test_number;
while (test_number != 0)
{
reverse = reverse * 10;
reverse = reverse + test_number % 10;
test_number = test_number / 10;
}
if (test_number_unchanged == reverse)
{
return (1);
}
else
{
return (0);
}
}
You don't set number_x_2 to 100 inside the outer loop... you do it only once outside all loops !
Thus when the 2nd loop on number_x_1 starts, number_x_2 is already at the maximum value and the inside loop (at while (number_x_2 < 1000)) does not start.
Check that simple mistake.. you must initialize number_x_2 = 100 in outer loop..
#include <stdio.h>
#include <string.h>
int is_a_palindrome(int test_number);
int main (void)
{
long result;
long number_x_1;
long number_x_2;
long biggest_pal;
number_x_1 = 100;
while (number_x_1 < 1000)
{
number_x_2 = 100;
while (number_x_2 < 1000)
{
result = number_x_1 * number_x_2;
printf("%li\n", result);
if (is_a_palindrome(result) == 1)
{
biggest_pal = result;
printf("palindrome found : %li", biggest_pal);
}
number_x_2++;
}
number_x_1++;
}
return (biggest_pal);
}
int is_a_palindrome(int test_number)
{
int test_number_unchanged;
int reverse;
reverse = 0;
test_number_unchanged = test_number;
while (test_number != 0)
{
reverse = reverse * 10;
reverse = reverse + test_number % 10;
test_number = test_number / 10;
}
if (test_number_unchanged == reverse)
{
return (1);
}
else
{
return (0);
}
}
The inner while loop sends number_x_2 to 1000, but then it stays at 1000 so the program never runs through the inner loop after the first cycle. The program then increments number_x_1 until it reaches 1000, and the program ends.
To solve this, move the statement number_x_2 = 100; To the line before while(number_x_2 < 1000).
This question already has answers here:
Returning an array using C
(8 answers)
Closed 7 years ago.
How can we return an array from a function i have no idea how to do this???
the are three cars and each is parked in a parking area for maximum 24 hours we have to find the cost for each car by making a function which wil evaluate the cost..??
#include <stdio.h>
#include <math.h>
#include <conio.h>
int calculateCharges(float hours[]);
int main() {
float hours[3];
int i;
for (i = 0; i <= 2; i++) {
printf("Enter the hours you parked for car : %d\n", i + 1);
scanf_s("%f", &hours[i]);
}
hours[i] = calculateCharges(hours[]);
printf("%-10s%-10s%-10s\n", "Cars", "Hours", "Charge");
for (i = 0;i <= 2;i++) {
printf("%-10d%-10.2f%-10.2f\n", i + 1, hours[i], calculateCharges(hours));
}
_getch();
return 0;
}
int calculateCharges(float hours[]) {
float cost[3];
int i;
for (i = 0; i <= 2; i++) {
if (hours[i] <= 3) { //if car parked for 3 or less hours it cost 2$
cost[i] = 2;
}
else if (hours[i] > 3 && hours[i] < 24) { //if car parked for more than 3 or less then 24 hours it cost 0.5$for each extra hour$
cost[i] = 2 + ((hours[i] - 3) / 2);
}
else if (hours[i] == 24) { //if hours = 24 hours 10$
cost[i] = 10;
}
else {
cost[i] = 0; //else its an error value zero cost
}
return cost[i];
}
}
You could pass in another array in which you return the cost, instead of making it a local array. Your method would look something like this:
int calculateCharges(float hours[], float costs[], int num) {
...
for(i=0;i<num;i++) {
...
costs[i] = 2;
Functions cannot return arrays, but they can return pointers, and they can modify caller-visible variables via pointer arguments. If you want a function to create an array and provide it to the caller, then that function would need to allocate the array dynamically (via malloc() or calloc()) and then use one of the methods I named to return a pointer to the first element of that array.
But as commenters also remarked, none of that appears to be needed for the problem you presented. As far as I can tell, you just need a function that computes one cost for one car. You can call such a function from inside a loop (even the same loop in which you read the input) to calculate the cost for each car, which the caller can then handle however is appropriate.
I have a function that runs every second automatically,
inside the function i have a counter "i" that increments by 1 so every 1sec. i dont want to run stuff every second but at every x seconds e.g. every 10 seconds.
so i presume the best approach is to detect the increments of i, when it increases by 13?
or a timer/sleep function to be called for the function to wait?
question: how do i detect increments i.e. how do i check if "i" goes up by 13?
void func(void){
static int i = 0;
if (every i seconds)
{
do something
}
i++;
}
Thanks for any help i get
I think you are looking for modulo operation (http://en.wikipedia.org/wiki/Modulo_operation):
void func(void){
static int i = 0;
int x = 13
if (i % x == 0)
{
do something
}
i++;
}
I am not sure I have completely understood your question.
You can try this:
void func(void){
static int i = 0;
int interval = 13;
if (i % interval == 0) /* interval can be your every second */
{
do something
}
i++;
}
Perhaps using the time() function:
#include <time.h>
const time_t intervalTime = (13);
void func(void)
{
static time_t savedTime = 0; // results in 'do something' on first execution
time_t currentTime = time(NULL);
if ( intervalTime <= (currentTime - savedTime) )
{
if( 0 == savedTime )
{ // then first time through function
savedTime = currentTime;
}
savedTime += intervalTime; // this avoids time interval drifting
do something
}
}
Your approach is legit.
Answering your question about running things every 13 seconds:
if (i > 0 && (i % 13) == 0) {
//do something
}
If you don't need to run your loop every second, then a more robust mechanism would be to use the alarm functionality available in libc: http://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html
This question already has answers here:
What are function pointers used for, and how would I use them?
(9 answers)
Closed 8 years ago.
Yesterday I learned of this really cool way to use function pointers.
Although I think its a really cool thing to be able to do I cant see WHY and WHERE this sort of method will be used?
Could someone shed some light on this?
int Mul(int x , int y)
{
return x*y;
}
int Div(int x , int y)
{ return x/y;
}
typedef int (*FuncP)(int,int);
int compu(FuncP functionP, int x , int y)
{return functionP(x , y)}
//Calling it will look like
compu(Mul,5,10);
Thanks
Cart
If you need something to be dynamic based on a situation like so:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdbool.h>
typedef int (*worker_operation)(int);
int check_for_new_woot(int inVal) {
int ret = arc4random() % 10;
if (ret < 5) {
puts("Found new woot!");
sleep(1);
return 1;
} else {
puts("No new woot :(");
sleep(1);
return 0;
}
}
int buy_current_woot(int inVal) {
if (inVal != 0) {
fprintf(stderr, "Insufficient funds!!!\n");
}
return 0;
}
int check_if_should_buy_woot(int inVal) {
printf("Should we buy the latest woot? ");
char input[10];
read(STDIN_FILENO, input, 10);
if (input[0] == 'y') {
return 1;
} else {
return 0;
}
}
void *worker_thread(void *inVal) {
worker_operation *ops = (worker_operation *)inVal;
int i = 0;
worker_operation op = ops[i];
int arg = 0;
while (op) {
arg = op(arg);
op = ops[++i];
}
free(ops);
return NULL;
}
pthread_t start_worker(worker_operation *ops) {
pthread_t pt;
pthread_create(&pt, NULL, worker_thread, ops);
return pt;
}
int main(int argc, const char *argv[]) {
bool autoBuy = true; // fetch whether we should automatically buy from woot.com from argv or stdin
int numberLoops = 10; // fetch number of times to loop through the process
int i;
worker_operation *operations;
if (autoBuy) {
operations = (worker_operation *)malloc(sizeof(worker_operation) * (numberLoops * 2 + 1));
for (i = 0; i < numberLoops; i++) {
operations[2 * i] = check_for_new_woot;
operations[2 * i + 1] = buy_current_woot;
}
operations[2 * i] = (worker_operation)NULL;
} else {
operations = (worker_operation *)malloc(sizeof(worker_operation) * (numberLoops * 3 + 1));
for (i = 0; i < numberLoops; i++) {
operations[3 * i] = check_for_new_woot;
operations[3 * i + 1] = check_if_should_buy_woot;
operations[3 * i + 2] = buy_current_woot;
}
operations[3 * i] = (worker_operation)NULL;
}
pthread_join(start_worker(operations), NULL);
return 0;
}
Note that in this code snippet uses function pointers in two places. We have a function which is agnostic of how the user wants the program to perform, that is start_worker simply creates a worker thread that will work with a list of operations. This can be easily used to create a program which has multiple threads going all with different operation queues. The second place function pointers are used are with threads. The ptrhead_create call uses a function pointer in order to create a new thread (the function specified is the function to be ran on the new thread).
Generally this is called a command programming paradigm. One can easily create an operation that another part of code can call, agnostic of what the function does. For instance this could be useful for games in the following situation:
We have a game controller that gives input. The user clicks 'up'. In code call the operation that is hooked to the 'up' action.
This modular approach allows one to enable settings for the controls so someone can hook a 'jump' operation to 'up' or a 'move forward' operation, or anything really.
Hope this helps!
Pointers to functions has multiple uses but, sticking to your example, pointer to funcions can help you to avoid hurge and ugly conditional branches like if's and switches:
If you create an associative array of operations characters as index and pointer to functions as value:
//implementacion in C doesn't matter for the example
operations["*"] = Mul;
operations["/"] = Div;
operations["*"] = Add;
operations["-"] = Sub;
You can do something like this:
int op1;
int op2;
char operation;
cout << "Insert first number /n";
cin >> op1;
cout << "Insert second number /n";
cin >> op2;
cout << "Insert operator /n";
cin >> operation;
cout >> compu(operations[operation],op1,op2);