DPST1091 Revision Arrays Sample Solutions
Revision Exercise: Filter a 1D array(●◌◌)
Download filter_list.c here
Or, copy these file(s) to your CSE account using the following command:
1091 fetch-activity filter_list
Your task is to write a program to find the number of bags from people over a specified height.
More specifically, your program should do the following.
- Scan in 5 pairs of height and number of bags, and store these pairs in an array of structs
- Ask the user for a minimum height to filter by
- Find the number of bags, from people who were greater than or equal to that height
This program has some starter code which includes the following struct.
struct passenger {
double height;
int num_bags;
};
The starter code also creates an array for you to store data in.
struct passenger my_array[SIZE];
Examples
dcc filter_list.c -o filter_list ./filter_list Enter height & number of bags: 150.0 1 Enter height & number of bags: 160.0 2 Enter height & number of bags: 170.0 3 Enter height & number of bags: 180.0 1 Enter height & number of bags: 190.0 2 Select height: 170.0 Total of 6 bags from people over 170.000000 ./filter_list Enter height & number of bags: 150.0 1 Enter height & number of bags: 160.0 1 Enter height & number of bags: 170.0 1 Enter height & number of bags: 180.0 1 Enter height & number of bags: 190.0 1 Select height: 200.0 Total of 0 bags from people over 200.000000
Assumptions/Restrictions/Clarifications
- Your program should match the output shown above exactly.
- You can assume you will always be given the correct data type during input.
- You can assume a height is always a positive and non-zero number.
- You can assume the number of bags is non-negative.
- Your program should still work when a person has no baggage.
When you think your program is working you can use autotest
to run some simple automated tests:
1091 autotest filter_list
filter_list.c
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
struct passenger {
double height;
int num_bags;
};
int main(void) {
struct passenger my_array[SIZE];
for(int i = 0; i < SIZE; i++) {
printf("Enter height & number of bags: ");
scanf("%lf %d", &my_array[i].height, &my_array[i].num_bags);
}
double filter_height;
printf("Select height: ");
scanf("%lf", &filter_height);
int count = 0;
for (int i = 0; i < SIZE; i++) {
if (my_array[i].height >= filter_height) {
count += my_array[i].num_bags;
}
}
printf("Total of %d bags from people over %lf\n", count, filter_height);
return 0;
}
Revision Exercise: Array Functions (●●●)
Download array_functions.c here
Or, copy these file(s) to your CSE account using the following command:
1091 fetch-activity array_functions
In this exercise, you'll be creating a small collection of functions that could help you with working on arrays.
Your task is to implement the missing functions in array_functions.c
and
implement the functions.
Some of these functions read through an array and return some information about the array but do not change the array in any way.
These functions are:
array_max
returns the maximum value in the array,array_min
returns the minimum value in the array,array_average
returns the average value in the array, andarray_sum
returns the sum of all values in the array.
Note: array_average
should return the greatest int
less than or equal to
the statistical mean of the array.
Some other functions change the array values or have an effect outside the program. We say that these functions have side effects as they do something other than just return a value.
These functions are:
array_add
; which adds a value to every element in the array,array_scale
; which multiplies every value in array by the same value, andscan_array
; which reads in values from input and stores them in the arrayshow_array
; which shows an array on the screen in the style[1, 2, 3, 4, 5, 6]
copy_array
; which copies one array into another
The file array_functions.c
contains a main function with some unit tests to
help you test your functions.
When you think your program is working you can use autotest
to run some simple automated tests:
1091 autotest array_functions
array_functions.c
// Some useful array functions
// Sample solution.
#include <assert.h>
#include <stdio.h>
#define SMALL_ARRAY 5
#define MEDIUM_ARRAY 20
#define LARGE_ARRAY 200
// Display useful facts about the array (changes the array).
void array_facts(int size, int array[]);
// Reading and showing arrays.
void scan_array(int size, int array[]);
void show_array(int size, int array[]);
// Array functions without side effects.
int array_max(int size, int array[]);
int array_min(int size, int array[]);
int array_sum(int size, int array[]);
int array_average(int size, int array[]);
// Changing the whole array.
void array_add(int size, int array[], int num);
void array_scale(int size, int array[], int num);
int main(int argc, char *argv[]) {
// Create an array with 5 elements.
int array_a[SMALL_ARRAY] = {1, 2, 3, 4, 5};
// Assert the min, max, and sum are what we expect.
assert(array_min(SMALL_ARRAY, array_a) == 1);
assert(array_max(SMALL_ARRAY, array_a) == 5);
assert(array_sum(SMALL_ARRAY, array_a) == 15);
assert(array_average(SMALL_ARRAY, array_a) == 3);
// Add 1 to all of the values in the array.
array_add(SMALL_ARRAY, array_a, 1);
// Check the min/max/sum/average again.
assert(array_min(SMALL_ARRAY, array_a) == 2);
assert(array_max(SMALL_ARRAY, array_a) == 6);
assert(array_sum(SMALL_ARRAY, array_a) == 20);
assert(array_average(SMALL_ARRAY, array_a) == 4);
// Create a medium-sized array to perform more unit tests.
int array_b[MEDIUM_ARRAY] = {0};
int b = 0;
while (b < MEDIUM_ARRAY) {
array_b[b] = b * b;
b = b + 1;
}
// Check that the min/max/sum/average are what we'd expect.
assert(array_min(MEDIUM_ARRAY, array_b) == 0);
assert(array_max(MEDIUM_ARRAY, array_b) == 361);
assert(array_sum(MEDIUM_ARRAY, array_b) == 2470);
assert(array_average(MEDIUM_ARRAY, array_b) == 123);
// Scale the array by -2, and then re-check the min/max/sum/average.
array_scale(MEDIUM_ARRAY, array_b, -2);
assert(array_min(MEDIUM_ARRAY, array_b) == -722);
assert(array_max(MEDIUM_ARRAY, array_b) == 0);
assert(array_sum(MEDIUM_ARRAY, array_b) == -4940);
assert(array_average(MEDIUM_ARRAY, array_b) == -247);
// Test an array with manual values
int manual_array[MEDIUM_ARRAY] = {0};
scan_array(MEDIUM_ARRAY, manual_array);
array_facts(MEDIUM_ARRAY, manual_array);
printf("All tests passed. You are Awesome!");
return 0;
}
// Display some useful facts about an array.
// NOTE: this will change the array that is used.
void array_facts(int size, int array[]) {
printf("The largest value in the array is %d\n",
array_max(size, array));
printf("The smallest value in the array is %d\n",
array_min(size, array));
printf("The sum of all values in the array is %d\n",
array_sum(size, array));
printf("The average value in the array is %d\n",
array_average(size, array));
int s = 0;
while (s < 5) {
printf("The array with %d added to all elements:\n", s);
array_add(size, array, s);
show_array(size, array);
s = s + 1;
}
printf("The array with 10 subtracted from all elements:\n");
array_add(size, array, -10);
show_array(size, array);
int m = 1;
while (m <= 5) {
printf("The array with all elements multiplied by %d:\n", m);
array_scale(size, array, m);
show_array(size, array);
m = m + 1;
}
}
// Read values from the screen, and store the values in an array.
void scan_array(int size, int array[]) {
printf("Enter %d numbers: ", size);
int i = 0;
while (i < size) {
scanf("%d", &array[i]);
i = i + 1;
}
}
// Show an array on the screen.
// This should look like [0, 1, 2, 3, 4, 5]
void show_array(int size, int array[]) {
printf("[");
int i = 0;
while (i < size) {
printf("%d", array[i]);
i = i + 1;
// Add the comma and space
if (i != size) {
printf(", ");
}
}
printf("]\n");
}
// Return the largest value in an array.
int array_max(int size, int array[]) {
int max = array[0];
int i = 0;
while (i < size) {
if (array[i] > max) {
max = array[i];
}
i = i + 1;
}
return max;
}
// Return the smallest value in the array.
int array_min(int size, int array[]) {
int min = array[0];
int i = 0;
while (i < size) {
if (array[i] < min) {
min = array[i];
}
i = i + 1;
}
return min;
}
// Return the sum of all values in the array.
int array_sum(int size, int array[]) {
int sum = 0;
int i = 0;
while (i < size) {
sum += array[i];
i = i + 1;
}
return sum;
}
// Return the average of all values in the array.
int array_average(int size, int array[]) {
return array_sum(size, array) / size;
}
// Add num to all values in the array.
void array_add(int size, int array[], int num) {
int i = 0;
while (i < size) {
array[i] += num;
i = i + 1;
}
}
// Multiply all values in the array by num.
void array_scale(int size, int array[], int num) {
int i = 0;
while (i < size) {
array[i] *= num;
i = i + 1;
}
}
Revision Exercise: Split sum (●●◌)
Download split_sum.c here
Or, copy these file(s) to your CSE account using the following command:
1091 fetch-activity split_sum
Your task is to add code to this function in split_sum.c:
/**
* The array is split into two parts by the index passed in so
* the first part has indexes until the index non-inclusive and
* the second part has indexes including the index till the end of the array.
* This function finds the sum of the first part and puts it into the first sum,
* and finds the sum of the second part and puts it into the second sum.
*
* Takes in
* the array "array",
* the array's length "length",
* the index that splits the array into two parts "index",
* a pointer to where the value of the first part of the array's sum should be
* placed "first_sum" and
* a pointer to where the value of the second part of the array's sum should be
* placed "second_sum".
*
* Returns nothing.
*/
void split_sum(int array[], int length, int index, int *first_sum, int *second_sum) {
// TODO complete this function
return;
}
In this exercise you will be asked to sum two parts of an array and store the results at two given addresses.
You will implement the split_sum
function, which takes five arguments:
array
, length
, index
, first_sum
and second_sum
. You should sum the
array's values from the start of the array up to (but not including) the index
given and put the result into first_sum
, and then sum the array's values from
the index till the end of the array and put the result into second_sum
.
Examples
dcc split_sum.c -o split_sum ./split_sum Enter length: 3 Enter array values: 11 2 3 Enter index: 1 First sum: 11 Second sum: 5 ./split_sum Enter length: 6 Enter array values: 1 2 3 4 5 6 Enter index: 4 First sum: 10 Second sum: 11 ./split_sum Enter length: 7 Enter array values: 12 45 24 57 10 8 12 Enter index: 2 First sum: 57 Second sum: 111
Assumptions/Restrictions/Clarifications
- You may assume the index given is between 0 and the length of the array inclusive.
- You may assume you always receive valid inputs.
- Hint: The sum of an empty array is 0.
When you think your program is working you can use autotest
to run some simple automated tests:
1091 autotest split_sum
split_sum.c
#include <stdio.h>
#define MAX_SIZE 100
/**
* The array is split into two parts by the index passed in so
* the first part has indexes until the index non-inclusive and
* the second part has indexes including the index till the end of the array.
* This function finds the sum of the first part and puts it into the first sum,
* and finds the sum of the second part and puts it into the second sum.
*
* Takes in
* the array "array",
* the array's length "length",
* the index that splits the array into two parts "index",
* a pointer to where the value of the first part of the array's sum should be
* placed "first_sum" and
* a pointer to where the value of the second part of the array's sum should be
* placed "second_sum".
*
* Returns nothing.
*/
void split_sum(int array[], int length, int index, int *first_sum, int *second_sum) {
// Gets the first sum of the array
int i = 0;
int sum = 0;
while (i < index) {
sum += array[i];
i += 1;
}
*first_sum = sum;
// Gets the second sum of the array
sum = 0;
while (i < length) {
sum += array[i];
i += 1;
}
*second_sum = sum;
return;
}
/**
* This is a simple main function that you can use to test your
* split_sum function.
* It will not be marked - only your split_sum function will be marked.
*
* Note: The autotest does not call this main function!
* It calls your split_sum function directly.
* Any changes that you make to this main function will not affect the autotests.
*/
int main(void) {
printf("Enter length: ");
int length;
scanf("%d", &length);
printf("Enter array values: ");
int i = 0;
int array[MAX_SIZE] = {0};
while (i < length) {
scanf("%d", &array[i]);
i += 1;
}
printf("Enter index: ");
int index;
scanf("%d", &index);
int first_sum;
int second_sum;
split_sum(array, length, index, &first_sum, &second_sum);
printf("First sum: %d\n", first_sum);
printf("Second sum: %d\n", second_sum);
return 0;
}
Revision Exercise: Reverse an array (●◌◌)
Write a C program, reverse_array.c
, which reads integers line by line, and
when it reaches the end of input, prints those integers in reverse order, line
by line.
You will never be given more than 100
integers to print out.
Examples
dcc reverse_array.c -o reverse_array ./reverse_array Enter numbers forwards: 10 50 20 40 Reversed: 40 20 50 10 ./reverse_array Enter numbers forwards: -5 -4 -3 -2 -1 Reversed: -1 -2 -3 -4 -5
When you think your program is working you can use autotest
to run some simple automated tests:
1091 autotest reverse_array
reverse_array.c
// A program to print a list of integers in reverse
// Written by Tom Kunc (t.kunc@unsw.edu.au)
// Created in 2019-06-23
#include <stdio.h>
#define MAX_NUMBERS 100
int main(void) {
int i = 0;
int did_scan_something = 0;
int scanned_value;
int scanned_numbers[MAX_NUMBERS];
printf("Enter numbers forwards:\n");
while (scanf("%d", &scanned_value) == 1) {
scanned_numbers[i] = scanned_value;
did_scan_something = 1;
i++;
}
printf("Reversed:\n");
while (i > 0 && did_scan_something) {
i--;
printf("%d\n", scanned_numbers[i]);
}
return 0;
}
Revision Exercise: Calculate the dot product of two arrays.(●●◌)
Download dot_product.c here
Or, copy these file(s) to your CSE account using the following command:
1091 fetch-activity dot_product
Your task is to add code to this function in dot_product.c:
// Calculates the dot product of two arrays of the same length.
//
// Parameters:
// `length`: the length of both arrays
// `vector1`: The first array
// `vector2`: The second array
//
// Returns: the dot product of `vector1` and `vector2`.
int dot_product(int length, int vector1[], int vector2[]) {
// TODO: Complete this function
}
This function takes in two arrays and returns their dot product.
To calculate the dot product of two arrays (v1
and v2
) of length n
we use
the formula
(v1 . v2) = v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2] + ... + v1[n - 1] * v2[n - 1]
For more information about the dot product see this link
Once your program is working, the output from the provided main function should be:
dcc -o dot_product dot_product.c ./dot_product Result: 106 Result2: -8
Assumptions/Restrictions/Clarifications
- Your program is not required to do any error checking
- You must not modify the arrays within the
dot_product
function. - Both arrays will be fully initialised
- You can assume length will be greater than 0
When you think your program is working you can use autotest
to run some simple automated tests:
1091 autotest dot_product
dot_product.c
// This program was written by YOUR-NAME-HERE (z5555555)
// on INSERT-DATE-HERE
#include <stdio.h>
int dot_product(int length, int vector1[], int vector2[]);
// This is a simple main function that you can use to test your array_sum_prod
// function.
// It will not be marked - only your function will be marked.
//
// Note: the autotest does not call this main function!
// It calls your function directly.
// Any changes that you make to this main function will not affect the autotests.
int main(void) {
//Feel free to modify any of these tests.
int test_vector1[] = {5, 10, 3};
int test_vector2[] = {5, 3, 17};
int test_vector3[] = {-5, 0, 1};
int result = dot_product(3, test_vector1, test_vector2);
printf("Result: %d\n", result);
int result2 = dot_product(3, test_vector2, test_vector3);
printf("Result2: %d\n", result2);
return 0;
}
// Calculates the dot product of two arrays of the same length.
//
// Parameters:
// `length`: the length of both arrays
// `vector1`: The first array
// `vector2`: The second array
//
// Returns: the dot product of `vector1` and `vector2`.
int dot_product(int length, int vector1[], int vector2[]) {
int result = 0;
for (int i = 0; i < length; i++) {
result += vector1[i] * vector2[i];
}
return result;
}
Revision Exercise: Return Common Elements Of Two Arrays (●●●)
Download common_elements.c here
Or, copy these file(s) to your CSE account using the following command:
1091 fetch-activity common_elements
Your task is to add code to this function in common_elements.c:
int common_elements(int length, int source1[length], int source2[length], int destination[length]) {
// PUT YOUR CODE HERE (you must change the next line!)
return 42;
}
common_elements
should copy the values in the first source array which are
also found in the second source array, into the third array.
In other words, all of the elements that appear in both of the source1
and
source2
should be copied to the third destination
array, in the order that
they appear in the first array.
common_elements
should return a single integer: the number of elements
copied to the destination array.
For example, if the source arrays contained the following 6 elements:
source1: 1, 4, 1, 5, 9, 2
source2: 1, 1, 8, 2, 5, 3
common_elements
should copy these 4 values to the destination array:
1, 1, 5, 2
The value 4 and 9 do not get copied because they do not occur in the second array.
common_elements
should return the integer 4, because there were 4 values
copied.
common_elements
should copy the elements in the order that they appear in the
first array.
If a value in the first array occurs one or more times in the second array, each occurrence of those values in the first array should be copied.
It doesn't matter how many times the values occur in the second array, as long as the values occur at least once.
For example. if the two arrays contained the following 5 elements:
source1: 1, 2, 3, 2, 1
source2: 1, 2, 3, 4, 5
Your function should copy all five values (1, 2, 3, 2, 1
) from source1
to
the destination array as all of the values (1, 2, 3
) appeared at least
once in source2
and it should return 5 because because 5 values were copied.
Assumptions/Restrictions/Clarifications
- You can assume the two source arrays contain only positive integers.
- You can assume that all three arrays are the same size (
length
) andlength
is> 0
. - You cannot assume anything about the number of common elements, i.e. there may not be any common elements between both arrays, or conversely, the entire contents of the first array may also be present in the second array.
common_elements
should return a single integercommon_elements
should not change the array it is givencommon_elements
should not call scanf (or getchar or fgets)common_elements
should not print anything. It should not call printf- Your submitted file may contain a main function. It will not be tested or marked
When you think your program is working you can use autotest
to run some simple automated tests:
1091 autotest common_elements
common_elements.c
int common_elements(int length, int source1[length], int source2[length], int destination[length]) {
int upto = 0;
int a1 = 0;
while (a1 < length) {
int found = 0;
int a2 = 0;
while (a2 < length && !found) {
if (source1[a1] == source2[a2]) {
found = 1;
}
a2 = a2 + 1;
}
if (found) {
destination[upto] = source1[a1];
upto = upto + 1;
}
a1 = a1 + 1;
}
return upto;
}
Revision Exercise: Count the big numbers in the array (●●◌)
Download count_bigger.c here
Or, copy these file(s) to your CSE account using the following command:
1091 fetch-activity count_bigger
Your task is to add code to this function in count_bigger.c:
// return the number of "bigger" values in an array (i.e. larger than 99
// or smaller than -99).
int count_bigger(int length, int array[]) {
// PUT YOUR CODE HERE (you must change the next line!)
return 42;
}
count_bigger
should return a single integer: the number of values in the
array which are larger than 99 or smaller than -99.
For example if the array contains these 8 elements:
141, 5, 92, 6, 535, -89, -752, -3
Your function should return 3
, because these 3
elements are
bigger than 99
or smaller than -99
:
141, 535, -752
Assumptions/Restrictions/Clarifications
count_bigger
should return a single integercount_bigger
should not change the array it is givencount_bigger
should not callscanf
(orgetchar
orfgets
)- You can assume the array contains at least one integer
count_bigger
should not print anything. It should not callprintf
- Your submitted file may contain a main function. It will not be tested or marked
When you think your program is working you can use autotest
to run some simple automated tests:
1091 autotest count_bigger
count_bigger.c
int count_bigger(int length, int array[length]) {
int bigger = 0;
int i = 0;
while (i < length) {
if (array[i] > 99 || array[i] < -99) {
bigger = bigger + 1;
}
i = i + 1;
}
return bigger;
}