All posts by risto

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

Homework: age grouping

Your task is to create a program that will analyze the ages of guests for an event. As input, you will get an unknown number of age values until the user enters 0 as the age. At that point the input will stop and the output statistics will be printed.

Grouping requirements:

  • Everyone below 18 is a minor
  • Ages 18 and beyond will be put grouped with a step of 5 years (e.g. 18 – 22, 23 – 27 etc.)
  • Everyone whose age is above the previously defined groups will be grouped as elders.

Data structure

The counters for each group will be created as an array, where each array member is for one of the predefined groups. The size of the array is defined with the macro GROUPS .

  • Index GROUPS - 1  is for elders
  • Index GROUPS - 2  is for minors
  • Indexes from 0 to GROUPS - 3  are used for the rest of the age groups.
    I.e. index 0 is for ages 18 – 22; index 1 is for 23 – 27 etc.

Program requirements:

  • Grouping settings must be easily configurable by only adjusting macros.
    • Group count
    • Group stepping
    • Upper bound for minor group
  • The rest of the code must automatically adjust itself if any of the macros were altered.

Required functions

For this task, you should create at least 3 functions

  • To validate that the user input is within allowed and reasonable bounds
  • To find the group index that the age belongs to. Group index must be returned by this function and stored into idx  variable
  • To print the results

You can also make a 4th function to make the program even nicer by moving the infinite loop from main into a separate function handling the processing.

Program structure

We are giving you the generic structure for the program with the macros already in place. You need to use them in the final code.

The places where you should call your functions (the ones listed by “required functions” section)  are highlighted as comments.

Algorithm

We have modeled most of the algorithm for you that you need to implement. Some of the calculations we have left for you to figure out – e.g. how to find the end points for age ranges in the output and a little bit of the array indexing as well.

Sample

Here is a sample of the program and how it behaves. You can also see a debugging output – it is useful to sanity check yourself. You can print out even more data just to be sure. In this case it helps to identify which counter (array slot) was increased. In the final version you do not need to include the counter, but for development it is highly recommended.

NB! When testing that your code works, try to also change the GROUPS and GROUP_STEP macros and see if everything still calculates correctly.

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

Welcome to IAX00584 Programming 2 (spring 2021)

This page has been created for students of Risto Heinsar. The links to various environments may be specific to the classes taught by me. If you are taking this class with a different teacher, look for their materials!

The purpose of this document is to give you a starting point to get you going.

Table of contents:

Introduction

The homepage for my students is https://blue.pri.ee/ttu/ (you are on this page right now).

The first thing that you should do is watch the introduction video. The lecture recordings are stored in Echo360 environment. They are not public, so you will have to register an account to view them. I will provide 2 links:

  1. With this link you can register and access the entire Echo360 content of my lab: https://echo360.org.uk/section/d2e8d568-050a-48bc-8237-4fd1f83365ff/public
  2. With this link, you can only view the introduction without registering for Echo: https://echo360.org.uk/media/3cbd2f4a-2b99-4a52-b8a9-589e6a32bb1c/public

Start by watching the introduction. Get a feel for the subject and see if this fits for your curriculum and expectations.

Once you move forward from here, I expect that you are interested to continue under my supervision and will declare the subject to me.

Lab time

The lab time during the distance will be the official time on the timetable.

Once it will be possible to hold the labs in the classroom, we will do so. We intend to have 50% occupancy rate and thus have booked two classes next to each other, so half of you will be able to sit in the next room and get the information through the presentation equipment in the classroom.

Lab time during the distance learning has some advantages

  1. Me and my assistants will try to be available – in case you have a question or are having trouble with something, we can provide the answers quicker.
  2. We will try out BBB (Big Blue Button) for voice/video calls and screen sharing. This should also help with problem solving, as you can screen share easily what you are seeing, as well as we can show you how to do some specific process.

First week

We will start out slow with revision. This should give you the feel whether you are ready for this class or not. It will also show you if you need to revise something.

If the tasks seem hard, then you should definitely consider if you are ready for this class or not – it might require more studying than the average. Otherwise you are ready to continue.

For any questions, ask them through Mattermost.

