Category Archives: Pr1_en

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

6. lab: functions

Lab material

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
Test 2: invalid input tests

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.

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).
  • 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
Test 2: errors in input

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

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.

Additional content

13. Strings

Lab materials

Lab tasks

In this task you have 2 tasks. First of which we’ll focus on the string.h library and in the second one we’ll look at manipulating strings manually.

Task 1: introducing the string.h library

In this task we’ll be focusing on the functions in the string.h library.

Requirements
  • Follow the step-by-step guide when solving this task!
  • The program must ask for a predefined password when starting. You must not allow the user past it until a correct password is entered.
  • User is asked for a sentence. Program will show how many characters there were in the given sentence (including spaces, punctuation).
  • The user is asked for a search phrase, after which it will output whether the phrase was present in the originally entered sentence (yes/no answer).
  • User is asked for 2 words, which are used to compose a sentence
    • You can choose the types of words yourself (e.g. verbs, nounds, names of items, names of people etc)
    • You can also choose the sentence you wish to compose
    • Compose the given words with others to compose a simple sentence consisting of at least 4 words.
    • One of the words given by the user must be the first word in this sentence.
    • The composed sentence must be written in a completely new (empty) variable, which must fit the composed sentence even in the worst case scenario (e.g. maximum possible length for the user-entered words).
Helper function for debugging

If you have any trouble figuring out what is actually in the string, use this function. It will print out the string, followed by each individual character (one per line). It will print the index, ascii code and the character it represents. This way it’s easy to figure out if you have a stray line change for an example.

Step-by-step guide
1. step: getting user input

We will go through this step in the class together! In this step we will create two functions necessary for our program.

For starters, let’s create a function to read a string. In the solution it is important that we would be able to read strings consisting of multiple words – we must be able to read  strings containing spaces. There are multiple ways to do this. In this sample, we will approach it using the function fgets() . If you wish to take a different approach, you are welcome to do so.

The function  fgets()  is meant to be used for reading files. However everything is a file, including the data stream coming from the keyboard. To use it, we will read the data from a file called  stdin . Secondly, the function requires us to specify the maximum length for the string – this is for safety so we wouldn’t be susceptible to buffer overflow attacks. Thirdly and the most problematic for us is that when we press the enter key when writing text, the newline \n  created by the enter key is also stored into the array.

We will approach this with the idea of creating a wrapper function. Wrappers surround an existing function or functions while providing extra features, convenience or safety.

Our wrapper needs two inputs – the character array (string) where we will store the input and the maximum length of that string.

In the solution for this function, I’ve left in question marks in 3 places where you will have to fill the gaps! Hint: if the read string is 10 characters, then at the index 8 is the last important character for us which the user entered. It is followed by the unwanted newline character, which we must get rid of. To do so, we will replace it with the string terminator symbol.

If you need, you can use the helper function provided earlier to see the contents of the read string.

In order for it to compile, the two lines handling the newline correction are commented out. Once you have replaced the question marks, comment them back in for it to work correctly.

Once the reading is done, let’s write another wrapper, this time for our  GetString()  function. This way it will be a lot cleaner to ask for input.

Now let’s try to get some input. In the example I have a character array sentence[]  , which has a length of  MAX_STR , defined a macro. The function call will look like this:

2. step: read a sentence and print its length

Read a sentence from the user. Find and print the length of the sentence the user entered.

3. step: search phrase

Add a new function to the program, where you will ask the user to input a search phrase. The function should then print whether the phrase existed in the previously entered sentence or not.

A yes/no answer is enough. To achieve this, you can just check the return value as such:

4. step: password prompt

Add a function to the program that will ask the user for their password. It could look something like this:

The prompt must be inside of a loop in such a way that the user wouldn’t be able to proceed to use your program before they’ve entered a correct password. The password prompt must be case sensitive. If you wish, you can add hints on incorrect input or limit the amount of tries the user has.

5. step: composing a sentence

Add a function to your program that will compose a simple sentence of at least 4 words. Since we don’t have any good inputs or outputs for the function, we can create it as follows (typically avoid void-void functions!):

Think! How long should the variable sentence  be to hold both user entered words in the worst case scenario, as well as all the characters you are using to formulate the sentence? The size can be approximated, but must be sufficient!

Now think of a sentence you wish to create. The sentence will have two gaps that the user will have to fill. You can choose which type of words go in there (names of objects, people, verbs, adjectives, …). One of the words that the user enters must be the at the start of the sentence. The location of the second word is up to you. E.g.  <word1> is a <word2> name! .

Once you have asked the user for input and read the words, you must compose the sentence. The sentence must be written into a new, unused (empty) character array. You must account for the worst case scenario for fitting the sentence (when the user decides to enter the maximum possible length words for booth inputs).

Example
Advanced task: Alternative count

Create a new function to do a manual count and add statistics

  • Count and show how many alphabetical characters [a-zA-Z] there were. Do not count punctuation, spaces etc.
  • Calculate and print the percentage of non-alphabetical characters in the sentence.
  • Show the percentage with one place after the comma.

Example

Task 2: Generating e-mail addresses from CSV

In this task we’re introducing you to a widely used file format for keeping data. The purpose of this task is to practice working with characters inside of a string manually.

Download the starter code: 12_2_csv_starter.c

