All posts by risto

PR1EN5: Arrays

Lab content

Tasks

The task for this week is separated into two parts. First complete the first part and present your solution. Then improve your existing solution by solving the second part of the task and present the solution again. The base task can be extended by two extra task.

Task 1 part 1 [W05-1]: Finding extreme values

Part 1 will be solved as a UML activity diagram in the class. You will have to implement the algorithm as a program based on the starter code presented, following the logic of the algorithm. In part 1, you will have four functions besides main() !

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

Requirements
  • Part 1 must match the logic described in the UML activity diagram
  • You have to complete all 4 functions that are described in the starter code as comments and use them in your solution. You will need to also add missing parts like macros, variable declarations, function prototypes and function calls.
  • User will enter 6 numbers from the keyboard, which will be stored in an array.
  • The process of entering the numbers must be clear. You must show which number and out of many they are currently entering
  • You need to find and print the smallest number in the array. The smallest value needs to be found in a user-defined function, returned and printed in main().
  • You need to find and print the greatest number in the array. The greatest value needs to be found in a user-defined function, returned and printed in main().
  • You need to print out the original array. This must be done in a separate function.
Workflow guide

NB! For every function, first read the function comment to understand what the function does, which inputs are needed as parameters and what the result (return) has to be. Each function must be implemented below the comment.

  1. Start by completing ReadIntArray()  function given in the starter code. This is the first function after main() .
    You will need to write a loop that on each iteration, prints the prompt and then reads the value, storing it into the array.  There will be a very similar example done in the lab as live code.
  2. To test it, we need to call the function. For this, we need to declare the array in the main function and then call the function, passing it the array and its length.
    Assuming you have a macro called NUM_CNT  and an array called numbers , the function call will look like  ReadIntArray(numbers, NUM_CNT); Test and see if your reading code works.
  3. To validate our results, we should print what we got.  Complete the function PrintArray()  and call it from main() .  Note that this time you have to set the parameters and return value yourself.
  4. Now you have two more functions to complete. Both are specified as function comments in the starter code. Finish the functions, call them out and print the results.
    NB! The functions finding min and max values are not allowed to have side effects. Results must be printed in the main() function.
Testing

Test 1: min first, max last

Test 2: min last, max first

Test 3: Min value is negative. Both min and max are in the middle of the array.

Task 1 part 2 [W05-2]: positions and repetition count

In part 1 you found the extreme values from the array. In part 2, you need to find the positions of those values and how many times they occurred.

Requirements
  • Print all positions of the greatest value in the array. Printing must be done in a separate function, outside of main() .
  • Print all positions of the smallest value in the array. Printing must be done in a separate function, outside of main() .
  • Print how many occurrences the min and max value had. Results must be found in a separate function and printed out in main() .
  • Positions printed must match the way you asked the user for input!
  • Implement the two functions specified under Workflow Guide. Reuse the created functions for both min and max values.
Workflow guide

To solve this part of the task, you need to create two functions. Both functions are given to you as function comments. You will need to implement the functions based on the comment.

First function will be to print out all the positions of the array. To do this, you need to loop through the array and every time you find the  number you are searching for (e.g. min value), you need to print out the position you are currently at in the loop! So in total, the function will consist of a loop, a conditional statement and a print statement – that’s it!

You need to reuse this function for both min and max! Note that the text describing the results should be printed in main (i.e. “Min value position(s): “)

After implementing this function, check that the code works before proceeding to the next function!

The second function will be very similar to the first one. In this one, you need to count instead of print. Once finished, just return the result you counted and print it in main() .  There is no printing of the result in the function itself, i.e. function should have no side effects!

Testing

Test 1: only 1 occurrence of min and max

Test 2: Multiple occurrences of min and max

Extra task 1 [W05-3]: Statistics

In this extra task, we will calculate 3 more results from the data in the array.

Requirements

  • Implement 3 functions, that will find the sum, product and arithmetic
  • Calculating arithmetic mean should reuse the function to calculate sum so you wouldn’t copy-paste code
  • All 3 functions must use the array and the length of the array as their parameters
  • All functions must calculate the result and return the answer. Result must be printed out in main()
  • Display the arithmetic mean with 3 places after the comma