Now I will provide you a checklist for the things to do on the first week. For students coming from the previous semester, some of this will already be done for you (e.g. software installation).

If you managed to get this far, you should be good for the week. From next week, we will start to introduce new topics!

 

2. lab: pointers

Lab content

 

After the class, you should be able to

  • Understand what a pointer is
  • Declare different types of pointers
  • Understand some of the use cases for pointers
  • Understand what a NULL pointer is
  • Understand the dereference and address operators
  • Understand why some variables when reading with scanf() required & and some didn’t
  • Find the address of any variable
  • Pass addresses of variables to functions (by reference)
  • Better understand the difference of passing arguments to functions by value and by reference (originally simplified as copy, original)
  • Understand how arrays are actually passed to functions and thus why we can alter them without any extra steps
  • Understand pointer arithmetics
  • Know what a memory address looks like
  • Understand that there are different width memory addresses and why  it is like that

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.

9. lab: matrices

Lab content

Lab tasks

This lab has two gradable tasks. Second task is extended by two extra tasks.

Task 1: Calculating various results from a matrix

In this task we’ll practice navigating a matrix and finding results from it.

The task is graded separately in 3 parts.  Look for “Graded parts” below.

To start, download the following files.

Note: the task must be shown with stream redirection with the provided data file in order to be accepted!

Requirements
  • You have been given a starter code and an input file to use
  • Program must be shown using stream redirection
  • Add the printout of the matrix
  • Find and print the following results
    • The sum of negative elements on the main diagonal
    • The product of positive elements above the anti-diagonal
    • The greatest value in every row
  • All values must be stored as integers. Data types such as float, double and such are not allowed.
  • If you want to use smaller or bigger data types than a 32-bit int, you must use it precisely (e.g. through inttypes.h ). Data types such as long  and long long  are not allowed.
  • The solution must be cross-platform. Formats such as %ld  and %lld  are not allowed.
  • You must complete at least the listed functions below under “required functions”.
Required functions

You need to have at least 5 user-defined functions created in your program. You are allowed to create more if it suits the purpose.

  • Reading the matrix. During the function, all values were be stored into your 2-dimensional array (matrix). This has been done for you.
  • Printing of the matrix. During the function, the matrix will be printed onto the screen as shown in the example below. Function has no return value. Prototype for it has been done for you.
  • Finding the sum of negative numbers from the main diagonal. Function returns the sum to main() function, where it will be printed. Side effects are forbidden! Prototype for it has been done for you.
    NB! Think carefully about which values need to be summed up and watch out for excess work. Check out the indexes where your values are and make sure that you only go through those and nothing else. E.g., going through the entire 49-member array only to add up 7 values is not ok. Imagine if this was a 1000 x 1000 matrix – in that case you would visit a million numbers only to find 1000 of them. This would make the useful work to be 0.1% (reduction in efficiency is exponential if you go through the entire array).
  • Finding the product of positive values that are positioned above the anti-diagonal. Function returns the product to main() function, where it will be printed. Side effects are forbidden.
  • Finding the greatest values in each row. This one is entirely up to you how to design. You can have side effects and print the results inside of this function. You can add some helper functions as needed as well.
Grading

The task has 3 graded parts, marked separately.

There are 2 requirements which must be completed regardless of which part you intend to present

  1. Program must be executed using stream redirection
  2. Matrix must be printed on the screen

Separately graded parts

  • Part 1: the sum of negative elements on the main diagonal
  • Part 2: the product of positive elements above the anti-diagonal
  • Part 3: the greatest value in every row
Hints
  • Look at how ReadMatrix()  is written. You can write the parameter list for your other functions based on this
  • Printing: Again, take inspiration from ReadMatrix()  function. This already has everything you need to go through all the positions. Now you just need to format the printout nicely. To figure out the line change, think of what is the purpose of inner and outer loops!
  • Part 1: Write the indexes that you need to sum up. Take a look at those indexes and think of how many variables (and loops) you even need to go through all of them!
  • Part 2: Remind yourself what happened during an integer overflow!
  • Part 3: You can pass a single row of a matrix into a function. For this, we will specify the index of the row we wish to pass as well as pass the length of that row. This way you can re-use a function that you’ve created previously. E.g. FindMaxValue(matrix[rowIndex], rowLength)
