# Very basic “sleep calculator” algorithm in C using cs50 library

I've been following along with CS50 online and tried my first shot at making a program from scratch and without guidelines. I hope you may be able to rip it to shreds for me.

//
// this program determines how many hours you slept last night.
// it assumes that:
// you're using a 12 hour clock
// you sleep for a maximum of 24 hours
//

#include <stdio.h>
#include <cs50.h>

int main(void)
{   // get user bedtime
printf("When did you go to bed last night?\n");
int bedtime = GetInt();
// determine AM or PM
printf("AM [1]\nor\nPM [2]\n");
int b = GetInt();
// get user wake up time
printf("When did you wake up this morning?\n");
int wakeup = GetInt();
// determine AM or PM
printf("AM [1]\nor\nPM [2]\n");
int w = GetInt();
// interpret inputs and determine how to calculate hours slept
{if ((b == 1) && (w == 1))
{
int slept = wakeup-bedtime;
printf("You slept for %i hours last night\n",slept);

}
else if (((b == 1) && (w == 2)) || ((b == 2) && (w == 1)))
{
int slept = 12-bedtime+wakeup;
printf("You slept for %i hours last night\n",slept);

}
else
{
int slept = (12-bedtime)+12+wakeup;
printf("You slept for %i hours last night\n",slept);
}
}
}


A few things:

• Naming: b and w aren't particularly descriptive. Even bampm and wampm are better.

• You've got extra {} around your if statement for some reason.

• Your algorithm does a lot of tests. What if you convert to 24-hour time?

Doing so will let you get rid of b and w by changing bedtime and wakeup after you read them.

printf("When did you go to bed last night?\n");
int bedtime = GetInt();
// determine AM or PM
printf("AM [1]\nor\nPM [2]\n");
int ampm = GetInt();
// convert to 24-hour time
if (ampm == 2) bedtime = bedtime + 12;
// get user wake up time
printf("When did you wake up this morning?\n");
int wakeup = GetInt();
// determine AM or PM
printf("AM [1]\nor\nPM [2]\n");
ampm = GetInt();
// convert to 24-hour time
if (ampm == 2) wakeup = wakeup + 12;


Also, the conditionals get easier:

int slept = wakeup - bedtime;
if (slept < 0) { slept = slept + 24 } // math is your friend
printf("You slept for %i hours last night\n",slept);

• Once principle of programming is "Don't Repeat Yourself" aka "DRY". Do you really need 3 copies of the output printf?

Of course not. You can move it after the end of the if statement.

• Finally, I don't know if this was covered in class, but you're not doing any input checking. What if the user puts in 3 instead of 1 or 2 ? What if they put in times like -5 or 27 ?