Lab material
- Slides: functions
- Additional example: dist_converter.c
Lab tasks
For this lab, you have 2 tasks. There is also an advanced task, which extends the features of lab task #2.
In the first task, you need to write the declarative part of functions in a pre-written program. In this task, you will only be working with variables.
In the second task we focus on arrays and you have to write the entire program.
Task 1: Electricity price calculator
In this task, we have written most of the program already. This includes the entirety of main() function.
You will need to fill in the missing parts in the functions for this program. In the base code, all of the returns from the functions have been written as return 0 . This is done so that the program would compile and you could test it step-by-step. You need to replace this in every function based on the description in the function comment, right above the function itself.
Download the starter code from here: 6_1_electricity_basecode.c
Requirements
- Start by introducing yourself to the base code. Your task must be built on it.
- Your task is to write te declarative part of seven functions. The purpose of the function is described right before it as a comment.
- main() function and the structure of the code cannot be changed. It’s recommended to also avoid renaming the functions and variables.
Recommendations and hints
- Start by going through the code. Look at where all the parts of the code are – libraries, macros, prototypes, main function and the rest of the user-defined functions. Check out how main calls the user-defined functions, what is given as parameters etc. Do not change anything right now!
- Once familiar, start by writing the function bodies (declarative part of the function). Solve 1 function at a time, compile and test if it works! Do not move forward before it works!
- The recommended structure for the input functions is a do while loop, which has an if statement inside to print an error for wrong input.
- All other functions are solvable by just writing one line. You need to replace the return 0 with the correct formula.
- Careful with units! There is a mix of megawatw-hours, kilowatw-hours and watt-hours! Check the function comment for which it is.
- VAT – value added tax, 20% in Estonia
- Current market price in MWh before taxes: https://dashboard.elering.ee/et
- Current market price per kWh in cents, including taxes: https://www.elektrikell.ee
Testing
Test 1: no errors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Enter the market price for electricity in MWh: 412.65 Market cost of electcity is 412.65 EUR / MWh. This is 0.4126 EUR per kWh before and 0.4952 EUR per kWh after taxes. Lets do a rough savings estimate when switching from incandescent bulbs to LEDs Number of E27 lightbulbs in use: 9 Average hours per day the bulbs are turned on for: 6 Results are calculated for a 30-day month. Using 60 W incandescent bulbs consumes 97200 W, costing 48.13 EUR Using 9 W LED bulbs consumes 14580 W, costing 7.22 EUR That's a saving of 40.91 EUR. At the price of 0.69, you could buy 59 packs of instant noodles with that money! |
Test 2: invalid input tests
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Enter the market price for electricity in MWh: -250 Retry! Must be > 0 > -5 Retry! Must be > 0 > 125 Market cost of electcity is 125.00 EUR / MWh. This is 0.1250 EUR per kWh before and 0.1500 EUR per kWh after taxes. Lets do a rough savings estimate when switching from incandescent bulbs to LEDs Number of E27 lightbulbs in use: -1 Retry! Must be > 0 > -3 Retry! Must be > 0 > 8 Average hours per day the bulbs are turned on for: 7 Results are calculated for a 30-day month. Using 60 W incandescent bulbs consumes 100800 W, costing 15.12 EUR Using 9 W LED bulbs consumes 15120 W, costing 2.27 EUR That's a saving of 12.85 EUR. At the price of 0.69, you could buy 18 packs of instant noodles with that money! |
Task 2: finding results from an array
The purpose of the second task is to find results from a user-entered array, based on the knowledge acquired so far. The functions you create must be universal (array length must not be fixed, but passed). These will also be the first function in your own collection of functions that you can easily copy in as needed later in the course!
Requirements
- Program should read 5 integers from the user. Numbers must be from -100 to 100, ends inclusive.
- Print out the numbers entered (self-check)
- Find and print the arithmetic mean with 2 places after the comma.
- Find and print the smallest value in the array
- Allow the user to enter a number and then find if it was a part of the originally entered array or not.
- All functions must be made according to the function descriptions provided on this page under “Step-by-step guide to solve the task”
Code general structure
This is a general recommendation of order of operations for the code which you may use as a template.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <stdio.h> // Constants for min and max value #define VALUE_MIN -100 #define VALUE_MAX 100 // Constant for amount of numbers the program processes #define NUM_CNT 5 // Function prototypes int main(void) { // Call the function "filling the array" // Call the function "printing the array" // Call the function "arithmetic mean", // and print the answer returned in here // Call the function "minimum value", // and print the answer returned in here // Call "reading a single integer". Store the returned value. // It will be passed the the next function. // Call the function "check if value in array", // after which print the conclusion right here whether the number was in the array or not return 0; } |
Step-by-step guide to solve the task
In addition to what you have studied before, the following rules also apply
- Constants defined as macros that could vary from task to task (e.g. array length, min and max values, tax percentage) must be passed as a parameter. This does not apply for magical number that will never change (e.g. mass of an electron, universal gas constant, pi).
12345678910// Sample given from lab task 1// Magical number is defined as a macro#define VAT_PERCENTAGE 20.0f// When calling the function, we pass itCalculateVat(pricePerKwh, VAT_PERCENTAGE);// In the function we accept it as a parameter (local variable)float CalculateVat(float price, float vatPcnt): - The functions you create for calculation results must not have side effects (e.g. arithmetic mean, min value, does the vaule exist in an array). The result must be returned and printed out in main. Printing the result in the function is not allowed.
- Side effects are allowed (and expected) in functions dealing with input and output (e.g. reading a single integer, printing of the array).
- No global variables! All variables must be declared as local variables, values should be passed as parameters and given back using the return value.
Solve the program step-by-step. Test your code every time after you complete a function. The functions are given in the order in which we recommend to complete them for this task.
You must create all functions described below. There can be more functions than initially may seem reasonable. Just as a reminder – the philosophy is to write simple and short functions that typically don’t have any side effects and that do only one thing (and do it well).
➡ Function: reading a single integer
Description:
Reads one integer from the user, that is checked to be in the allowed range. The function must not return before the entered value is within the allowed range. If the user entered number wasn’t between the allowed minimum and maximum, the user will be warned and prompted again.
Parameters:
- integer – minimum allowed value.
- integer – maximum allowed value.
Return: integer, that is between the allowed minimum and maximum.
Use: You will need to ask the user for input in two places in your program. Use this function for both of those!
➡ Function: filling the array
Description: Function is used to read n integers and store them in the array. However the function itself does not include any scanf() statements to read the values! To read a number, instead it will call the function “reading a single integer” and the value returned by it will be stored into the array. This will be done repeatedly in a loop for each member of the array.
Parameters:
- integer array – the array that will be filled.
- integer – array length.
You can add 2 extra parameters, min and max, if you wish to do so (lower and upper bound of the values).
Return: none.
➡ Function: printing the array
Description: Function prints values stored in the array.
Parameters:
- integer array – the array that will be printed.
- integer – array length.
Return: none.
➡ Function: arithmetic mean
Description: Function finds the arithmetic mean from the array and returns it.
Parameters:
- integer array – array, that contains the members of which the average will be calculated.
- integer – array length.
Return: real number – arithmetic mean.
➡ Function: minimum value
Description: Function finds the smallest member of the array and returns it.
Parameters:
- integer array – values from where the minimum value will be searched for.
- integer – array length.
Return: integer – smallest number in the array.
Testing
Test 1: no errors
1 2 3 4 5 6 7 8 9 10 |
Enter number 1 / 5: 5 Enter number 2 / 5: 9 Enter number 3 / 5: -2 Enter number 4 / 5: 16 Enter number 5 / 5: 3 The entered numbers are: 5 9 -2 16 3 Smallest value is -2 Arithmetic mean is 6.20 |
Test 2: errors in input
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Enter number 1 / 5: 15 Enter number 2 / 5: -234 Error! Allowed input range is -100 .. 100 > 999 Error! Allowed input range is -100 .. 100 > -5 Enter number 3 / 5: 19 Enter number 4 / 5: 25 Enter number 5 / 5: 55 The entered numbers are: 15 -5 19 25 55 Smallest value is -5 Arithmetic mean is 21.80 |
Advanced task 1: Check if value in array
For this task, you will create a function that checks if a given number is in the array or not.
You can use a boolean value instead of a coded integer, however boolean data type is not yet covered in the class (will be in a few weeks).
Reminders:
- When returning a coded integer, avoid magical numbers! 0 and 1 are magical in this context because they have a meaning.
- Function cannot have side effects.
Function description
Description: Function looks if the entered value is within the array or not. The result will be coded as an integer and returned.
Parameters:
- integer array – values from were the search key is being looked for.
- integer – array length.
- integer – the value that is being looked for.
Return: integer – was the entered number present in the array or not.
Testing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Enter number 1 / 5: 15 Enter number 2 / 5: -234 Error! Allowed input range is -100 .. 100 > 999 Error! Allowed input range is -100 .. 100 > -5 Enter number 3 / 5: 19 Enter number 4 / 5: 25 Enter number 5 / 5: 55 The entered numbers are: 15 -5 19 25 55 Smallest value is -5 Arithmetic mean is 21.80 Enter a number to search for: 12345 Error! Allowed input range is -100 .. 100 > 55 The number 55 is in the array! |
Advanced task 2: multiples of n to the new array
- User enters a multiplier (positive integer). Reusa a function you already have made!
- Create a function inside of which you will fill the members for a new array
- Values where the absolute value is a multiple of the entered multiplier will be added to the new array. New array members must also be absolute values.
- Function cannot have any side effects – it is not allowed to print the array. In addition, you are not allowed to call a print function from this function.
- Print the members of the newly populated array. Use a function that you already have made before.
E.g.: Input array (-5, 3, -12, 9, 22), multiplier (3), formed array(3, 12, 9)
After the class, you should
- Know the difference between a local and a global variable
- Understand what a function is and why it is important to use them
- Understand that we have been using functions from the first week. Both functions that return values and those that don’t!
- Understand, that we can create functions just like those we have been using.
- Understand the following terms
- Function prototype
- Function return type
- Function arguments
- Function parameters
- Function header
- Function body
- Be able to create proper functions
- Be able to pass variables and arrays to functions
- Be able to store the value returned from a function
- Be able to reuse functions with different arguments
- Be able to decompose your code into smaller functions
- Have a small list of universal functions that you can reuse in future codes! This list of functions will increase every week from now on.