Testing

This include the answers expected from the given matrix.

Task 2: Cinema hall

We have been given a layout with the current bookings for a cinema hall. It is represented as a 2-dimensional array. Your task will be to correctly interpret the values to display the hall plan.

All seats in the hall are coded with the following integers:

  • 0 – the seat does not exist at this location
  • 1 – the seat is free
  • 2 – the seat is already booked

The array position 0, 0 corresponds with the top left seat of the movie hall.

Download the starter code with the hall plan here: https://blue.pri.ee/ttu/files/iax0583/aluskoodid/9_2_cinema_init.c

Requirements
  • Print the hall plan. Program’s output must match the one given in the sample
    • Row numbers are placed on the left side
    • All rows start with the seat number 1. You must account for missing seats (and not count them – look at the example)
    • Free seats are marked as seat numbers
    • Missing seats are marked as an upper case ‘X’ character
    • Seats that don’t exist are not depicted
    • The location of the screen is shown in the plan
  • Ask the user for a seat (row, seat number) and print if it is free or not.
  • At minimum, you should have 2 functions besides main. One for printing the plan, another for checking the availability of the chose seat. You are free to create more as you see fit.
Workflow recommendation
  1. Print out the floor plan just as regular matrix with all numbers. Do not try to adjust what’s printed yet.
  2. Start altering the output (interpreting the coded values in the array). Create a conditional statement to print “nothing” instead of the code that represents missing seats
  3. Continue to interpret the other codes.
  4. Now that the floorplan is printed, print out the row numbers on the side.
  5. Ask the user for their preferred seat. Don’t forget to sanity check them!
  6. The row index can be calculated in one step. Column index has to be adjusted for the missing seats.
  7. Print out the indexes in the array data structure to validate that you got the correct position! 
  8. Now finish the program.
Hints
  • The floor plan is flipped compared to the array indexes. It may help you to draw it out and write the indexes for the first and last row compared to the floorplan.
    • Row 14 has the row index of 0
    • Row 1 has the row index of 13
  • To figure out the seat number, use a separate counter
  • A really clean solution to handle such a coded integer is a switch()  statement.
Testing of the program and samples

NB! The sample also uses colors in code, your solution doesn’t have to (but can 🙂 )

We’ve added a small debugging line where we are showing the index of the array we are checking for seat availability. It’s recommended to add it to yours as well, as it will be easier to check for correctness of it.

Sample output after solving the base task:

Click me to see the image

Sample output after solving both extra tasks:

Open me to see the image

Extra task 1: n tickets

Lets add a feature so that the user can book multiple tickets with one purchase. Add this to the base task.

  • User is asked for the number of tickets required.
  • All of the seats offered must be in the same row, next to each other.
  • Use the entered seat position as the starting point for your search. The other seats can booked to the left or to the right of the chosen seat, including to both sides at the same time.
  • Display the offered seats

Extra task 2: confirmation

Lets add a confirmation before the seats are booked

  • You must have both the base task and extra task 1 completed and in the same program for this.
  • After giving the offer to book the seats, prompt the user a confirmation if the offered seats are OK.
  • If the user refuses the seats you offered or there were not enough seats available at the chosen location, allow them to choose again (both seat position and number of tickets)

Hint: There are 3 coded values in the initial matrix. If you wish, you can add them. As an alternative, you may just want to make a copy of the initial matrix.

After the class, you should

  • Be able to use various length integers in code, including a 64 bit integer in cross-platform compatible code.
  • Understand how integer overflows happen in code
  • Be able to visualize a two-dimensional array
  • Understand how to declare and index a two-dimensional array
  • Be able to index only a specific part out of that array (e.g. first row, last row, first three rows, second element from the third row etc.)
  • Understand and be able to use matrix diagonal properties
  • Be able to go through the array both row by row and column by column

Additional content

7. lab: Sorting

Lab materials

Tasks

This lab has one task which can be extended by 2 extra tasks.

Lab task: Bubble sort