CSV format

CSV stands for comma separated value. CSV files are used for storing structured data. Every data field in a CSV file, as the name suggest, is separated by a comma. It’s one of the most widely used formats for storing and backing up data next to database systems themselves. The primary benefit of CSV is in its simplicity, making it supported by almost all applications that process any kind of data.

In the most simple case, all data fields are separated by comas:

We are using the same complexity level for this lab task. To see how more complicated data is stored when you also need to store commas and quotes within the data fields, as well as add column headers, check here: https://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules

Requirements
  • The task must be built on the starter code.
  • Program generates e-mail addresses for every person
    • The name part of the e-mail address must be composed of first 3 characters from the first name, followed by the first 3 characters of the last name.
    • The name part is followed by a domain of your choosing
    • You can only have lower case characters in the e-mail address
    • The e-mail address must be stored in a new character array that you create. Print it to the screen from that array. You are not allowed to print the characters on the fly while processing the entry.
  • The program must print:
    • The full name of the person. First and last name must be separated by a space.
    • Generated e-mail address
  • You are not allowed to change the code present in the starter code without a confirmation from us. The starting point of the code you write is in the function  ProcessPerson()  . You are welcome (and recommended) to add more functions to the code.
Example
Hints
  • By knowing the location of the comma, you will also be able to calculate the position of the first character from the last name
  • Lower and upper case ASCII characters differ from each other by a single bit, which is valued at 32 (e.g. A is 65, a is 97)
  • All operations in this task besides adding the domain address in the end are easiest done character at a time. Library functions from string.h  can be used, but they might be unnecessarily complex for now.
  • The most common mistake in this task is forgetting to add a string terminator to the end after copying over the name part of the address!
Advanced task 1: short names

Change the way you are generating the e-mail addresses to accommodate people with shorter first or last names.

Example: Ly Kask -> lykask@ttu.ee

Advanced task 2: unique e-mail addresses

Change the way you are generating the e-mail addresses in such a way that for similarly starting names the resulting e-mail address would be different.

Change your data array to the following:

Requirements

  • The e-mail addresses must be unique
  • The name part of the address must be 6 characters
  • The addresses must still refer to the owner’s name as much as possible
  • The exact algorithm and thus the final form of the address is up to you. You will defend your decision when showing.

After this lesson, you should

  • Know that there are various ways of encoding characters, including ASCII and Unicode
  • Know what is an ASCII table and how to use it.
  • Know how strings work in C.
  • Know how to terminate a string in C and why it’s necessary.
  • Know that strings in C are also related to byte-arrays.
  • Know what is CSV, where it’s used and why.
  • Know how to use the string.h library to manipulate strings.
  • Be able to write your own string manipulation functions (manipulating characters)
  • Know what is buffer overflow and the attacks related to it.

Additional content

12. Lab: Linux and CLI

Remote lab
Note: In 2024 autumn, this lab is intended to be solved remotely. Check for more information on MM.

Lab materials

Help on commands

If you need help with some of the commands, there are three main ways to get information on the commands. Third and the slowest would be using the internet, so we’ll skip this one. The other two sources of information are available quickly from your command line

tldr (simplified community-driven man pages)

This is a quick “handbook” composed by daily Linux users. It’s main purpose is to quickly and simply describe the most common ways to use each of the programs, as well as some less common, but important ones. The downside to this utility is that it often lacks detailed information and explanations, however it will get you the information you need or at least a starting point most of the time

The tool does not come as default, but we have installed it on the lab computers.

To use in the command line type tldr command

Alternatively, you can use the web version from https://tldr.sh

I.e.. to learn how to copy files, write tldr cp

man pages

man stands for manual and comes native with Linux. It includes manuals for commands, libraries, system calls etc. It includes manuals on how to use most programs. To use a manual, just type man command .

E.g. to check out how to copy files, you can run  man cp.

To close the manual, hit the letter  q . To search within a manual, hit   / , followed by what you are searching from. All other hotkeys and additional help can be read by hitting the key  h .

The advantage of  man  compared to  tldr  is that its very detailed and has a variety of different types of information. This can also be a downside for new users, as they are very throughout and might discourage or even terrify new users.  However, once you get used to reading information in this way, it becomes irreplaceable.

Lab tasks

There are two lab tasks this week. Both of them end up with a web form that you must fill! You do not need to present us your solutions after completion. Solutions are presented by filling out web based forms.

Task 1: working on the command line

The following task will introduce you to the command line and some basics working on it.

The task will end with a web form that must be filled. The submission of the web form confirms the completion of the task.

Pick your method

Before you can start solving you will need access to Linux and a terminal window. Some options that would work for this task:

  1. Solve the task in the lab computer
  2. Solve the task by using a remote desktop connection to the lab
    Guide: Remote access using RDP
  3. Solve the task by connecting to the lab computers through an SSH tunnel
    Guide: SSH connection guide

Note: Don’t use your own Linux for this task as there are some parts of it that can only be done with the university mount points.

Solving the task

The task is written as a step-by-step workflow that you should follow. All actions should be done using the command line. In the end, you will need to submit your command history. Prepare yourself enough time to solve the task 1 from start to finish, as you will need to submit your command history in the end of the task.

Step 1: Pick your working directory

