Week 04 Tutorial Sample Answers
Tutorial Overview:
- Part 1: Functions Practice
- Part 2: Style
Part 1: Functions Practice
Tutor Demo! (10 mins)
The parts of a function
return_type function_name(parameters) {
// function body
return value;
}
Explain the parts of a function through creating a simple program which calculates
and returns the sum of two numbers. Make sure to cover the following points:
- The function protoype is above the main function and defines the function's name,
return type, and parameters (if any). It follows the syntax:
return_type function_name(
parameter_1 type parameter 1, parameter_2 type parameter_2, ...);
- The function body contains the actual code that the function executes.
It is enclosed within curly braces {}
.
- If the function has a return type other than void, it must contain a return
statement to return a value to the caller.
- Parameters are placeholders for values that are passed into the function when
it is called. They are defined in the function header and used within the function body.
- Local variables are declared within the function body and are only accessible
within that function. They store temporary data used during the function's execution.
- The function is invoked or called by its name followed by parentheses ()
containing the arguments (if any) being passed to it.
Solution below:
// functions.c
//
// Written by Sofia De Bellis (z5418801)
// on March 2024
//
// This program is a simple demonstration of functions
#include <stdio.h>
// Function protoype
int add(int number1, int number2);
int main() {
int result;
int num1 = 5;
int num2 = 3;
// Function call
result = add(num1, num2);
printf("Result: %d\n", result);
return 0;
}
// Function definition
int add(int number1, int number2) {
// Function body
int sum = number1 + number2;
// return statement
return sum;
}
Your turn! (20 mins)
We have been provided a program which simulates a bubble tea shop and is very similar to last weeks coffee shop activity. All the code for the program is currently in the main
function and this task involved you working together to refactor the program to use a series of functions.
// bubble_tea.c
//
// Written by YOUR-NAME (YOUR-ZID) on TODAYS-DATE
//
// This program is a simple bubble tea store used to teach functions
#include <stdio.h>
#define LARGE 'L'
#define REGULAR 'R'
#define ADDED_COST 0.5
#define BASE_TEA 10
#define BASE_TOPPINGS 5
#define BASE_COST 6.5
// enum definitions
enum bubble_tea_type {
MILK_TEA,
FRUIT_TEA,
TARO_MILK,
MATCHA_LATTE,
};
enum topping_types {
TAPIOCA_PEARLS,
JELLY,
POPPING_PEARLS,
ALOE_VERA,
};
// struct definitions
struct bubble_tea {
enum bubble_tea_type type;
enum topping_types topping;
int topping_qty;
char size;
};
struct inventory {
int tea;
int toppings;
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////// FUNCTION PROTOYPES //////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// TODO: Add functions protoypes here
////////////////////////////////////////////////////////////////////////////////
////////////////////////////// MAIN FUCNTION ///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
int main(void) {
struct inventory inventory;
inventory.tea = BASE_TEA;
inventory.toppings = BASE_TOPPINGS;
// Take the user's bubble tea order
struct bubble_tea order;
int type;
printf("Enter bubble tea type (0: MILK TEA, 1: FRUIT TEA, 2: TARO MILK, "
"3: MATCHA LATTE): ");
scanf("%d", &type);
if (type == 0) {
order.type = MILK_TEA;
} else if (type == 1) {
order.type = FRUIT_TEA;
} else if (type == 2) {
order.type = TARO_MILK;
} else if (type == 3) {
order.type = MATCHA_LATTE;
}
printf("Enter topping (0: TAPIOCA PEARLS, 1: JELLY, 2: POPPING PEARLS, "
"3: ALOE VERA): ");
scanf("%d", &type);
if (type == 0) {
order.topping = TAPIOCA_PEARLS;
} else if (type == 1) {
order.topping = JELLY;
} else if (type == 2) {
order.topping = POPPING_PEARLS;
} else if (type == 3) {
order.topping = ALOE_VERA;
}
printf("Enter topping qty: ");
scanf("%d", &order.topping_qty);
printf("Enter size (L for Large, R for Regular): ");
scanf(" %c", &order.size);
// Check available stock and end the program if insufficient stock
if (inventory.tea - 1 <= 0 ||
inventory.toppings - order.topping_qty <= 0) {
printf("Sorry, we cannot fulfill your bubble tea order due to "
"insufficient stock.\n");
return 1;
}
// Calculate the cost
double total_cost = BASE_COST;
if (order.size == LARGE) {
total_cost += ADDED_COST;
}
if (order.type == MILK_TEA ||
order.type == TARO_MILK ||
order.type == MATCHA_LATTE) {
total_cost += ADDED_COST;
}
int count = 0;
while (count < order.topping_qty) {
total_cost += ADDED_COST;
count++;
}
// Print the final order and cost
printf("Order:\n");
printf("Type: %d\n", order.type);
printf("Topping Qty: %d\n", order.topping_qty);
printf("Size: %c\n", order.size);
printf("Total Cost: %.2lf\n", total_cost);
// Update the stock after fulfilling the order
if (order.size == LARGE) {
inventory.tea -= 2;
} else {
inventory.tea -= 1;
}
inventory.toppings -= order.topping_qty;
// Step 6: print the remining inventory
printf("The current inventory is: ");
printf("Bubble tea(s): %d\n", inventory.tea);
printf("Topping(s): %d\n", inventory.toppings);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
///////////////////////////// FUNCTION DEFINITIONS /////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// TODO: Write function definitionds here
Extra Tip: When to Create Your Own Functions?
In the above activity, we have seen functions created for the specific context. However, when you are creating your own functions, if you are unsure what code you should put into functions, here are some example operations that programmers often create functions for:
- Printing out values from an array
- Checking inputs from the user are valid (e.g. within a valid range of values)
- Modifying arrays in a specific way (e.g. sorting an array of ints in ascending order)
- Searching for a particular value in a collection such as an array
- Mathematical operations which require multiple lines of code
- Handling and printing error messages
- Memory allocation and value initialisation for a data structure (this will be addressed later in the term)
Part 2: Style (10 mins)
This Kahoot will cover points from the https://cgi.cse.unsw.edu.au/~dp1091/24T3/resources/style_guide.html