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 may be available for some them (Command included at bottom of each exercise if applicable).

Exercise
(●◌◌)
:

Working with Enums (Revision Session Exercise)

Copy the file(s) for this exercise to your CSE account using the following command:

1511 fetch-revision 04

Write a C program enum_weekday.c that prompts the user to enter a day of the week for their tutorial as an integer and prints a message indicating the day.

Use an enum to represent the days of the week.

No autotests are provided for this question.

Examples

dcc enum_weekday.c -o enum_weekday
./enum_weekday
Please enter the day of the week your tutorial is on:
0: Monday
1: Tuesday
2: Wednesday
3: Thursday
4: Friday
5: Saturday
6: Sunday
0
Your tutorial is on Monday!
./enum_weekday
Please enter the day of the week your tutorial is on:
0: Monday
1: Tuesday
2: Wednesday
3: Thursday
4: Friday
5: Saturday
6: Sunday
3
Your tutorial is on Thursday!

Assumptions/Restrictions/Clarifications

  • You can assume the user supplies a valid integer between 0 and 6.
  • You do not have to check the return value from scanf.
Sample solution for enum_weekday.c
#include <stdio.h>

// start with constants, then move to enums
// #define MONDAY 0
// #define TUESDAY 1
// #define WEDNESDAY 2
// #define THURSDAY 3
// #define FRIDAY 4

// [TUTOR NOTE] Start off with constants for the days of the week
// [TUTOR NOTE] Since they are part of a set, we can link them together under the one enum, enum weekday
// [TUTOR NOTE] Create the enum,
// [TUTOR NOTE] Enums are of type int, and are similar to constants, but they are automatically assigned values.
// [TUTOR NOTE] Makes the code much easier to read & maintain
// [TUTOR NOTE] Demonstrate how they start at 0 but this can be edited (e.g. change to MONDAY = 1)
enum weekday {
	MONDAY,
	TUESDAY,
	WEDNESDAY,
	THURSDAY,
	FRIDAY,
	SATURDAY,
	SUNDAY
};

int main(void) {
	// [TUTOR NOTE] Change lecture to an enum, and declare & initialise one for tutorial (the scanned input).
	enum weekday lecture = MONDAY;
	
	// [TUTOR NOTE] Optional: fix up style by showing how to shorten a long printf() (also a common question)
	printf("Please enter the day of the week your tutorial is on:\n0: Monday\n1: Tuesday\n2: Wednesday\n4: Thursday\n5: Friday\n");
	int day;

	// [TUTOR NOTE] Explain that you cannot scan directly into an enum, and have to scan into an int first
	// [TUTOR NOTE] Emphasise the type is enum weekday (there’s usually a lot of confusion on the type & naming for enums & structs)
	scanf("%d", &day);

	enum weekday tutorial = day;

	if (tutorial == MONDAY) {
		printf("Your tutorial is on Monday!\n");
	} else if (tutorial == TUESDAY) {
		printf("Your tutorial is on Tuesday!\n");
	}

	return 0;
}

// [TUTOR NOTE] Ask for examples of other enum applications

Exercise
(●◌◌)
:

Working with Structs (Revision Session Exercise)

Copy the file(s) for this exercise to your CSE account using the following command:

1511 fetch-revision 04

Modify the given C program structs.c so that it initialises a struct representing a tutorial and then allows the user to update the time of the tutorial if it is scheduled on Tuesday.

Use an enum to represent the days of the week, and a struct to store details of the tutorial, including the day, time, stream, and number of students.

No autotests are provided for this question.

Examples

dcc struct_tutorial.c -o struct_tutorial
./struct_tutorial
Time: 15, Stream: A.
That time is full! Please enter a new time! 17
Your new time is: 17

Assumptions/Restrictions/Clarifications

  • You can assume the initial tutorial day is Tuesday, and the user will enter a valid integer for the new time if prompted. - You do not have to check the return value from scanf.
Sample solution for struct_tutorial.c
#include <stdio.h>