Testing

The biggest stumbling block in this task is getting the arithmetic mean correct. Let’s test it.

Extra task 2 [W05-4]: n numbers without VLA

To make the program a bit more useful, we’ll allow the user to enter the amount of numbers the program can work with.

NB! Even though most C compilers work with VLAs (variable length array), not all versions of the C standard define it as mandatory property of the C language. Depending on the compiler, it may fail to work.

In addition, there are also downsides to performance of VLAs, which make them less preferred in performance-oriented tasks. In short, VLAs translate to more complex assembly code which takes more CPU cycles to execute. In addition, if no other checks are performed, it is extremely easy to crash programs using VLAs (e.g. I want to enter 10 000 000 numbers).

Because of this, you are allowed to declare an array where the size is defined by another variable (e.g.  int numbers[numberCount]; , where numberCount  is a variable specified by the user during runtime). The universal solution based on the standard is by using dynamic memory allocation, but that is a topic for Programming 2.

For the purpose of this lab task, you will decide on a maximum size that the user can enter and use that as the upper bound. This means, that most likely there will be unused slots in the array. However since our program is small, this won’t cause us problems.

Note, that in general, use of VLAs is not forbidden in this course. The limitation is for this task.

Requirements
  • Allow the user to specify how many numbers they will be entering
  • Limit the program so that the user cannot enter a number greater than the size of the array defined.
  • Asking of the size from the user must be handled by a function you create for this task. The function will only be allowed to return if the input is within the specified limits.
    • Use parameters to specify the limits
    • The function you create should be reusable in other similar situations (but with different limits).
  • You can choose the “reasonable” size of the array yourself (e.g. 50 members).
  • Create error handling for situations where the user enters the array size which is either too big or small.
  • Usage of VLA (variable length array) is forbidden in this task!
  • NB! Make sure to update your coding style – variables cannot be written in the same style as macros!
Testing

Make sure to test the following

  • Minimal allowed number count.
  • Maximum allowed number count.
  • Number count that is different from the original task.

After the class, you should

  • Know how to perform type casting
  • Know about floating point precision and problems with it
  • Know how fixed point and floating point number representation works
  • Know about math library and how to use it, including how to set the compiler flag, if necessary
  • What an array is
  • How to declare an array
  • How to initialize arrays
  • How to index each member of the array
  • How to index through an array using loops
  • How to find the extreme values in an array
  • How to pass arrays to functions

Additional content

PR1EN3: Loops

Lab materials

Tasks

This lab has two base tasks for which you need to create a total of four separate programs. There are also two extra tasks, separate from the base tasks, that can be written as a single program.

Task 1 [W03-1]: Sum of 5 numbers

You are tasked with creating a program that will find the sum of five numbers entered by the user. The program must be created 3 times – one for each loop type. All 3 programs must do the exact same thing.

Requirements
  • Program asks the user for 5 integers
  • After every number, except the last one, the program prints the current subtotal
  • After the last number is entered, the program prints the final sum instead of the subtotal
  • Program must give a clear instructions to the user
  • You cannot have any magical numbers in your code
  • Design your program in a way that if you would need to do the same task for 10, 20 or even 1000 numbers, you will only need to change one number in your code. Test it before submitting – change that number to be 7 and see if your program still works and the output makes sense!
  • Create the same program using a while, do while and a for loop
Hints
  • Think carefully which variables you will need! Regardless of how many numbers you need to add up, the amount of variables should remain the same
  • It’s recommended to start counting loops from 0. This is because most things that are counted in the computer, start from 0. However you should display a number incremented by 1 to the user – non-developers usually count from 1.
    • (i + 1) takes the value if i and uses the incremented value in that place only. The incremented value is not stored and does not affect the program elsewhere.  E.g. printf("%d", i + 1);
    • Operations such as  i++, ++i, i += 1 and i = i + 1 store the updated value after incrementing (permanent).
Testing

This is the expected output of the program

Task 2 [W03-2]: Cash register with input validation