In this step, you need to choose the location for the files that you will create during this lab. Most likely it should be somewhere on your P drive – i.e. ~/P/iax0583/lab11 .

The following commands will help you navigate:

  • Use  pwd  to check your current working directory
  • Use cd  to navigate from and to directories
  • Use  mkdir  to create a directory
  • Use  ls  to check the contents of the directory. Use additional arguments for more details.
  • Use mv  to rename directories and files  (if you happened to make a mistake)
  • Use tldr command  and man command  to get help on the commands.

Change the directory to the one you intend to solve your lab task

Step 2: Download the test program

The program wget  is most often used to download files off the internet. Use this to download a tester program by running the following command

Step 3: Unpack the tester and execute it

You’ve just downloaded a zip archive. Use the program called unzip to unpack it. First learn how to use it. Then pay close attention to the output that this program will give you in order to understand what was unpacked and where! Double-checking everything with ls  doesn’t hurt either. You need to understand what was unpacked and where!

You may need to manually make the test program executable

Once you have everything unpacked and found the testing program, you may need to add execute permission to it. Note, that it may also already be set by default. If you need to add the execute permission, use chmod  to change file access permissions (including adding execution privilege)

Execute the testing program

From this point on you can try to run the program provided. Try it now! Execute the tester!

The program will stop when an unmet requirement is encountered. You should retry the testing program  after every step from this point beyond.

You should see the following output:

Execute the tester after each step in this task.

Step 4: Download VIM configuration file

NB! You should skip this step if you already have one!

Vim is one of the more commonly used command line based text editors. It’s a lot more configurable and capable compared to basic text editors such as nano.

Lets download a configuration file that will make it a little bit nicer. I.e. introduce syntax highlighting, automatic tabs etc. The file needs to be stored in your home folder – that’s were Vim will be looking for it.

1. Go to your home directory. To do this, use the command cd .  Shorthand for your home directory is ~

2. Download the configuration file. Use wget  to download the following file: blue.pri.ee/.vimrc

Use the tester to verify completion of this step!

Step 5: Copy over an additional data file with the secret

Go to the M folder in your home directory (~/M/). Find your lecturer’s public directory and go to it. In there you will find a hidden directory (it starts with a dot).

Inside you will find a .dat file. Copy that file over to the same folder as the test program. For this you will need to use the cp  command. Specify the file you want to copy and the path you want to copy it to.

To test if this worked, run the program and see if it finds the secret!

Step 6: Next up, you need to create a file with your matricula

The file you need to create is named matricula . It needs to be saved into the same folder as the rest of the files so far. To create it, I’ll provide two possible options.

Option 1: Open up your preferred command line text editor, write a file called “matricula”

Vim guide:

    • Start by writing vim matricula  to create a file called matricula and open it in Vim.
    • Press ‘i’ to enter writing mode.
    • Now write your matricula number into the file.
    • Press ‘esc’ to exit write mode.
    • write :wq  in normal mode to write the file and exit

Option 2: This is what most people who use terminal regularly would likely do. They would use the echo  command, that just prints the passed text back on the screen and then redirect that output to a file, e.g. echo "text" > file

Step 7: Write a program that prints “Hello world!”

NB! Before continuing, remind yourself what is a file extension. What extension is used by C source code and what is used by programs!

Again use a command line text editor. We recommend Vim, as it supports C code, but you can use any other editor as well.

Once done, compile the program. Use -o hello  to specify the output (name of the program) as “hello”.

NB! Do not write the name of your source code file after -o. This will overwrite your source code!

Now run the test program that you downloaded from us. If everything was successful, it will create a new file with instructions.
Follow those instructions to complete the task.

Task 2: filtering logs and web home

In this task we will look at a tool that is widely used for digging through large amounts of data. We will also take a look at piping the standard output stream of one program into the standard input stream of another program. Lastly, we’ll do a quick introduction to your web home.

Input data

I’ve generated a file with someone random data that would simulate a log file from a robot. These kind of log files are typically extremely long. Usually we only look into them when something goes wrong and even then we are usually interested in only a fraction of what it contains.

Log file is at my web home: http://www.tud.ttu.ee/web/Risto.Heinsar/sensors.txt

Filtering data

To filter long text files we use a tool called grep . Grep is a pattern matching tool that will try to match entered the pattern and print all the lines containing it. Other lines will be skipped.

The patterns can be simple such as a single letter words or part of a string, e.g.  SENSOR , ERROR , firefox etc. In this case we would run the program as  grep pattern .

The patterns can also be more complex, containing regular expressions. To enable the use of regular expressions, we add a an argument -E  when executing. E.g.  grep -E sensor[1-3]:  will display us all the lines containing either  sensor1: , sensor2:  or sensor3: . Notice that the colon was also included in the pattern.

You can test your regular expressions here: https://regex101.com

Hint 1: You can grep the output of grep again – you don’t need to do everything with one execution if that is too difficult. Though you should definitely try!

Hint 2: the output of grep can be written to a file using output stream redirection.

Hint 3: You can also do regular expressions that include logical operations (e.g. one or the other).

Submitting the task (base and advanced)
  1. Decide whether you wish to solve the base or advanced task and solve it.
  2. Copy the resulting output file to your web home and figure out the public address of it
  3. Fill the following web form: https://forms.office.com/r/kb72jTqeXu

