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.
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.
Sample
1
2
3
4
5
6
7
8
9
10
11
12
13
Enter purchase total: 44.99
Did client present loyalty card?
1 - yes
0 - no
0
Apply extra discount?
1 - yes
0 - no
0
Invoice total: 44.99
Please enter card PIN code: 1234
Purchase complete!
New account balance is 55.01
Test 2: Client has the loyalty card and gets an extra discount.
Sample
1
2
3
4
5
6
7
8
9
10
11
12
13
Enter purchase total: 89.99
Did client present loyalty card?
1 - yes
0 - no
1
Apply extra discount?
1 - yes
0 - no
1
Invoice total: 71.99
Please enter card PIN code: 1234
Purchase complete!
New account balance is 28.01
Test 3: Client has exactly the required amount of assets on their card.
Sample
1
2
3
4
5
6
7
8
9
10
11
12
13
Enter purchase total: 100
Did client present loyalty card?
1 - yes
0 - no
0
Apply extra discount?
1 - yes
0 - no
0
Invoice total: 100.00
Please enter card PIN code: 1234
Purchase complete!
New account balance is 0.00
Test 4: Client that is only able to afford the purchase after the discount.
Sample
1
2
3
4
5
6
7
8
9
10
11
12
13
Enter purchase total: 105
Did client present loyalty card?
1 - yes
0 - no
1
Apply extra discount?
1 - yes
0 - no
0
Invoice total: 94.50
Please enter card PIN code: 1234
Purchase complete!
New account balance is 5.50
Test 5: Client with not enough assets.
Sample
1
2
3
4
5
6
7
8
9
10
11
12
Enter purchase total: 110
Did client present loyalty card?
1 - yes
0 - no
0
Apply extra discount?
1 - yes
0 - no
0
Invoice total: 110.00
Please enter card PIN code: 1234
Error! Not enough assets on the card!
Test 6: Client, who does not know their PIN code.
Sample
1
2
3
4
5
6
7
8
9
10
11
12
Enter purchase total: 50
Did client present loyalty card?
1 - yes
0 - no
1
Apply extra discount?
1 - yes
0 - no
1
Invoice total: 40.00
Please enter card PIN code: 9999
Error! Incorrect 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!
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
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!
Download VIM configuration file
1. Go to your home directory
1
cd ~
2. download the file
1
wget blue.pri.ee/.vimrc
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
1
wget blue.pri.ee/week7.zip
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.
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
Program must be executed using stream redirection
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Given matrix:
10 9 8 0 -10 8 5
7 6 9 1 -7 -9 4
-5 5 -5 5 -5 5 -5
8 7 6 5 4 3 2
1 2 3 4 5 6 7
-1 -2 -3 -4 -3 -2 -1
0 0 0 0 0 0 0
The sum of negative elements on the main diagonal is -7
The product of positive elements above the anti-diagonal is 36578304000
Greatest number on row 1 is 10
Greatest number on row 2 is 9
Greatest number on row 3 is 5
Greatest number on row 4 is 8
Greatest number on row 5 is 7
Greatest number on row 6 is -1
Greatest number on row 7 is 0
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.
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
Print out the floor plan just as regular matrix with all numbers. Do not try to adjust what’s printed yet.
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
Continue to interpret the other codes.
Now that the floorplan is printed, print out the row numbers on the side.
Ask the user for their preferred seat. Don’t forget to sanity check them!
The row index can be calculated in one step. Column index has to be adjusted for the missing seats.
Print out the indexes in the array data structure to validate that you got the correct position!
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
Many functions that otherwise seem generic and easily reusable, such as input functions or output functions, might have an issue that the text printed on the screen does not really work for us.
One way to handle this is what we did before – we printed the text separately and called the generic input/output function (such as read array, read number, print array etc). In general, this still remains my recommendation. This way you have less complexity that could otherwise hinder the reusability of this function.
However, as an alternative, I’ll give another idea. Let’s follow the basic principle of when to create a function – if you are copy-pasting code because you have a marginal difference between them, try to find a way to handle it using function parameters. This will now offer us a solution – we can pass the text we wish to print as a function parameter.
This works quite well if we want to give the user an input prompt on entering a value, such as an integer. It also can work reasonably well for printing an array with a label before it.
NB! Two additional important thoughts! Both of which we will talk in greater detail in the second part of this semester.
Text is an array, composed of individual character. Each character also has its own index.
As opposed to integer and float arrays, we do not need to pass the length of a text array to print it (we still need it for processing).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
include<stdio.h>
#define DEFINED_STRING "Passing by using a macro"
voidPrintPassedText(chartext[]);
intmain(void)
{
PrintPassedText("Passing by using a constant");
PrintPassedText(DEFINED_STRING);
charinputString[]="Passing by using a variable";
PrintPassedText(inputString);
}
voidPrintPassedText(chartext[])
{
/* To print double quotes, they need to be escaped first! */
printf("Text passed to this function: \"%s\"\n",text);
}
Theory nugget 2: Passing an array vs a member of an array
In the last lesson, we discussed how arrays behave with functions. Some key points
Arrays were passed as the reference to the location of the array.
We can manipulate arrays in functions. Modifications are persistent.
Array length needs to be passed to the function alongside the array
When passing an array to a function, we use the name of the array only, nothing else.
Additionally, as a reminder, when we put the square brackets after the name of the array in the middle of the code, we are indexing the said array.
This leads us to the following example, where we are highlighting passing an array to a function vs passing a member of the array to a function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#define ARR_LEN 5
voidPrintNum(intnum);
voidPrintIntArray(intarr[],intlen);
intmain(void)
{
intnums[ARR_LEN]={9,24,-2,3,25};
/* Passing an entire array */
PrintIntArray(nums,ARR_LEN);
/* Passing the second number in the array */
PrintNum(nums[1]);
/* Passing the fourth number in the array */
PrintNum(nums[3]);
}
voidPrintNum(intnum)
{
printf("Passed number: %d\n\n",num);
}
voidPrintIntArray(intarr[],intlen)
{
printf("Numbers are: ");
for(inti=0;i<len;i++)
{
printf("%d ",arr[i]);
}
printf("\n\n");
}
Tasks
In this class, you need to solve two tasks. Additional points are available for extra tasks.
The task extends the algorithm with additional functionality.
Algorithm
Requirements
Program must be based on the provided algorithm and extended based on the requirements.
The user is asked for 6 numbers, which are stored in an array.
A second array is created based on the rules set in the algorithm. In the algorithm, it’s referred to as the reordered array. In the task description, we will also refer to it as the algorithmically created array.
A third array is created, which will only contain numbers greater than zero. The length of the array might end up being smaller than the initial array.
After all 3 arrays are populated, they are printed out.
The program must contain a total of four functions. One to read the numbers, one to print an array, one to compose the array made of positive numbers and one to compose the array specified by the algorithm.
All functions for creating and printing of the arrays must be called from the
main() function.
Hints and recommendations
Start by completing the reading and printing of the array functions. Both of these you have done previously. Create the necessary array and reuse the functions you created last week. When copying the functions, don’t forget to copy the function comment!
Now lets create a function to make the algorithmically created array. First, create a new array that has the same length as the array where the numbers are entered in. Remember, you cannot return an array from a function. You need to declare this array in the
main() function and pass it to this function. To create the new array, follow the algorithm provided. Then print out the array you created. The code should look something similar once completed (names of functions and variables can be different).
If you feel that your main() function is starting to be overcrowded, the printed text can be passed with the function call. Look at the first theory nugget.
Now move on to the last function, where you need to create an array with only positive numbers. Most of it will look very similar to what you just did, just shorter as you don’t need to go through the array twice. Think carefully about how to get the length of the new array back to
main() function! This array will likely be shorter and have unused slots in the end. Once you have the length of this array, call the printing function from
main() to print out the third array.
Testing
In the first test, we’ll run through the most typical case for this program, where we have both positive and negative numbers as well as a zero.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Enter number 1 / 6: 6
Enter number 2 / 6: -9
Enter number 3 / 6: 3
Enter number 4 / 6: -12
Enter number 5 / 6: 0
Enter number 6 / 6: 4
The original array
6 -9 3 -12 0 4
The rearranged array
-9 -12 6 3 0 4
The positive number array
6 3 4
The program should should also account for the situation where no positive input values were given.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Enter number 1 / 6: -1
Enter number 2 / 6: -4
Enter number 3 / 6: -66
Enter number 4 / 6: -97
Enter number 5 / 6: -3
Enter number 6 / 6: -5
The original array
-1 -4 -66 -97 -3 -5
The rearranged array
-1 -4 -66 -97 -3 -5
The positive number array
Empty array
Lab task 2: Array indexing and comparisons
Read 5 integers from the keyboard
Ask user for two indexes.
Check that they are within the array bounds before proceeding. If needed, prompt the user again!
Numeration must be the same as when asking for input
Recommendation: Print the values corresponding to those indexes from the array for self-check
Using those two values you found, find the following results
Compare them, print out their relation to each other (e.g. is the first number smaller, greater or equal to the second)
Create a division operation. The operation must be formed in a way, that the dividend is always greater than the divisor. If needed, swap them around.
Division answer must be given as a real number. Display 1 place after the comma.
For this task, you need to create four functions. Functions are described for you in varying detail.
Functions to create
1. Reading the array. Reuse the code that you have done before. Copy it in with its comment.
2. Reading the index. For this, you need a new function. Let’s make it a generic and reusable function that you can use in the future – reading an integer in range. This way you can use it whenever you need one (i.e. from 0 to 5; from -10 to 10; etc). If you completed the extra task from last week, you will likely already have this function.
I’m proposing two ways to write this function. Pick the one that you prefer and implement it.
First version assumes that the question (what to enter) is presented to the user before this function is called.
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Description: Asks the user for an integer in between the given limits.
* Repeats until requirements are met and returns the number.
*
* Parameters: min - lower bound for the user input (inclusive)
* max - upper bound for the user input (inclusive)
*
* Return: number within the specified limits
*/
intGetIntInRange(intmin,intmax)
{
}
The second version will present the prompt to the user by the function itself. This requires the prompt to be passed to this function (theory nugget 1).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Description: Asks the user for an integer in between the given limits.
* Repeats until requirements are met and returns the number.
*
* Parameters: min - lower bound for the user input (inclusive)
* max - upper bound for the user input (inclusive)
* prompt - prompt for user input, printed before entry
*
* Return: number within the specified limits
*/
intGetIntInRange(intmin,intmax,charprompt[])
{
}
3. Comparison of values. For this function, you need to pass the two numbers you are comparing. You need to print both numbers and their relation to each other (which one is bigger or are they equal). Output should be using the format “a < b”, “a > b” or “a = b”
NB! To pass numbers to this function, look at the second nugget of information.
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Description: Compares the given values (val1 and val2) and prints
* results of the comparison (which is greater; or equal)
*
* Parameters: val1 - first value being compared
* val2 - second value being compared
*
* Return: -
*/
voidCompareValues(intval1,intval2)
{
}
4. Division. Similarly to the last function, this one also expects two values. Again, you need to do the comparison as the last time, but this time instead of printing the results, you need to choose the operands for the division operation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Description: Compares the given values (val1 and val2). Performs the
* division by dividing greater number with the smaller number.
* Both division operation and result are printed.
*
* Parameters: val1 - first value
* val2 - second value
*
* Return: -
*/
voidDivideValues(intval1,intval2)
{
}
Sample solution
NB! The sample has a visible debugging printout (starts with DEBUG). It’s recommended that you also do this to verify that you are indexing the array correctly. Once you are sure about your indexes and your code works, comment this out.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Enter number 1 / 5: 5
Enter number 2 / 5: -5
Enter number 3 / 5: 24
Enter number 4 / 5: 9
Enter number 5 / 5: 1
Enter first index: -5
Error! Index must be within 1 and 5!
Enter first index: -7
Error! Index must be within 1 and 5!
Enter first index: 0
Error! Index must be within 1 and 5!
Enter first index: 4
Enter second index: 3
9 < 24
24 / 9 = 2.7
Testing
This is a partial list of the suggested tests:
Try a normal scenario that shouldn’t cause any errors.
Try out of bounds indexes ( -10, 10). Test them both as the first and the second index.
Try the out of bounds indexes multiple times to make sure that the program wouldn’t continue unless the inputs are usable.
Try indexes on the edge cases. E.g.
If you count from 0 – 6, try -1, 0, 6, 7
If you count from 1 – 7, try 0, 1, 7, 8
Try all 3 different results for comparison (<, >, ==)
Try to divide by zero. NB! Dividing by 0 is undefined! Just doing the division by zero may crash the program or reset the entirecomputer (it’s common for controllers to completely reset themselves if this happens). You are not allowed to perform divisions by zero!
Extra task 1: non-recurrent numbers
This is a continuation of lab task #1.
Requirements
Task must be built on the same base as the base task. The functionality of the base task must remain the program.
Solution can include both advanced tasks.
Create a new array based on the entered numbers. The new array must be built in a way that only a single instance of each number can exist in it.
Create functions as seem suitable for solving this task.
Testing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Enter number 1 / 6: -5
Enter number 2 / 6: 3
Enter number 3 / 6: 9
Enter number 4 / 6: 3
Enter number 5 / 6: -5
Enter number 6 / 6: 5
The original array:
-5 3 9 3 -5 5
The rearranged array:
-5 -5 3 9 3 5
The positive number array:
3 9 3 5
The nonrecurrent array:
-5 3 9 5
Extra task 2: additive inverses
This is a continuation of lab task #1.
Requirements
Task must be built on the same base as the base task. The functionality of the base task must remain the program.
Solution can include both advanced tasks.
Find and display the additive inverses of the numbers in the array.
Same numbers can be used in a pair only once, regardless of their ordering or repetition count.
Create functions as seem suitable for solving this task.
Testing
Make sure that the pairs don’t repeat.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Enter number 1 / 6: 1
Enter number 2 / 6: 5
Enter number 3 / 6: -1
Enter number 4 / 6: -5
Enter number 5 / 6: 5
Enter number 6 / 6: 224
The original array
1 5 -1 -5 5 224
The rearranged array
-1 -5 1 5 5 224
The positive number array
1 5 5 224
The nonrecurrent array
1 5 -1 -5 224
Pairs: (-1, 1) (-5, 5)
After the class, you should
Know how to pass text (strings) into functions.
Know how and when to pass either the entire array or just a member from an array to a function.
Know and be able to compose and use arrays where not all members from the declared array are in use.
Be more comfortable indexing an array in other ways than from first to last element.
Be able to copy values from one array to another using two different indexes in the same loop.
The task for this week is separated into two parts. First finish the first part and present your solution. Then improve your existing solution by solving the second part and present the solution again. The base task can be extended by two extra task.
Task 1 part 1
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. In part 1, you will have 4 functions besides
main() !
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 to the user. You must show which number they are entering out of how many at all times (e.g. 3/6 would be 3rd number from 6 in total).
You need to find and print the smallest number in the array. The smallest value needs to be found in a separate function, returned and printed in main().
You need to find and print the greatest number in the array. The smallest value needs to be found in a separate 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 provided as parameters and what the result (return) has to be. Each function must be implemented below the comment.
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.
To test this, we need to call it out. 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.
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.
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! you are not allowed to print the results in the functions that find min and max values. Printing statement must be in the main() function!
Testing
Test 1: min first, max last
Sample 1: Min ind 0
1
2
3
4
5
6
7
8
9
10
11
12
Enter number 1 / 6: 1
Enter number 2 / 6: 2
Enter number 3 / 6: 3
Enter number 4 / 6: 4
Enter number 5 / 6: 5
Enter number 6 / 6: 6
Entered numbers:
1 2 3 4 5 6
Min value is 1
Max value is 6
Test 2: min last, max first
Sample 2: max is ind 0
1
2
3
4
5
6
7
8
9
10
11
12
Enter number 1 / 6: 6
Enter number 2 / 6: 5
Enter number 3 / 6: 4
Enter number 4 / 6: 3
Enter number 5 / 6: 2
Enter number 6 / 6: 1
Entered numbers:
6 5 4 3 2 1
Min value is 1
Max value is 6
Test 3: Min value is negative. Both min and max are in the middle of the array.
Sample 2: min and max in the middle
1
2
3
4
5
6
7
8
9
10
11
12
Enter number 1 / 6: 1
Enter number 2 / 6: 2
Enter number 3 / 6: 3
Enter number 4 / 6: 4
Enter number 5 / 6: -933
Enter number 6 / 6: 1
Entered numbers:
1 2 3 4 -933 1
Min value is -933
Max value is 4
Task 1 part 2
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 2 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 (i.e. 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): “)
1
2
3
4
5
6
7
8
9
10
/**
* Description: Prints all positions of val in the array. Shows positions
* (starting from 1), instead of indexes.
*
* Parameters: nums - values that are checked
* len - length of the array
* val - value for which the positions will be printed
*
* Return: -
*/
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!
1
2
3
4
5
6
7
8
9
/**
* Description: Counts the number of times val is present in the array
*
* Parameters: nums - values that are checked
* len - length of the array
* val - value to search for
*
* Return: number of times val occurred in array
*/
Testing
Test 1: only 1 occurrence of min and max
Sample: min and max single occurrence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Enter number 1 / 6: 10
Enter number 2 / 6: 11
Enter number 3 / 6: 12
Enter number 4 / 6: 13
Enter number 5 / 6: 14
Enter number 6 / 6: 15
Entered numbers:
10 11 12 13 14 15
Min value is 10
Min value position(s): 1
Min value occurred 1 time
Max value is 15
Max value position(s): 6
Max value occurred 1 time
Test 2: Multiple occurrences of min and max
Sample: min and max multiple occurrence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Enter number 1 / 6: 10
Enter number 2 / 6: 13
Enter number 3 / 6: 12
Enter number 4 / 6: 10
Enter number 5 / 6: 13
Enter number 6 / 6: 13
Entered numbers:
10 13 12 10 13 13
Min value is 10
Min value position(s): 1 4
Min value occurred 2 times
Max value is 13
Max value position(s): 2 5 6
Max value occurred 3 times
Extra task 1: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.
Sample: precision test for avg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Enter number 1 / 6: 1
Enter number 2 / 6: 1
Enter number 3 / 6: 1
Enter number 4 / 6: 1
Enter number 5 / 6: 1
Enter number 6 / 6: 3
Entered numbers:
1 1 1 1 1 3
Min value is 1
Min value position(s): 1 2 3 4 5
Min value occurred 5 times
Max value is 3
Max value position(s): 6
Max value occurred 1 time
Sum is 8
Product is 3
Arithmetic mean is 1.333
Extra task 2: 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 completely 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 (i.e. I want to enter 10 000 000 numbers).
Because of this, you will not be allowed to declare an array where the size is defined by another variable (e.g.
intnumbers[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 trouble.
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.
Sample: testing of user entered n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Enter number count (up to 50): 127
Error! Invalid number count!
Enter number count (up to 50): 3
Enter number 1 / 3: 5
Enter number 2 / 3: 1
Enter number 3 / 3: 2
Entered numbers:
5 1 2
Min value is 1
Min value position(s): 2
Min value occurred 1 time
Max value is 5
Max value position(s): 1
Max value occurred 1 time
Sum is 8
Product is 10
Arithmetic mean is 2.667
After the class, you should
Look into homework 1 requirements and go through the videos
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
This lab has two base tasks for which you need to create 5 programs in total and 2 extra tasks that can be written into a single program.
Task 1: 5-number sum
You are tasked with creating a program that will find the sum of 5 numbers which are 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 input, the program outputs the current sum.
After the last value is entered, the program outputs the final sum instead of the current sum.
Program must give a clear instructions for the user what is expected of them.
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.
Sample of expected result
Sample: 5-number sum
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
This program takes 5 numbers from the user and adds them up. Subtotal is shown after each addition until the last one.
Enter number 1 / 5
9
Subtotal 9
Enter number 2 / 5
3
Subtotal 12
Enter number 3 / 5
2
Subtotal 14
Enter number 4 / 5
1
Subtotal 15
Enter number 5 / 5
5
The final sum is 20
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 many other internals also rely on that number. However you should display a number incremented by 1 to the user – users 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 incrementation (permanent).
Task 2: cash register with loops
In this task we’ll revisit the task from last week and add a few features to it.
In this lab, most of the tasks are done together. Later in class, you will have one base task and one extra task to solve on your own.
Task 1: Parity check (base task)
Requirements
User is asked for and must be able to enter an integer.
Program outputs if the entered integer was odd or even.
Pseudo code
Pseudo code is one way of describing algorithms. It has a similar structure to a program, but does not adhere to language specific rules such as syntax requirements. The written “code” should be well structured, but remain human readable.
1
2
3
4
5
6
The user will enter an integer
If the entered number is even:
Print: „The entered number is even“
Else:
Print: „The entered number is odd“
End of program
Background
Modulo division is widely used as a means of creating a checksum. E.g. it can be used to validate your id code or bank card number to be valid.
In this task we are doing modulo 2 division – e.g. parity check. 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).
Testing
This program has 2 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
Sample 1: even integer test
1
2
3
Please enter an integer:
2
The number 2 is an even number.
Test 2: odd number
Sample 2: odd integer test
1
2
3
Please enter an integer:
19
The number 19 is an odd number.
If everything works as expected, make sure to present your task!
User is asked for and must be able to enter an integer.
Program must output whether the number is divisible by 3, divisible by 5, divisible by both or neither of them.
The program will find the multiples and remainders by dividing the number by both 3 and 5. All 4 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
Sample 1: divisible by both
1
2
3
4
Enter a number to check: 15
Divisible by both 3 and 5.
By dividing 15 with 3, we get 5 multiples of 3 and a remainder of 0.
By dividing 15 with 5, we get 3 multiples of 5 and a remainder of 0.
Test 2: Number is divisible by 3 only
Sample 2: divisible by 3 only
1
2
3
4
Enter a number to check: 27
Divisible by 3 only.
By dividing 27 with 3, we get 9 multiples of 3 and a remainder of 0.
By dividing 27 with 5, we get 5 multiples of 5 and a remainder of 2.
Figure the last 2 tests out on your own and make sure it works in all cases!
After the 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.
Why it’s so important that the algorithms are written in a way that everyone understands them the same way.
Youtube: Exact Instructions Challenge – THIS is why my kids hate me. | Josh Darnit https://www.youtube.com/watch?v=cDA3_5982h8