In this task, we will revisit the task from last week and add a few features to it. You can either use the provided starter code or your own solution from last week.

Download the lab task 2 starter code [optional]: https://blue.pri.ee/ttu/files/iax0583/aluskoodid/3_1_cashier_starter_loop.c

Requirements

You must add the following features to the program

1. Input validation for loyalty card and extra discount

  • Ask the user for input until either 0 or 1 is entered
  • For invalid input, print an error message
  • Recommendation: Use an exit-controlled loop.

2. PIN code can be entered up to 3 times

  • If the PIN code has been entered incorrectly for 3 times, write an error message and close the program.
  • If a correct PIN is entered within 3 attempts, check the balance and if possible, do the transaction.
  • Recommendation: Use an entry-controlled counting loop.
Testing

Extra tasks

Extra task 1 [W03-3]: Mario tower
  • Using nested loops, create a representation of the Mario stairs using the pound symbol. A total of 13 rows of steps.
  • Place an ASCII stick man on top of the stairs
  • The width of the top platform must be enough for the stick man to rest his feet comfortably
  • In the end of each row, show the number of blocks used for that row and the total number of used blocks until that moment
  • Alignment should be as shown in the example below
Extra task 2 [W03-4]: Mirrored tower with specified height
  • Ask the user for the width of the platform (range 7 -20 blocks)
  • The steps must be mirrored this time as is in the Mario game when approaching the castle.
  • The bottom-most step must start from the left edge of the terminal window, no spaces allowed before it.
Hints

After the class, you should

  • Know what steps need to be gone through to get from the source code that we write to a executable program
  • Know what is a #define macro and how it works
  • Know what is a magic number and how to handle them
  • Know about problems with non-initialized variables.
  • Use a switch statement.
  • Use all 3 types of loops for a specified number of iterations.
  • Know how to create a loop that runs infinitely
  • Know the increment/decrement operators.
  • Know the difference between loops that check the conditions before or after executing the loop body.
  • Be able to nest blocks of code (e.g. conditional statement inside of a loop, loop inside of a loop, …)
  • Know about two control statements: break and continue.
  • Know, that we DO NOT use goto statements.
  • Use expressions and constants as printf arguments.
  • Be able to model loops in UML

Additional content

PR1EN1: Hello world

Lab materials

Tasks

Most likely everything in this lab is completely new to you. Because of this, most of the lab we’ll be working together – lecturer shows things in front and you’ll follow along on your computer.

In the end of the lab, you’ll have one base task to complete and defend. Faster ones will also be able to complete and defend the extra task.

Task 1 [W01-1]: Parity check (base task)

Requirements
  • User is asked for and must be able to enter an integer
  • Program must prints the entered number
  • Program must print if the entered integer was odd or even

NB! In addition to functional requirements, the program  must also follow the style requirements. Most common errors are related to indentation (number of spaces from the left before the code), missing spaces surrounding operators (e.g. space before and after equal sign) and lack of empty lines to indicate different logical parts of the program.

Task background

Modulo division is widely used as a means of creating a checksum. E.g. it can be used to validate your Estonian ID code or bank card number.

In this task we are doing modulo 2 division – i.e. dividing the number by 2 and taking the remainder. This allows us to check if the number is odd or even. Parity check is one of the simplest ways to do error checking in data transfers – e.g. if the amount of bits in a data packet with the value ‘1’ is odd or even? This can be used to check if there was a data transmission error (though as said before, this will only catch extremely simple errors).

Pseudo code

Pseudo code is one way of describing algorithms. It uses similar structure to a program, but does not adhere to language specific rules such as syntax requirements. This means pseudo code is typically human readable without knowledge of programming.

Algorithm

The task is modeled together in a class, to show you some of the techniques around formatting the diagram – e.g. how to create a conditional statement, using right angles when creating control flows etc. For the sake of completeness of the task specification, we have also given one of the two possible forms of this algorithm in this page.

How to solve the task