NB! If you have technical issues with the web home, let us know after filling out the form. Show us the location of your file and the addresses you tried.

Base task requiremets

Your task is to find all the lines in the file given by me which have the severity level of ERROR and which are related to the sensor number derived from your matricula number using the formula matricula % 10 .

Example:

Student code 123456IACB -> matricula 123456.
123456 % 6 is 6

So the output has to be about SENSOR6. Some examples:

The task can be solved either in one go or in parts – it’s up to you.

Write this output to a text file using stream redirection. The name of the created file should be your student_code.txt. E.g. if your student code is 123456IACB, then your file name should be called 123456iacb.txt.

Extra task requirements

Your task is to find all lines containing the severity level ERROR. The lines you are looking for should contain the sensors matricula % 10  and motor number matricula % 4 .

Example:

Student code 123456IACB, matricula 123456
123456 % 10 -> 6
123456 % 4 -> 0

This means we are looking for SENSOR6 and MOTOR0. Some examples of the lines:

The task can be solved either in one go or in parts – it’s up to you.

Write this output to a text file using stream redirection. The name of the created file should be your student_code.txt. E.g. if your student code is 123456IACB, then your file name should be called 123456iacb.txt.

Using the web drive

All students have their own web drive where they can hold and publish simple web pages and files. It’s the W drive. Copy the output of your filtered data to that drive.

More information on the web drive (Estonian only): https://taltech.atlassian.net/wiki/spaces/ITI/pages/38994529/li+pilase+veebikataloog+Online+student+directory

Copy the resulting file to your web drive. You can use cp  to copy files.

Now the file should be accessible under one of the following links:

  • http://www.tud.ttu.ee/web/uni-id/student_code.txt
  • http://www.tud.ttu.ee/web/Firstname.Lastname/student_code.txt

Now fill out the form!

Additional content

8. Standard streams

Lab material

Lab tasks

In this lab you have two tasks. Both of the tasks have an extra task available

Task 1: date validation

The purpose of this task is to check given numerical dates and check if the date is valid or not. In this task, we’ll also introduce stream redirection.

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

Requirements
  • The program checks each date and prints if it was a real date or not after it.
  • Limited year range: 1900 – 2099
  • The program implements leap year check
  • Must be able to verify 100 dates in a single run
  • Dates are given in DDMMYYYY format
  • For the base task, the functions must be implemented exactly as  they are described and structured in the base code.
  • When presenting your program for submission, you must use stream redirection. Input file to test with is also given on this page with the test dates.
Algorithm

The algorithm is showing a higher level view of the solution and is given for you as a guideline to solve the task. It doesn’t show the information exchange between functions. Due to separating the code out to functions you will notice that also the order of some operations will change as well as some logic will be written differently.

Ste-by-step guide

To start off, we should create a text file that will contain the inputs we would have otherwise typed in from the keyboard. This way we can write the test once and then use it each time after we change something in the program to test it quicker. Depending on the program structure, you may need to have multiple test files with different scenarios.

For this task we are able to only write one test file. We need to have both valid and invalid dates to make sure our algoritm detects them correctly. E.g. 11th of December 1981 would be a valid date, however 51st of December, month number 22 etc. will would not. In addition, you need to take extra care to test the edge cases – e.g. months 0, 1, 12, 13. Also testing days and months combined, e.g. 31st of December and 32nd of December. There is some additional complexity for leap years where the month of February can have either 28 or 29 days.

Here are your dates to test. Save it as a text file to the same directory as your source code and program! You’re allowed to add your own lines to the end.

Next you’ll need to make a program that will start to verify these dates.

Now let’s work with the starter code.

First two functions from it be done during the class. If you weren’t in the lab, check out the lecture recording!

From this point forward, we should have 2 files:

  1. Program code (e.g. date.c )
  2. Text file with the dates (e.g. input  or input.txt )

Next up we need to compile the program. One option would be to use Geany or any other IDE that you’ve used so far. You can do that if that’s what you feel the most comfortable with. Just don’t forget to recompile after changing the code!

Click me to see how to compile from command line

As an alternative, you can try to compile the code from the command line (that’s basically what happens when you press the build button anyway). The structure to do it yourself is compiler_name -o program_name source_code_file.cIt is important that -o is followed by the name of the desired program (output). In the end of the line we put the name of the source code file that we wrote. In addition we will also use flags to make sure that all the warnings are displayed – e.g. -Wall  and -Wextra .

Now lets put all this together. Once you are in the right directory with your command like, you can enter the following line:

gcc -o date -Wall -Wextra date.c

Using this like, the source code file date.c  will be compiled into a program called date .

Let’s verify that everything is where it should by by using the command ls -l :

Before we had 2 files, now we should have 3 of them:

  • date  – the so called binary file , that we produced by compiling our program. Can be executed.
  • date.c  – source code. This is the file we wrote our code in. Cannot be executed.
  • input.txt  – text file, that contains dates (test data).

Now we run the program so that instead of writing the input from the keyboard, it will be read from the file that we’ve composed (using the stream redirection). We need to use the following structure, but replace the names with the ones for our files  ./program_name < data_file

./program_name – this is how you can run a program in Linux console
< – a symbol denoting that the input stream will be redirected for this program
data_file – the file it will use to stream the input from