// [TUTOR NOTE] This includes the enum weekday from the enum exercise 
// 		- to keep things simple you can add the enum weekday in at the end, 
//		and leave it out for the initial struct explanation 
enum weekday {
	MONDAY,
	TUESDAY,
	WEDNESDAY,
	THURSDAY,
	FRIDAY,
	SATURDAY,
	SUNDAY
};

// [TUTOR NOTE] Explain that structs group different but related variables 
//		(of same or different types) into one structure
struct tutorial {
	enum weekday day;
	int time;
	char stream;
	int num_students;
};

int main(void) {
	// [TUTOR NOTE] Start off with variables
	// [TUTOR NOTE] Since these variables together make up the details for a 
	// 		tutorial, they’re perfect for a struct tutorial
	// [TUTOR NOTE] Create the struct tutorial

	// [TUTOR NOTE] Define & initialise a struct tutorial called my_tutorial instead of the variables, explaining the syntax
	struct tutorial my_tutorial;
	my_tutorial.day = TUESDAY;
	my_tutorial.time = 15;
	my_tutorial.stream = 'A';
	my_tutorial.num_students = 25;

	// [TUTOR NOTE] Ask students to help fix up the rest of the code
	printf("Time: %d, Stream: %c.\n", my_tutorial.time, my_tutorial.stream);

	if (my_tutorial.day == MONDAY) {
		printf("Your tutorial is on Monday!\n");
	} else if (my_tutorial.day == TUESDAY) {
		printf("That time is full! Please enter a new time! ");
		scanf("%d", &my_tutorial.time);

		printf("Your new time is: %d\n", my_tutorial.time);
	}

	return 0;
}

// [TUTOR NOTE] Ask for examples of other struct applications

Exercise
(●◌◌)
:

Working with While Loops (Revision Session Exercise)

Copy the file(s) for this exercise to your CSE account using the following command:

1511 fetch-revision 04

Write a C program while_grid_printer.c that performs the following tasks using while loops:

  1. Prints all numbers from 0 to SIZE (not inclusive) that are divisible by 2.
  2. Prints a SIZE * SIZE grid of 'X's.
  3. Prints a SIZE * SIZE grid where every odd column is 'O' and every other position is 'X'.
  4. Prints a SIZE * SIZE grid where the diagonals are 'O' and every other position is 'X'.

No autotests are provided for this question.

Examples

dcc while_grid_printer.c -o while_grid_printer
./while_grid_printer
Part 1:
0 2 4 6 8 
Part 2:
X X X X X X X X X X 
X X X X X X X X X X 
X X X X X X X X X X 
X X X X X X X X X X 
X X X X X X X X X X 
X X X X X X X X X X 
X X X X X X X X X X 
X X X X X X X X X X 
X X X X X X X X X X 
X X X X X X X X X X 
Part 3:
X O X O X O X O X O 
X O X O X O X O X O 
X O X O X O X O X O 
X O X O X O X O X O 
X O X O X O X O X O 
X O X O X O X O X O 
X O X O X O X O X O 
X O X O X O X O X O 
X O X O X O X O X O 
X O X O X O X O X O 
Part 4:
O X X X X X X X X O 
X O X X X X X X O X 
X X O X X X X O X X 
X X X O X X O X X X 
X X X X O O X X X X 
X X X X O O X X X X 
X X X O X X O X X X 
X X O X X X X O X X 
X O X X X X X X O X 
O X X X X X X X X O 
Sample solution for while_grid_printer.c
#include <stdio.h>

#define SIZE 10

// [TUTOR NOTE] Go through each scenario, taking suggestions. For the first 
//      couple explain the syntax of while loops. Diagrams/stepping through the 
//      code by hand will be helpful