When solving the task, follow both the algorithm and the code snippets provided on the slides. This task resembles a lego that needs to be assembled correctly.

  1. Start by creating a new file. Save it in a subdirectory for Programming course on your P drive using a   .c  file extension- e.g. paritycheck.c .
  2. Now write the template code from the last slide into your code file. We will be showing you this on the projector as well. Note that we have left a mistake in the template! You should immediately notice it if you try to compile the program at its current state. Fix the mistake before proceeding to work on the task. If necessary, look in your hello.c  program for a similar line – you should find a solution and explanation in the comment of your code.
  3. The next piece of the puzzle is the code structure for a conditional statement. Find how to find the conditional if/else statement from the slides and write the structure into your program. Don’t copy code – writing helps with your muscle memory. Make sure to pay attention to the indentation of the code and the space following the  if keyword. Poorly formatted code will not pass the defense.
  4. Third piece of the puzzle is the condition itself (goes within the parenthesis for the  if  statement. Just as a reminder, the task is to check if an entered number is odd or even. Examples of conditions are provided on the slides. After creating the conditional statements, try to compile and make sure there are no errors!
  5. The last piece of the puzzle is the contents for the code blocks so that the result would be printed correctly. For this you need to write two calls to the  printf()  function. They should look something similar to the following code statement:
    Notice, that we left in two blanks. One of them needs to contain the number entered by the user. The second one whether it was an odd or an even number.
Testing

This program has two possible outcomes – the number is either even or odd. To test your program, you need to run the program twice, covering both of these tests.

Test 1: even number

Test 2: odd number

Everything worked as intended? Good, you are almost done!

Remember that the code has to be readable and maintainable. To achieve this, all programmers must adhere to coding style. Compare the look of your code to previous programs and examples from this class. Pay attention to

  • Use of spaces (before and after mathematical operators, after the if  keyword
  • Indentation – how many spaces must be left empty from the left of the text document on each line. Indentation by 1 is typically considered to be 1 tab or 4 spaces. The statements inside of a code block (indicated by the curly braces) always increase indentation by 1. This means that the code in the main function should be indented one (e.g. asking for input, reading input, return statement), but the printing of the result should be indented once more, because they are inside of another (nested) code block.
  • Use empty lines to visually separate different parts of code (before main()  function, before the if  statement, before the return statement)

Code both functional and readable? Now let us know that you want to defend your task!

Extra task [W01-2]: Division by 3 and 5

Before solving this task, solve the base task! You should first defend the base task and then the extra task.

Read on how to use logical operators: https://blue.pri.ee/ttu/coding-guides/conditional-statements/#Logical_operators

Requirements
  • User is asked for and must be able to enter an integer
  • Program must print whether the entered number is divisible by 3, divisible by 5, divisible by both or neither of them.
  • The program must find the multiples and remainders by dividing the number by both 3 and 5. All four results must be printed regardless of the divisibility.
  • Calculations (e.g. divisions) can only be done once. If you need to use the result multiple times in your code, store it in a variable.
Background

The task is based on a classical interview question used for recruiting software developers. This is a modified version of the FizzBuzz task.

Testing

Based on the divisibility checks, you have 4 possible outcomes that must all be tested.

Test 1: Number is divisible by both 3 and 5

Test 2: Number is divisible by 3 only

Figure the last 2 tests out on your own and make sure it works in all cases!

After this class, you should

  • Understand the requirements for this subject, including how to get a grade
  • Be able to log into Linux on the class computer
  • Know the main software we use in this class
  • Know your way around the environments – where to find what
  • Know what is the C programming language, how does the program structure look like and how to write a basic program.
  • Know the structure of a C program and be able to write, compile and execute a simple program.
  • Understand the basics of the following programming concepts.
    •  #include statements
    • why is main() function special
    • declaring variables, data types
    • print statements for basic text, changing line, printing the contents of a single or multiple variables with text and integer data types.
    • reading a value from keyboard and storing it in a variable (scanf statement)
    • basic math operations and how they are written
    • if/else statement (conditional statement)
    • Understand integer division and modulo division
  • Understand what an algorithm is
  • Understand what is UML and why it is used. Understanding the basic elements (start, end, action statement, fork, join) in the design. Being able to create a basic diagram in UML.

Additional content