This is how the output will look like after we finish the part of the code done together and you will start your individual work

Testing: completed solution

After implementing the date validation, Your output should look something like this:

Task 2: Lottery

Start by downloading the starter code

Requirements
  • Lab task must be built on the starter code. It contains a list of functions with comments that you need to implement and use.
  • Lottery numbers can be from 1 to 25 (ends inclusive).
  • User is asked to enter 6 numbers
  • Computer will randomly generate 10 lottery numbers
  • Program will print out both the user and the randomly generated numbers
  • Check and show how many and which numbers matched (won)
    • There is no number uniqueness requirement for the base task
    • Every user number can win only once
  • If all numbers won, congratulate on jackpot. If none of the numbers won, give your condolences.
Testing

NB! The nature of a lottery is to be random, however testing this program without knowing that numbers to expect is not possible. Due to this, we will fix the random seed (srand function parameter) to be the same on every run. Then generate the lottery numbers once and remember them / write them down so you can test the program!

Test 1: Random numbers, some may win, no errors on input

Test 2: No winning numbers

Test 3: Jackpot

Test 4: Invalid user input

Test 5: Every user number can win only once (sanity check)

In this test, we will change the specification for the constants. This will help us test that every user number can only win once. This is also called a sanity check type of test.

NB! This test will only work if you haven’t yet solved the extra task where all numbers are checked to be unique. Repetition of numbers must be allowed for this!

After changing the constant, check for 2 things:

  1. How many numbers match! Should be  Matched 6 out of 6!)
  2. Check the numbers generated by the program. They can only be ones! (0 or 2 would mean that you have a mistake in the formula for limiting random numbers)

Extra task 1: reason for validation failure (date validation)

Lets improve our program to make it more clear why a date failed our validation.

Requirements
  • Extend your program in a way that it will give a reason for why the date didn’t validate
  • At minimum, you must be able to differentiate
    • Invalid year
    • Invalid month
    • Invalid day. You must differentiate between dates lower and higher than the allowed range for a specific month
    • Non-leap year 29th of February.
  • You are allowed to add functions and modify the existing structure of the program within reason.
  • Reminder! Avoid magical numbers! Define your constants
Testing

Extra task 2: unique numbers for lottery

By completing this task, you will make your program more realistic. For this we need to only solve 1 more function CheckIfNumInArray()  and start using it

Requirements
  • Enforce a requirement for the user entered numbers to be unique. If a user enters a number that they already entered before, immediately ask them for a different number.
  • Enforce the same requirement for the lottery machine.
  • Do not chagne the implementations of  GetUserNumbInRange()  and GenerateRandomNum()  functions. There is a better suited place for this.
  • Comment in and solve the function  CheckIfNumInArray() . You need to start using it in three different places
    • During user input to make sure that the values are unique
    • During generation of lottery numbers to make sure that they are unique
    • To count how many user numbers matched with the winning number in the function FindMatchCount()
Testing

Test 1: Check the uniqueness requirement for the user

NB! Use the exact same sequence to test!

Test 2: Check the uniqueness requirement for generated lottery numbers

To test the random numbers, we need to manipulate one of the constants

We will force the amount of numbers the computer is generating to be exactly as many unique numbers can be generated based on our lower and upper bounds for the numbers. We should get all numbers from 1 – 10 and none of them can repeat.

Think and answer the question: What would happen if we would have made the constant to be 9?

After the class, you should

  • Know which standard streams exist
  • Know how to use stream redirection on different platforms
  • Know how to execute the programs you create on Linux command line
  • Be able to use Boolean values
  • Be able to split up input
  • Know how to use the return value of scanf
  • Know how and when to omit curly braces. Also when not to.
  • Know what a dangling else statement is.
  • Be able to generate pseudo-random numbers
    • … within a specific range
    • … while fixing the seed for testing
    • … while making them dependent on the current time
  • Know the difference between pseudorandom and random
  • Know how UNIX time works and what’s the importance of 1st of January, 1970.

Additional content

10. lab: Menu-program

Theory and reminders

Characters, strings and output functions

Even though we will deep-dive into strings in a few weeks, lets take a look at a few things

Strings is a sequence of characters. It can be a word or a sentence, but also just a sequence of symbols. Strings are between double quotes.

Examples:

    • "a"
    • "Hello!"
    • "I do wish we could chat longer, but I'm having an old friend for dinner."
    • "lFRD=)m+0FDj2"

Characters are written in between single quotes. A string is composed of such characters.

NB! Symbols starting with a backslash are called escape sequences and they are stored as a single character in the computer memory (e.g.   \n  ).

Examples:

    • 'a'
    • 'y'
    • '\n'
    • '\t'

Now to some functions for text

printf()   – print formatted. This is the most complicated output function that we’ve looked at so far. We can use it to print text, format it and also output the contents of variables. Newlines must be manually written.

Example: printf("Hello, %s!\n", name); puts()  – put string. This is a simple output function used for printing text on separate lines. It does not support formatting and printing contents of variables. It however will print a newline after the text.

Example: puts("Hello, user!"); putchar()   – put character. This is the simplest output function out of them. It allows to print a single character only. It is good to use it for printing newlines for an example.

Example: putchar('\n');

Passing arrays to functions