int main(void) {
    printf("Part 1:\n");
    int count = 0;
    while (count < SIZE) {
        // print every number
        // printf("%d ", count);

        // print numbers divisible by 2
        if (count % 2 == 0) {
            printf("%d ", count);
        }
        count++;
    }
    printf("\n");

    // [TUTOR NOTE] Emphasise the importance of initialising row & col correctly, 
    //      as well as incrementing properly (show an infinite loop & how to stop them)
    printf("Part 2:\n");
    // print a SIZE * SIZE grid of X's.
    int row = 0;
    while (row < SIZE) {
        int col = 0;
        while (col < SIZE) {
            printf("X ");
            col++;
        }
        printf("\n");
        row++;
    }

    printf("Part 3:\n");
    // print every odd column as O's, every where else as X's.
    row = 0;
    while (row < SIZE) {
        int col = 0;
        while (col < SIZE) {
            if (col % 2 == 1) {
                printf("O ");
            } else {
                printf("X ");
            }
            col++;
        }
        printf("\n");
        row++;
    }

    // [TUTOR NOTE] The last one is not as important - it’s more problem solving 
    //      by that point than while loop logic
    printf("Part 4:\n");
    // print the diagonals as O's, everywhere else as X's.
    row = 0;
    while (row < SIZE) {
        int col = 0;
        while (col < SIZE) {
            if (row == col || row + col == SIZE - 1) {
                printf("O ");
            } else {
                printf("X ");
            }
            col++;
        }
        printf("\n");
        row++;
    }
}

Exercise
(●◌◌)
:

Scanning in Numbers Until Ctrl D (Revision Session Exercise)

Copy the file(s) for this exercise to your CSE account using the following command:

1511 fetch-revision 04

Write a C program number_scanner.c that performs the following tasks:

  1. Prompts the user to enter a number and prints the number.
  2. Creates a loop that repeatedly scans and prints a single number until the user hits CTRL + D.
  3. Creates a loop that repeatedly scans and prints two numbers until the user hits CTRL + D.

No autotests are provided for this question.

Examples

dcc number_scanner.c -o number_scanner
./number_scanner
Enter a number: 5
The number was 5
10
The number was 10
3
The number was 3

Assumptions/Restrictions/Clarifications

You can assume the user provides valid integers.

Sample solution for number_scanner.c
#include <stdio.h>

// [TUTOR NOTE] Hint that this will be helpful for this week’s labs devowel & cs_calculator

int main(void) {
    printf("Enter a number: ");
    int number;
    scanf("%d", &number);

    printf("The number was %d\n", number);

    // create a loop that scans 1 number repeatedly until the user hits CTRL + D
    // [TUTOR NOTE] Before creating a loop, explain that scanf() has a return 
    //      value, and that it is the number of items successfully scanned & stored
    // [TUTOR NOTE] Ask what they think scanf() returns when you enter a number, 
    //      a character, and CTRL + D
    // [TUTOR NOTE] Go through those inputs and explain them (can pull up the man 
    //      pages if they’re following along well/want more explanation)

    // [TUTOR NOTE] Create a loop to scan until CTRL + D the long way (using 
    //      scanf() return), then simplify so scanf() is in the while loop itself
    int scanf_return = scanf("%d", &number);
    while (scanf_return == 1) {
        printf("The number was %d\n", number);
        scanf_return = scanf("%d", &number);
    }

    // [TUTOR NOTE] Change the loop to scan in 2 numbers at a time instead 
    //      (so they can see 1 change to 2)
    
    // // final:
    // while (scanf("%d", &number) == 1) {
    //     printf("The number was %d\n", number);
    // }

    // // create a loop that scans 2 numbers repeatedly until the user hits CTRL + D
    // int number_2;
    // while (scanf("%d %d", &number, &number_2) == 2) {
    //     printf("The numbers were %d and %d\n", number, number_2);
    // }
}

// [TUTOR NOTE] If they are following along well, it’s a good opportunity to 
//      introduce the man pages with man scanf, especially showing the return value section

Exercise
(●●◌)
:

Guessing Card Game (Revision Session Exercise)

Copy the file(s) for this exercise to your CSE account using the following command:

1511 fetch-revision 04

Write a C program guessing_cards.c that implements a small guessing game where two players try to guess each other's card (number and suit). The game consists of five rounds, with each player having a turn to guess the other’s card in each round. Players score points based on correct guesses (1 point for guessing the number, 1 point for guessing the suit). The game ends if one or both players correctly guess the other’s card before five rounds are up, declaring the winner or a draw. If the game reaches five rounds without a correct guess, it prints the final score and declares the winner or a draw.

