PR1EN4: Functions

Lab material

Lab tasks

In this lab, you have a total of 3 lab tasks. All tasks have starter codes that will fix the structure and give you a planned workflow, which mostly is given as step-by-step instructions.

Tasks number 2 and 3 can be expanded by extra tasks.

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: https://blue.pri.ee/ttu/files/iax0583/aluskoodid/4_1_electricity_template.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

Test 2: invalid input tests

Task 2: Sequence generator

In this task, you will create a program that generates 2 different sequences of numbers: arithmetic sequence, geometric sequence. This task is expanded with an extra task, improving visuals and adding a prime number generator

Follow the step-by-step guide to complete this task!

Download the starter code: https://blue.pri.ee/ttu/files/iax0583/aluskoodid/4_2_sequence_gen_template.c

Requirements

  • Complete all the functions as instructed by the function comments and the step-by-step guide below the requirements section on this page.
  • The program contains both arithmetic sequence (arithmetic progression) and geometric sequence (geometric progression) generators.
  • User is allowed to select which generator they want to use and the parameters for the sequence.
  • Initial values for sequences and ratios must allow for floats.
  • Results must be printed with 2 decimal places.

Step-by-step guide

  1. Compile the code. See what works, what doesn’t. Read through the code.
  2. Add the call to the PrintMenu()  function into main() . Look for the TODO comment.  Write the function call below it. If it works, delete the TODO comment.
    TEST THAT IT WORKS BEFORE MOVING ON!
  3. Complete the PrintSeparator()  function. You need to write a loop to print exactly the number of #  symbols on the screen that was given as the function parameters.
    TEST THAT IT WORKS BEFORE MOVING ON!
  4. Complete the PrintAsciiWelcomeMsg()  function by adding some ASCII art of your own preference (image, text, ..) . You can use text or image to ASCII art converters or use already existing ASCII art galleries to find something you like.
    TEST THAT IT WORKS BEFORE MOVING ON!
    TIP: There are many online resources for galleries and converters. One of such is https://www.asciiart.eu
    NB! Some commonly used symbols in ASCII, such as \  (escape sequence) or  %  (format specifiers) have reserved meaning in C. To print \ , you need to write \\  and to print %  you need to write %%. An easy way to handle this is put the art into a new file and do a document-wide replacement for the unwanted character (ctrl+h in Geany).
  5. Go to ArithmeticSequence()  function.
    1. Declare the missing variables (you need 3 in total)
    2. Add the prompts for user input and store the input into the variables declared.
    3. Write a function call the function ArithmeticSequenceGenerator()  with the required parameters.
      NB! The function ArithmeticSequenceGenerator()  is commented out from the code to avoid excess compiler warnings on unused variables. Until you comment that function in, you will see an “undefined reference” error and the program will not compile! Comment the function in so you can compile and test!
      TEST THAT IT WORKS BEFORE MOVING ON!
  6. Go to the function ArithmeticSequenceGenerator()  and complete it. You need to write a loop, that has 2 statements
    1. Print the current value of the sequence.
    2. Calculate the next value in the sequence.
      NB! This order is important!
      Hint 1: next_value = current_value + common_difference
      Hint 2: You don’t need any other variables besides the loop counter. Do not use arrays! (future topic).
      TEST THAT IT WORKS BEFORE MOVING ON!
  7. The switch ()  statement handling the user input only has one case specified. Add the other 2 cases that are missing from it (You can see that they are listed as menu options by the PrintMenu()  function
  8. In the same manner you completed the arithmetic sequence, complete the two functions for geometric sequence.

Now the task should be complete. Compare your output to the testing output below.

Testing

Make sure to test through all 3 menu options and invalid input.

Testing the arithmetic sequence generator

Testing the geometric sequence generator

Exiting without using

Task 3: Appointment planner

In this task, you will create a simple time generator for appointments.

Download the starter code: https://blue.pri.ee/ttu/files/iax0583/aluskoodid/4_3_timetable_template.c

Requirements

  • The start of the workday is defined
  • User must enter the number of clients and the duration of an appointment
  • Program will generate consecutive appointment times for the clients
  • Must implement and use at least the given list of function. If you wish, you can implement extra functions.
  • Generated appointment times must be valid
  • Output must be visually aligned
  • All functions are given as names only. You must give all of them return types and parameters. Note, that if there are no parameters, void must be written into the parenthesis.
  • The calculation of the time is given to you as an algorithm

Time calculation algorithm

Approach

This task is given to you as more of a bare-bones structure, so that you will in the end, still be able to divide your program into reasonable functions, but allow you more freedom of thought.

For every function you implement, start by setting up a return type and parameters list. These are specified in the function comment. Once that is complete, write the prototype for the function before the main() function. Then proceed to write the body of the function and finish by adding the call to the function in the appropriate place.

Open me to get some hints
  • First, finish the parts that are already in use or half finished – such as PrintTime()  and PrintTimeInterval() . These should be easy to complete and test and get some warnings out of the way.
  • Finish the GetPositiveInt() function. You’ve already written this function before in this class, just copy the body of the function, set the return value and parameter to void and you’re ready to grab the required user input from main() function (number of clients and appointment length).
  • Start working with the PrintTimetable()  function. Call it out from main() and create a loop to print out the list of clients. Don’t worry a bout times yet.
  • Next up, finish the CalcNextHour()  and CalcNextMin()  functions. Both of these are one-liners where you just need to do a calculation and return that value.
    Hint: you can test them by just calling them out randomly – i.e.
    CalcNextHour(8, 0, 50)  should return 8 and CalcNextHour(8, 0, 70) should return 9. Similarly CalcNextmin(8, 0, 50)  should return 50 and  CalcNextmin(8, 0, 70)  should return 10.
  • Now go and start filling the loop body of your  PrintTimetable() function. Look at the algorithm for reference.
    NB! For this to work, you need to know both the current time and the end time (next appointment time) at the same time – so you need variables for both.  With those 4 values, you need to call the  PrintTimeInterval() function.
  • Now test and debug. All the parts should be there, just need to make sure they work together.

Testing

Testing with only minute number overflowing. 

Testing with hours also overflowing

Extra tasks

Extra task 1: Prime numbers and results per line

This task expands on the base task completed in the lab.

Requirements

  • Use the completed lab task 2 as the base for this lab task
  • Add a prime number generator. Use the given function (below requirements)  in your code!
  • Add a limit to how many results per line will each generator print. Find a suitable limit on your own.
    Alternative: If you wish to make it look fancier, you can also count characters to avoid breaking the width of the application. Functions such as snprintf()  can help with this.

Testing for prime function

Use this function as a part of the prime number generator. Note you will also need to add the IS_PRIME macro to your code!

Hint: Function return values can be directly used in if  statements: https://blue.pri.ee/ttu/coding-guides/conditional-statements/#Function_calls_in_conditionals

Testing

Note, that there are two different results shown. Both are correct in terms of the task completion. You only need to show one of them! Second one is for inspiration if you want to go all out and make it even nicer.

Result count

Line character count

Extra task 2: Add breaks and end-of-day.

This task expands on the base task completed in the lab.

Requirements

  • Use the completed lab task 3 as the base for this lab task.
  • Add a configurable break between each client appointment (i.e. 10 min between clients)
  • Add a limit to how long a workday is (i.e. 8 hours. if a client’s appointment would go beyond the current work day, put that and all the following appointments to the next day. If multiple days are required, add day counter.

Testing

Example of expected output for multiday scheduling

After this class, you should

  • Be aware of simple padding and alignment modifiers
    • padding integers with spaces and zeros
    • padding floating point values
    • padding and left-aligning strings
    • stripping the ends of too long strings
  • 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 values (constants, macros, through variables) to functions
  • Be able to store the value returned from a function
  • 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.

Additional content