When passing arrays to functions, we are actually passing a reference to the location of the original data. This means we can modify arrays in any function without returning.

Most of the time, you will need to also pass the size of the array in C. This is due to the fact that it will not be possible to calculate the size after it has been passed to a function! An exception would be strings, which we’ll discuss further later.

Some more tricks and specifics

  • If you want to pass the whole array, regardless of the number of dimensions, we only specify the name of the array Func(numbers);
  • If you wish to pass only a single value from a 1-dimensional array int numbers[N]; , we will specify the index of that member Func(numbers[2]); . In the function we will use it as a single integer Func(int val);
  • If you wish to pass the beginning of a row from a 2-dimensional array int numbers[N][M]; , we will specify the index of that row and the length of it Func(numbers[2], M); . In the function we will use it as a 1-dimensional array Func(int numbs[], int n);
  • If you wish to pass only a single value from a 2-dimensional array int numbers[N][M]; , we will specify both indexes  Func(numbers[2][1]); . In the function we will use it as a single integer Func(int val);

Swapping two values in an array

To swap to values, we can use a method we learned during bubble sort. For this, we need a temporary variable.

Note: to apply this swapping for a swapping of rows or columns, you only need a single variable.

It is only beneficial to use a temporary array instead of a variable if you can apply parallel operations on a SIMD (sing-instruction-multiple-data) type of architectures such as found in GPUs (graphics processing units).

Zero-initialising an array

To zero-initialize a whole array, we put the constant in curly braces.

If it is a 2-dimensional array, need two sets of curly braces.

Tasks

In this task we’ll create a menu-program where the user can choose when they want to exit. We’ll be working with matrix manipulations in this program.

To start off, try the sample program, after which you should continue to solve the task.

Sample program

You are given a sample of the program you will create within this lab task. It is given as a compiled binary – you can run and test it to take a look at what the final product should look ike. In the end, your program should work similarly.

Both versions of the sample program are compiled for x86-64 architecture. They are guaranteed to work on the lab computers, but should also work on most of your personal computers. There can be issues with ARM processors without using x86-64 emulation.

NB! On Linux you must give the permission to execute it manually (safety first!). Changing the permission is a one-time task.

This will add the execute permission for the user.

  • chmod – change mode
  • u – user
  • x – execute

After this you can run the program as usual ( ./program_name)

Task description

The lab task is separated into two separately graded parts, which can be continued by adding extra tasks.

The program should work until the user chooses to exit. This may require you to add additional checks for the state of the matrix.

The maximum size of the matrix in memory is defined using macros LIMIT_ROWS and LIMIT_COLS , which define the maximum row and column counts. Make sure to use the correct ones!

Since the user can choose to use less than the maximum matrix size, part of the matrix may be left unused. To account for this, all functions should keep track of how much of the matrix is in use. FOr this, you will see  int rows  and int cols  being used in some functions for the amount of rows and cols currently active.

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

General requirements

These requirements apply regardless of which part of the program you are presenting.

  • Your solution must mimic the sample program as close as possible
  • The work must be built on the starter code
    • You are allowed to modify the starter code within reason. E.g. it might be beneficial to reorder some statements in the main function or add another parameter to the function GetIntInRange() . For any other modifications, think hard if they are necessary or useful!
    • Starter code already has 2 functions made for you. Use them as needed in the parts that you will code on your own!
    • Starter code also has the prototypes of the first two functions that you need to create during the first part of the task.
  • All the numbers in the matrix must be randomly generated and from 0 – 99.
  • All actions must be repeatable without exiting the program.
  • All of the processing code for the menu actions must be created as functions
    • You are free to print out helping texts and prompts in the switch() itself, as well as accept returned values from functions. If necessary, you can also add some if statemens.
    • You are not allowed to add any new loops into the main() function!
  • The program must be consistent and clear for the user. It must work until the user chooses to exit.

Lab task part 1

In the first part, we’ll complete the generation and displaying of the matrix.

Requirements

  • Use can generate an n * m matrix.
    • Matrix will be populated with randomly generated numbers (0 – 99)
    • Values n and m are entered by the user. If necessary, create limits for user input.
    • You are only allowed to use do while()  loops in  GenerateMatrix() function.
    • Reminder! C functions are simple and only do one thing at a time (and do it well)! Function   GenerateMatrix() is not allowed to handle user input!
  • User can display a matrix
    • You are only allowed to use  while()  loops in DisplayMatrix() function.
    • Matrix must be nicely aligned.
  • User can exit the program

Lab task part 2

In the second part, we will create functions for swapping rows and columns.

Requirements:

  • User must be able to swap two rows.
    • You are only allowed to use for()  loops in the swapping function.
  • User must be able to swap two columns.

Common mistakes

  • Copy-pasting, also known as repetitive code. Mostly this will happen in the input part (e.g. number of rows, columns etc)
  • Off by one issues. As a reminder, first row index is 0.
  • Magical numbers
  • Allowing matrix operations before having a matrix. You cannot display a matrix that has not yet been generated!
  • Wrong loop types (part 1 and 2 have fixed loop types that you can use!).
  • Mixing up row and column counts. Try the following
    • generate a 3 x 5 matrix, swap rows 1 and 3
    • generate a 5 x 3 matrix, swap columns 1 and 3

Extra task 1: deletion