In this lab task you will implement a bubble sorting algorithm that will sort an array of numbers entered by the user.

Requirements
  • User is asked for 5 integers, they are stored in an array.
  • Array is to be sorted using the bubble sort algorithm.
  • You must optimize the loops in such a way that it skips the redundant comparison operations – just as was shown in the slide! Make sure to optimize both the inner and the outer loop lengths.
  • Count and show how many times the numbers were compared by the algorithm. If you count exactly 10, the optimizations are likely correct.
  • Display the sorted array in an ascending order.
  • Display the sorted array in the descending order.
  • You are allowed to sort the array only once during the program! Displaying the numbers in the opposite order does not require sorting!
  • You are to create 4 functions within the base task (listed below)
  • Reminders!
    • Variables lowerCamelCase
    • Functions  UpperCamelCase
    • Macros  SCREAMING_SNAKE_CASE
    • Magical numbers must be replaced with macros
    • Array length must always be passed to the function

Answer the question: You can observe both the count of comparisons and swaps. Which one will be reduced by our optimization and why?

Create the following functions

Implement a total of 4 functions in your code

  • For reading the numbers
  • For sorting the array
  • Two functions for displaying the array
Hints
  • You can already start reusing the functions from last week. Copy the ones that suit this program over and adjust them as needed for this task. Then just add the function call.
  • Bubble sort is another one of those functions that you should keep in handy for the future. Just make sure to remove the counting part from the code – we typically don’t want side effects for our functions.
Test 1: Reverse order

This is the worst case scenario for bubble sort. All numbers are sorted in the opposite order to what they need to be.

Test 2: Random order

The order is randomized here. The number of comparisons remains the same. This may also trigger an edge case in some computer systems when an array bound is exceeded. NB! You should not assume this to be reliable, there are more specialized tools for that, however it may bring out some errors in some systems.

Extra task 1: further loop optimization

The algorithm used initially can be improved upon even further. Initial design doesn’t detect if the array gets sorted earlier. This can however be detected easily and the sorting process can be stopped.

  • If the array gets sorted earlier than the last iteration of the outer loop, stop the sorting. Avoid doing unnecessary work!
  • Hint: think of what statements are being executed in a situation where the array is still being sorted, that will no longer be executed once it is sorted. Detect it and stop the sorting.
  • During defense: explain which kind of data order benefits from this algorithm. Demonstrate that your algorithm indeed works!

Extra task 2: matrix sort

In this part you will jump a little bit ahead and have to familiarize yourself with 2-dimensional arrays.

  • Solve this task as a separate program. Use the original code as a template to build upon. Keep the original, you will need the functions later on!
  • You are permitted to solve this task without using functions as we haven’t covered passing 2-d arrays to functions.
  • Instead of a 1-d array, you will need to sort a 5 x 5 matrix.
  • Sorting is performed line-by-line (independently)
  • Matrix must be initialized. Use the following matrix as your test data.
Sorted matrix
Hint

Wish to use the sorting function that you just did within the base task? In C, you can pass rows of a matrix to a function (in reality it it’s a bit more complex, but it serves our purpose). Pass it to the sort function as follows:
SortArray(numbers[rowIndex], rowLength); This way your code will look a lot cleaner.

After the class

  • You should understand what a number base (radix) is
  • You should recognize the most common numbering systems, including binary and hexadecimal.
  • You should understand what’s the difference between a positional and non-positional numbering system.
  • You should know what a bit, a byte and a nibble are, as well as how many bits are there in a byte or in a nibble
  • You should understand basic conversion between bases (10 -> 2, 10 -> 16, 10 -> 8, 2 > 10, 2 -> 16, 16 -> 10, 16 -> 2, 8 -> 10)
  • You should be able to convert between any system positional numbering system and base 10 using the generic conversion algorithm.
  • You should understand what an integer overflow is, when it happens and how dangerous it can be
  • You should know that there are a lot of sorting algorithms out there and for a practical application, you need to pick the right one
  • You should understand, that optimization and faster hardware are important, however they will only have a limited effect compared to a faster algorithm
  • You should understand what a bubble sort is and be able to write and apply it

Additional content

Generic references

Integer overflow in real life