Programming Fundamentals
Information
- This page contains additional revision exercises for week 04.
- These exercises are not compulsory, nor do they provide any marks in the course.
- You cannot submit any of these exercises, however autotests are available for them (Command included at bottom of each exercise).
Exercise
(●◌◌)
:
Print the Middle Integer of 3 Integers
Download middle3.c here
Or, copy these file(s) to your CSE account using the following command:
1511 fetch-activity middle3
Write a C program middle3.c
that reads 3 integers into a struct and prints
the middle integer.
You are not permitted to use loops or arrays (use if statements).
Examples
dcc middle3.c -o middle3 ./middle3 Enter integer: 23 Enter integer: 5 Enter integer: 27 Middle: 23 ./middle3 Enter integer: 3 Enter integer: 6 Enter integer: 27 Middle: 6 ./middle3 Enter integer: 9 Enter integer: 7 Enter integer: 8 Middle: 8
You can assume the user supplies 3 integers. You do not have to check the return value from scanf.
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest middle3
middle3.c
// Program to scan in three integers and print out the middle one.
#include <stdio.h>
struct numbers {
int first;
int second;
int third;
};
int main(void) {
// DO NOT CHANGE CODE BELOW HERE
struct numbers nums;
printf("Enter integer: ");
scanf("%d", &nums.first);
printf("Enter integer: ");
scanf("%d", &nums.second);
printf("Enter integer: ");
scanf("%d", &nums.third);
// DO NOT CHANGE CODE ABOVE HERE
// ADD CODE BELOW HERE
int middle = nums.first;
if (nums.first > nums.second) {
// third second first
if (nums.second > nums.third) {
middle = nums.second;
// second third first
} else if (nums.first > nums.third) {
middle = nums.third;
}
} else {
// first second third
if (nums.third > nums.second) {
middle = nums.second;
// first third second
} else if (nums.third > nums.first) {
middle = nums.third;
}
}
printf("Middle: %d\n", middle);
return 0;
}
Exercise
(●◌◌)
:
Loop Sum
Write a program called loop_sum.c
that reads an integer
n from standard input, and then scans in n integers from
standard input, adds them together, then prints the sum.
You can assume that n is non-negative (>= 0).
You can assume that you are given exactly n + 1 integers.
You can assume that scanf succeeds (you do not need to check for errors).
Make your program match the examples below exactly.
Note: you are not permitted to use an array in this exercise.
Examples
dcc loop_sum.c -o loop_sum ./loop_sum How many numbers: 2 1 2 The sum is: 3
How many numbers: 3 -3 4 13 The sum is: 14
How many numbers: 5 -2 -1 0 1 2 The sum is: 0
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest loop_sum
loop_sum.c
// Read numbers in a loop, and calculate their sum.
// A sample solution.
#include <stdio.h>
#include <stdlib.h>
int read_num(void);
int main(void) {
printf("How many numbers: ");
int amount = read_num();
int sum = 0;
int i = 0;
while (i < amount) {
sum += read_num();
i++;
}
printf("The sum is: %d\n", sum);
return 0;
}
// Note: you did not need to check that scanf succeeds for this exercise.
int read_num(void) {
int num;
if (scanf("%d", &num) != 1) {
printf("Could not read a number\n");
exit(EXIT_FAILURE);
}
return num;
}
Exercise
(●●◌)
:
Print an Hourglass
Write a program called hourglass.c
that prompts the user to enter
an integer n and prints an nxn pattern containing an hourglass. This
hourglass will be made up of *'s', all surrounded by hyphens "-".
Please enter a size: 9 ********* -*******- --*****-- ---***--- ----*---- ---***--- --*****-- -*******- *********
You can assume n is >= 3.
Make your program match the examples below exactly.
This exercise is designed to give you practice with while loops and if statements. Do not use arrays for this exercise!
Note: you are not permitted to use an array in this exercise.
Examples
dcc hourglass.c -o hourglass ./hourglass Please enter a size: 3 *** -*- *** ./hourglass Please enter a size: 6 ****** -****- --**-- --**-- -****- ****** ./hourglass Please enter a size: 7 ******* -*****- --***-- ---*--- --***-- -*****- ******* Please enter a size: 10 ********** -********- --******-- ---****--- ----**---- ----**---- ---****--- --******-- -********- ********** ./hourglass Please enter a size: 15 *************** -*************- --***********-- ---*********--- ----*******---- -----*****----- ------***------ -------*------- ------***------ -----*****----- ----*******---- ---*********--- --***********-- -*************- *************** ./hourglass Please enter a size: 25 ************************* -***********************- --*********************-- ---*******************--- ----*****************---- -----***************----- ------*************------ -------***********------- --------*********-------- ---------*******--------- ----------*****---------- -----------***----------- ------------*------------ -----------***----------- ----------*****---------- ---------*******--------- --------*********-------- -------***********------- ------*************------ -----***************----- ----*****************---- ---*******************--- --*********************-- -***********************- *************************
For this exercise, try and break the problem down into small parts and solve them individually.
When you think your program is working,
you can use autotest
to run some simple automated tests:
1511 autotest hourglass
hourglass.c
// Program to print out an hourglass shape given an
// input size.
// Written by Rory Golledge (June 2021)
#include <stdio.h>
int main(void) {
int input;
printf("Please enter a size: ");
scanf("%d", &input);
int row = 0;
while (row < input) {
int col = 0;
while (col < input) {
// Take care of Top-half triangle
if (row < input / 2) {
if (row <= col && row + col <= input - 1) {
printf("*");
} else {
printf("-");
}
}
// Take care of Bottom-half triangle
else {
if (row >= col && row + col >= input - 1) {
printf("*");
} else {
printf("-");
}
}
col++;
}
printf("\n");
row++;
}
return 0;
}
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:
1511 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:
1511 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;
}
Exercise
(●●●)
:
Array Functions
Download array_functions.c here
Or, copy these file(s) to your CSE account using the following command:
1511 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:
1511 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;
}
}
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:
1511 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:
1511 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;
}