Add additional features to your program

  • User can delete a row that they desire.
  • User can delete a column that they desire.
  • After deleting a row, all rows following it will rise higher by 1. Similarly after deleing a column, all columns following it will move the the left by 1. The size of the matrix will shrink.
  • Add the required functionality to the menu.

Extra task 2: addition

Add additional features to your program

  • User can add a new row to the desired location.
  • User can add a new column to the desired location.
  • All elements for the added row / column will be generated randomly.
  • Any rows or columns after the desired location will move forward by 1. The size of the matrix increases.
  • Add the required functionality to the menu.

Extra task 3: transpose

Add additional features to your program

  • User can transpose the matrix.
  • Add the required functionality to the menu.

After this class, you should

  • Be able to create infinitely running menu-programs.
  • Know a few additional functions for text output.

Additional content

2. lab: conditional statements

Lab materials

Tasks

Task 1: cash register

With this task, we’ll go over a simple cash register application with the goal of trying to compose different conditional statements. Look for the comments in the base code and write the described lines of code after the comment!

Requirements:
  • Program must be logically identical to the given algorithm
  • Program must be built on the base code given. Your task is to add the missing printf , scanf ,conditional statements and calculations. Use the comments and the UML as a reference to where and what you need to write.
  • Don’t change the variable naming or the program structure.
  • Recommendation: To check that the values are correct and program behaves correctly, add printouts to check the values  in variables after operations. You can also check for entry into conditional statements.

Download task 1 basecode: [et] [en]

Algorithm

Testing

I’m proposing a series of tests for the program you are about to create. NB! I’ve left at least one important test case untested. Can you figure out which one?

Click me to see the test cases!

Test 1: Client is not offered any discount, successfully completes the payment. Also testing floating point values.

Test 2: Client has the loyalty card and gets an extra discount.

Test 3: Client has exactly the required amount of assets on their card.

Test 4: Client that is only able to afford the purchase after the discount.

Test 5: Client with not enough assets.

Test 6: Client, who does not know their PIN code.

Task 2: food scale

In this task you will have to create a program that simulates the food scale in a grocery store.

The UML activity diagram that the program will be structured upon is created in class. Your program must match or exceed the functionality described.

Requirements
  • You must have at least 4 products available.
  • Products are represented as pairs of product codes (integer) and names (e.g. 1 – banana).
  • You must handle matching the product code to the price of 1 kg in the switch  statement.
  • User will be displayed the total price only if a valid product code and weight are entered.
  • The given price(s) must be given with 2 decimal places.
  • Invalid product code and weight must trigger an error. There is no need to specify which error occurred. In case of an error, price must not be shown!

Download the base code for task 2: 2_2_scale_base.c

Testing

Test 1: Correct inputs will give us a total cost.

Test 2: Invalid product code triggers an error.
Test 3: Invalid weight triggers an error.

After the class, you should 

  • Know what is a truth table and how to read them
  • Be able to form conditional statements consisting of multiple conditions
  • Know what De Morgan’s law is
  • Know how to use inversion and short forms for conditional statements
  • Be able to initialize integers and floating point values when declaring them
  • Be able to nest code blocks in each other as done. Nest conditional statements.
  • Be able to use the same variable on both sides of the equal sign
  • Be able to use and print floating point values (simple cases)
  • Be able to use a switch statement
  • Be able to model a switch statement in UML
  • Know how to use swim lanes
  • Know how to create programs with multiple endings

Additional content

Command line arguments

Lab materials

Lab tasks

For this lab, you will have one main task with 2 advanced tasks that add extra functionality and features to the base task.

Lab task: calculator

For this task, you will build a calculator that works by getting its input from the command line

Requirements
  • You will create a simple calculator, that
    • can do addition, subtraction, multiplication and division
    • supports positive integers as operands
    • only does one operation at a time (e.g. 3 + 6)
  • Have a precision of 2 places after the comma
  • Both the operands and the operator will be given as command line arguments
    • E.g. an addition operation would look like this:
  • Program is not allowed to ask for any input during its execution
  • Your calculator must detect the following errors
    • Wrong argument count
    • Unknown operator
    • Non-numeric operand
    • Division by zero
  • When an error occurs, you will both present the specific error message and the guide how to use your program
Recommended list of functions
  • Display help
    • Shows how to use the program
  • Argument check
    • Checks for number of operands
    • In advanced, checks for --help  argument
  • Error management
    • Displays the specific error message
    • Calls the display help function
  • Operand check
    • Checks if the operand is numeric
    • Returns the operand converted to a number (e.g. int)
  • Calculation
    • Identifies the operation and calculates the answer
    • Returns the answer

You may also benefit from creating a function to check for the operator.

Example

To test a completed program, we recommend downloading the sample and seeing how it works.

To see all the test cases for the program, check the next paragraph.

Example 1: Input is OK and the program prints the answer

Example 2: Program is executed without arguments. An error message and a how to use guide is provided.

Test cases

Advanced task 1: real numbers

Change your program in a way that it would support all real numbers. You must add support for both negative numbers and numbers with decimal places.

Test the following

  • -3.3
  • 3-3
  • -3-3
  • 3.3.3

Advanced task 2: Extended functionality

Add the following functionality to your program

  • Taking a square root
  • Power function (xy)
  • Displaying help using the argument --help  without causing an error to occur.