You should:

  • Use structs to represent a card and a player.
  • Use enums to represent the suits.
  • Write functions to initialise cards, update points, and print the final results.

No autotests are provided for this question.

Examples

dcc guessing_card.c -o guessing_card
./guessing_card
Player 1, please enter your card number & suit: 7 2
Player 2, please enter your card number & suit: 10 3

Round 1!
Player 1, please guess player 2's card: 9 9
Player 2, please guess player 1's card: 5 2
Player 1: 0, Player 2: 1

Round 2!
Player 1, please guess player 2's card: 10 3
Player 2, please guess player 1's card: 7 3
Player 1: 2, Player 2: 2
Game over! It's a draw!

Assumptions/Restictions/Clarifications

You can assume the user inputs valid card numbers and suits. You do not have to check the return value from scanf.

Sample solution for guessing_cards.c
// Solution to guessing_cards.c with functions

#include <stdio.h>

#define MAX_TURNS 5
#define TRUE 1
#define FALSE 0

// [TUTOR NOTE] This should be done after enums.c & structs.c, some extra practice
// [TUTOR NOTE] Hopefully the students should be able to take the lead on this one, 
//      so take suggestions from them
// [TUTOR NOTE] Involves: scanning into structs, altering a field in a struct, 
//      while loops (count & sentinel), if/else
// [TUTOR NOTE] After solving everything in main, can demonstrate moving similar 
//      sections into functions (in my solution I use 3 - initialise_card, update_points & print_end)

enum suit {
    DIAMOND,
    CLUB,
    HEART,
    SPADE
};

struct card {
    int number;
    enum suit suit;
    int points;
};

struct card initialise_card(int player_num);
struct card update_points(struct card p1,
                          struct card p2,
                          int num,
                          enum suit suit);
void print_end(struct card p1, struct card p2);

int main(void) {
    struct card player1 = initialise_card(1);
    struct card player2 = initialise_card(2);

    int turns = 0;
    int game_end = FALSE;
    while (turns < MAX_TURNS && !game_end) {
        printf("\nRound %d!\n", turns + 1);

        int number;
        int suit;
        printf("Player 1, please guess player 2's card: ");
        scanf("%d %d", &number, &suit);

        if (player2.number == number && player2.suit == suit) {
            game_end = TRUE;
        }
        player1 = update_points(player1, player2, number, suit);

        printf("Player 2, please guess player 1's card: ");
        scanf("%d %d", &number, &suit);

        if (player1.number == number && player1.suit == suit) {
            game_end = TRUE;
        }
        player2 = update_points(player2, player1, number, suit);

        printf("Player 1: %d, Player 2: %d\n", player1.points, player2.points);
        turns++;
    }

    print_end(player1, player2);

    return 0;
}

struct card initialise_card(int player_num) {
    struct card player;
    int suit;
    printf("Player %d, please enter your card number & suit: ", player_num);
    scanf("%d %d", &player.number, &suit);
    player.suit = suit;
    player.points = 0;
    return player;
}

struct card update_points(struct card p1,
                          struct card p2,
                          int num,
                          enum suit suit) {
    if (p2.number == num) {
        p1.points++;
    } 
    if (p2.suit == suit) {
        p1.points++;
    }
    return p1;
}

void print_end(struct card p1, struct card p2) {
    printf("Game over! ");
    if (p1.points == p2.points) {
        printf("It's a draw!\n");
    } else if (p1.points > p2.points) {
        printf("Player 1 wins!\n");
    } else {
        printf("Player 2 wins!\n");
    }
}

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
Sample solution for 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
Sample solution for 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
Sample solution for 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 integer
  • count_bigger should not change the array it is given
  • count_bigger should not call scanf (or getchar or fgets)
  • You can assume the array contains at least one integer
  • count_bigger 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 count_bigger
Sample solution for 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, and
  • array_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, and
  • scan_array; which reads in values from input and stores them in the array
  • show_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
Sample solution for 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) and length is &gt; 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 integer
  • common_elements should not change the array it is given
  • common_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
Sample solution for 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;
}