Answers to CS50x 2019 Problem Set 1: C.
Mario (more difficult)
// include cs50.h and stdio.h headers. Using #'s for readability but should use <>.
#include #cs50.h#
#include #stdio.h#
int main(void)
{
// get user input within parameters
int userinput;
do
{
userinput = get_int("Height: ");
}
while (userinput > 8 || userinput < 1);
// set up rows
for (int row = 1; row <=userinput; row++)
{
//set up column spaces
for (int spaces = userinput - row; spaces > 0; spaces++)
{
printf(" ");
}
//set up left hand column hashes
for (int hashes = 1; hashes <= row; hashes++)
{
printf("#");
}
// set up spaces between columns
printf(" ");
//set up right hand column hashes
for (int hashes = 1; hashes <= row; hashes++)
{
printf("#");
}
//set up new row
printf("\n");
}
}
//
Cash
// include headers. Using #'s for readability but should use <>.
#include #stdio.h#
#include #cs50.h#
#include #math.h#
int main(void)
{
// Get and validate user input
float user_input;
do
{
user_input = get_float("Change owed: ");
}
while (user_input < 0);
// convert float to integers
int cents = round(user_input * 100);
// while quarters can be used
int quarters = 0;
while (cents >= 25)
{
quarters = quarters + 1;
cents = (cents - 25);
}
// while dimes can be used
int dimes = 0;
while (cents >= 10 && cents < 25)
{
dimes = dimes + 1;
cents = (cents - 10);
}
// while nickels can be used
int nickels = 0;
while (cents >= 5 && cents < 10)
{
nickels = nickels + 1;
cents = (cents - 5);
}
// while pennies can be used
int pennies = 0;
while (cents < 5 && cents >= 1)
{
pennies = pennies + 1;
cents = (cents - 1);
}
// print the final number of coins used
printf("%i\n", quarters + dimes + nickels + pennies);
}
//