Skip to main content

Example: Cookies

Write a program that will calculate the number of cookies that can be made given a certain amount of cookie dough and the size of the cookie.

This program will start by asking the user for two pieces of information:

  1. The amount of cookie dough in number of grams.
  2. The amount of dough needed for one single cookie in grams.

The program will calculate and print out:

  1. The number of cookies that can be made with the given amount of dough.
  2. The amount of left over dough.

Start by working out what we need to do:

To solve this problem we start by breaking down the sequence of steps and putting together what we already know how to do:

  1. We know we need to read in two pieces of information from the user:

    • total amount of cookie dough
    • amount of cookie dough needed per cookie
  2. We need to calculate and display two things:

    • number of cookies
    • amount of left over dough

Sequence

Sometimes it helps to organize our thoughts using flow charts which you are learning about in your APS Course

We know that we need to start by declaring variables to hold the information we want the user to enter. We can also declare variables to hold the results. For each piece of information we need from the user we need to prompt then read that information.

The above flow chart documents the sequence of instructions needed to accomplish our task. We will now convert this into C code

The program:

#include <stdio.h>

int main(void)
{
//we use int here as weight in grams are typically whole numbers.
//using int also allows us to use the modulus operator to find
//the left over amount of dough. We wouldn't be able to use
//modulus if we declared these as floating point.

//variables to store user input
int amtCookieDough;
int cookieSize;

//result variables
int numCookies;
int amtLeftOver;

//Prompt for amount of dough
printf("Please enter the amount of dough in grams: ");
//Read in amount of dough
scanf("%d",&amtCookieDough);

//Prompt for cookie size
printf("Please enter the size of one cookie in grams: ");
//Read in cookie size
scanf("%d",&cookieSize);

//calculate how many cookies by dividing the amt of dough by size
//of one cookie
numCookies = amtCookieDough/cookieSize;

//the left over amount is the remainder of the division
//calculated using modulus
amtLeftOver = amtCookieDough % cookieSize;

//Print numCookies and
//Print amtLeftOver
printf("You can make %d cookies with %d g of dough left over\n", numCookies, amtLeftOver);

return 0;

}