All added functions must be present when help is shown.

After the class, you should be able to

  • Understand what a command line argument is
  • Know other programs that use command line arguments
  • Be able to accept command line arguments in C code
  • Know that main() function has multiple forms
    • Understand what argument count is
    • Understand what argument vector is
  • Know what is the first argument passed to a program
  • Know how argument count changes depending on how many arguments are passed
  • Understand that * and [] interchangeable
  • Understand what * means in the command prompt and how to pass such characters to programs
  • Understand how to pass multiple words as a single argument
  • Be able to convert strings into integers, floats

Additional content

8. lab: functions

Lab content

Lab tasks

Task 1: finding results from an array

The purpose of this task will be to create a program, that:

  • Reads 5 integers from the user that will be in between -100 and 100.
  • Prints the entered numbers out.
  • Finds and prints the arithmetic mean with 2 places after the comma.
  • Finds and prints the smallest member in the array.
  • Allows the user to enter a number and checks if it exists in the array or not.

The task has the following limitations (in addition to previous practices):

  • All of the functions described below will have to be implemented and used to find the results.
  • Constants defined using macros must be passed as a function parameter and not directly used in the functions.
  • If the function’s purpose is to find a results (e.g. arithmetic mean, smallest number, …), the result must be returned to main(). Side effects (printing the results within the functions) is not allowed.

Solve the program step-by-step. Test each function after creating it before proceeding. Avoid writing the code without functions at first! The functions given below are in the order we recommend writing them.

We have written a simple writeup on the parameters for each functions.  If you wish, you can add additional parameters to the second function (read array), but nothing else!

The writeup on the functions is simplified and allows the developer to make some decisions on their own. It is not enough to be used as a sample for homework 2!

1. function: reading an 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.

2. function: filling an array

Description: This functions reads n integers and stores them into the array. To use each integer, the previously completed function (reading an integer) is called. It is done repeatedly in a look for each array member that needs to be read.

Parameters:

  • integer array – the array that will be filled.
  • integer – array length.

Return: none.

3. function: printing an array

Description: Function prints values stored in the array.

Parameters:

  • integer array – the array that will be printed.
  • integer – array length.

Return: none.

4. 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: float – arithmetic mean.

5. 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.

6. function: check if value in array

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 / boolean – was the entered number present in the array or not.

Advanced: multiples of n to a new array

  • User enters a multiplier (positive integer)
  • Create a function that will create the 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 itself must not print out the new array nor call a function to do so.
  • The newly created array must be printed out. Use a function that already exists.

Task 2: Converting an existing code to use functions

Take the following code and split it into functions:
https://blue.pri.ee/ttu/files/iax0583/warehouse_kontaktope.c

Create the following functions, move the code from main to those functions:

  • Array print (without return, code reuse)
  • Print message about how much will fit (without return)
  • Sorting (without return)
  • Combining in sorting facility (returns number of items moved to the third array)
    Note: This function can work with code reuse (called twice), but doesn’t have to!

Advanced: weight limit

Create a limit for the cargo exiting the sorting facility.

E.g. a truck can deliver up to 1500 kg at once. Fill it with heavier items first. If some items don’t fit the limit, try if a lighter item will fit.

Print out the items that did fit on the truck and then fit separately the items that were left in the sorting facility.

After the class, you should

  • Understand what a function is
  • 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 divide your code to functions
  • Have a small list of universal functions that you can reuse in future codes!

Additional content

Week 7 Linux task

Download VIM configuration file
1. Go to your home directory

2. download the file

Decide on where to put your program(s) for this lab.
e.g. ~/P/IAX0583/ or something similar. Make sure that folder exist, if necessary create a new folder.
Use cd  to navigate, mkdir  to create a directory

Download the archived test program

You need to unzip the file
Use the program called unzip

You may need to manually make it executable
You use chmod  for this

Note: From this point on you can try to run the program provided. I recommend you try this out now! The program will stop when an unmet requirement is encountered.

Copy over an additional data file with the secret

Go to the M: folder (~/M/). Find your lecturer’s directory and go to it. In there you will find a hidden directory – go to it (it starts with a dot).

Inside you will find a .dat file. Copy that file over to the same folder as the test program. For this you will need to use the cp  command. Specify the file you want to copy and the path you want to copy it to.

To test if this worked, run the program and see if it finds the secret!

Next up you need to create a file with your matricula

For this, go back to the folder with your lab files. For this one, I’ll provide two possible options.

Option 1: Open up your favourable command line text editor, write a file called “matricula”

Vim guide:

    • Start by writing vim matricula  to create a file called matricula and open it in Vim.
    • Press ‘i’ to enter writing mode.
    • Now write your matricula.
    • Press ‘esc’ to exit write mode.
    • write :wq  in normal mode to write the file and exit

Option 2: This is what most people actually would do. They would use the echo command and redirect the output streamto a file, e.g. echo "text" > file

Write another program that will print out “Hello world!”

Again use a command line text editor. We recommend Vim, as it supports C code, but you can use any other editor as well.

Once done, compile the program. Use “-o hello” to specify the name of the program as “hello”

Now run the test program that you downloaded from us. If everything was successful, you get a new file with instructions.
Follow the instructions or if necessary, fix the mistakes.