Week 08 Laboratory Exercises

Objectives

  • more pointers
  • using command line input
  • using structs and pointers

Activities To Be Completed

This lab is worth a total of 1.4 marks and consists of the following activities:

TypeActivitiesWeight
One-dot (●◌◌) array_sum_prod
summation
string_to_lower_args
15%
Two-dot (●●◌) char_index
stellar_information
15%
Three-dot (●●●) remove_repeated_lines
vector_best_permutation
Not worth marks
Group presentation presentation8
70%

Lab exercises are capped at 15 marks. For more details, see the course outline.

Exercise
(●◌◌)
:

Calculate both the sum and product of the values in an array

Download array_sum_prod.c here

Or, copy these file(s) to your CSE account using the following command:

1091 fetch-activity array_sum_prod

Your task is to add code to this function in array_sum_prod.c:

// Calculates the sum and product of the array nums.
// Actually modifies the  variables that *sum and *product are pointing to
void array_sum_prod(int length, int nums[length], int *sum, int *product) {
    // TODO: Complete this function
}

The above file array_sum_prod.c contains a function array_sum_prod, which should find the sum and the product of the values stored in the array. It should write these values into the integers referenced by the pointers in the input to the function.

Unfortunately, the provided function doesn't actually work. For this lab exercise, your task is to complete this function.

The file also contains a main function which you can use to help test your array_sum_prod function. It has two simple test cases.

This main function will not be marked -- you must write all of your code in the array_sum_prod function.

You may modify the main function if you wish (e.g. to add further tests), but only the array_sum_prod function will be marked.

Examples

dcc -o array_sum_prod array_sum_prod.c 
./array_sum_prod 
Sum: 20, Product: 360
Sum: 10, Product: 24

Assumptions/Restrictions/Clarifications

  • You will not be given an empty array as input, you can assume that you have at least 1 value.
You can run an automated code style checker using the following command:
1091 style array_sum_prod.c

When you think your program is working, you can use autotest to run some simple automated tests:

1091 autotest array_sum_prod

When you are finished working on this exercise, you and your lab partner must both submit your work by running give:

give dp1091 lab08_array_sum_prod array_sum_prod.c

Note, even though this is a pair exercise, you both must run give from your own account before Monday 16 March 09:00 to obtain the marks for this lab exercise.

Exercise
(●◌◌)
:

Summation

Write a C program summation.c that takes integers as command line arguments and calculates their sum.

Examples

dcc summation.c -o summation
./summation 1 2 3 4 5 6 7 8 9
Sum: 45
./summation -5 10 -15 20
Sum: 10
./summation 100
Sum: 100
./summation
Sum: 0

Assumptions/Restrictions/Clarifications

  • You may find the atoi() function in the C standard library (stdlib.h) useful.
  • You may assume that argv[0] will always be the program name and all subsequent elements will be integers.
You can run an automated code style checker using the following command:
1091 style summation.c

When you think your program is working, you can use autotest to run some simple automated tests:

1091 autotest summation

When you are finished working on this exercise, you must submit your work by running give:

give dp1091 lab08_summation summation.c

You must run give before Monday 16 March 09:00 to obtain the marks for this lab exercise. Note that this is an individual exercise, the work you submit with give must be entirely your own.

Exercise
(●◌◌)
:

Print out command line arguments in lower case

Write a C program, string_to_lower_args.c, which reads command line arguments then prints them out. When it prints out, it will convert all upper case letters to lower case.

Note: If there are any characters that are not Upper Case letters, they do not need to be converted.

Note: The apostrophe ' character causes problems when trying to print it out. There will be no tests using an ' in this activity.

The output from your program should look exactly like this:

dcc string_to_lower_args.c -o string_to_lower_args
./string_to_lower_args Hello World!
hello world!
./string_to_lower_args Its Over 9000!
its over 9000!
./string_to_lower_args KAMEHAMEHA
kamehameha

Need a Hint?

There's a way to decide if characters are upper case if they're between 'A' and 'Z'. They can then be treated as numbers to convert to lower case.

Otherwise, there is a C library called ctype.h that might have some useful functions!

You can run an automated code style checker using the following command:
1091 style string_to_lower_args.c

When you think your program is working, you can use autotest to run some simple automated tests:

1091 autotest string_to_lower_args

When you are finished working on this exercise, you must submit your work by running give:

give dp1091 lab08_string_to_lower_args string_to_lower_args.c

You must run give before Monday 16 March 09:00 to obtain the marks for this lab exercise. Note that this is an individual exercise, the work you submit with give must be entirely your own.

Exercise
(●●◌)
:

Find the first location of a character

You should make sure you have completed read_line before completing this task.

Download char_index.c here, or copy it to your CSE account using the following command:

cp -n /import/reed/A/dp1091/public_html/26T1/activities/char_index/char_index.c .

Your task is to add code to this function in char_index.c:

// Return the index of the first occurrence of
// character `c` in the string, or `NOT_IN_STRING`
int char_index(char c, char *string) {
    // Your code goes here!
    // Don't forget to return your result.
    return 0;
}

Note char_index takes a character and a string and should return the index (position) of the first appearance of the character in the string.

If the character doesn't appear in the string, char_index should return the value NOT_IN_STRING which has been already #defined for you.

char_index.c also contains a simple main function to help you test your char_index function.

// DO NOT CHANGE THIS MAIN FUNCTION
int main(int argc, char *argv[]) {
    // Declare a buffer
    char buffer[BUFFER_LENGTH] = {0};

    // Read in a line...
    printf("Enter a line: ");
    read_line(BUFFER_LENGTH, buffer);

    // Get a character
    printf("Enter a character: ");
    char ch;
    if (scanf("%c", &ch) != 1) {
        printf("Character '%c' is not in the string.\n", ch);
        return 0;
    }

    // Find and print character index or "not in string"
    int index = char_index(ch, buffer);
    if (index == NOT_IN_STRING) {
        printf("Character '%c' is not in the string.\n", ch);
    } else {
        printf("Index of character '%c': %d\n", ch, index);
    }

    return 0;
}
This main function reads in a string and a character. Here is how char_index.c should behave after you add the correct code to the function char_index:
dcc char_index.c -o char_index
./char_index
Enter a line: Hello, world!
Enter a character: w
Index of character 'w': 7
./char_index
Enter a line: aaa
Enter a character: a
Index of character 'a': 0
./char_index
Enter a line: aaa
Enter a character: b
Character 'b' is not in the string.
You can run an automated code style checker using the following command:
1091 style char_index.c

When you think your program is working, you can use autotest to run some simple automated tests:

1091 autotest char_index

When you are finished working on this exercise, you must submit your work by running give:

give dp1091 lab08_char_index char_index.c

You must run give before Monday 16 March 09:00 to obtain the marks for this lab exercise. Note that this is an individual exercise, the work you submit with give must be entirely your own.

Exercise
(●●◌)
:

Stellar Information Capture

Download stellar_information.c here

Or, copy these file(s) to your CSE account using the following command:

1091 fetch-activity stellar_information

Write a C program stellar_information.c that simulates a star system in space. Each star in the system is represented by a structure containing its name, distance from Earth (in light-years), and spectral type. Your task is to initialize a pointer to a star structure, write a function to populate its fields, a function to calculate an estimate for the time it would take to travel from earth to the star and a function to print the star's information and the estimate for the time it would take to travel from earth to the star.

Task 1

Define a structure named star with the following fields:

  1. name: a string of size 50 to store the star's name.
  2. distance: a double to store the star's distance from Earth in light-years.
  3. spectral_type: a character to store the star's spectral type (e.g., O, B, A, F, G, K, M).

Task 2

Declare a pointer star_ptr to a star structure.

Task 3

Write the function called input_star_information() that prompts the user to enter the star's name, distance from Earth, and spectral type. Then store the input values in the respective fields of the structure pointed to by star_ptr.

Task 4

Write the function called time_travel() that, given a pointer to a star, calculates and returns the estimated travel time from Earth to the star based on star's distance. This calculation involves the following steps:

  1. Converting the stars distance from light-years to kilometers by multiplying the distance by the CONVERSION_CONSTANT that is defined at the top of your program.
  2. Dividing that previously calculated value by the LIGHT_SPEED constant which is defined at the top of your program.

Task 5

Write the function called print_star_information() that, given a pointer to a star, prints the star's information (name, distance, spectral type, and time travel).

Examples

dcc stellar_information.c -o stellar_information
./stellar_information
Enter the star's name: Sirius
Enter the star's distance from Earth (in light-years): 8.6
Enter the star's spectral type: A

Star's Information:
Name: Sirius
Distance: 8.600000 light-years
Spectral Type: A
Estimated travel time from Earth: 271403091.80 seconds
./stellar_information
Enter the star's name: Polaris
Enter the star's distance from Earth (in light-years): 323
Enter the star's spectral type: F

Star's Information:
Name: Polaris
Distance: 323.000000 light-years
Spectral Type: F
Estimated travel time from Earth: 10193395192.08 seconds
./stellar_information
Enter the star's name: Rigel
Enter the star's distance from Earth (in light-years): 864.3
Enter the star's spectral type: B

Star's Information:
Name: Rigel
Distance: 864.300000 light-years
Spectral Type: B
Estimated travel time from Earth: 27276010726.06 seconds

Assumptions/Restrictions/Clarifications

  • You may assume that valid input will always be given
  • You may find using %.2lf useful for printing the travel time value to two decimal places
You can run an automated code style checker using the following command:
1091 style stellar_information.c

When you think your program is working, you can use autotest to run some simple automated tests:

1091 autotest stellar_information

When you are finished working on this exercise, you must submit your work by running give:

give dp1091 lab08_stellar_information stellar_information.c

You must run give before Monday 16 March 09:00 to obtain the marks for this lab exercise. Note that this is an individual exercise, the work you submit with give must be entirely your own.

Exercise
(●●●)
:

Print only lines which have not been seen before

Write a C program remove_repeated_lines.c which reads lines and prints them unless it has seen exactly the same line previously.

In other words it doesn't print repeated lines. It prints our only the first occurrence of any line.

It should stop when it reaches the end of input.

For example:

dcc -o remove_repeated_lines remove_repeated_lines.c
./remove_repeated_lines
one
one
hello world
hello world
two
two
one
hello world
two
hello
hello

./remove_repeated_lines
Na, na, na, na, na
Na, na, na, na, na
Na, na, na
Na, na, na
Na, na, na, na, na
Na, na, na
Do, do, do, do, do,
Do, do, do, do, do,
Do, do, do
Do, do, do
Do, do, do, do, do,
Do, do, do


You can assume lines will contain at most 256 characters.

You assume at most 256 lines will be read before end-of-input.

You can assume lines are terminated with a newline ('\n') character,

You can run an automated code style checker using the following command:
1091 style remove_repeated_lines.c

When you think your program is working, you can use autotest to run some simple automated tests:

1091 autotest remove_repeated_lines

Exercise
(●●●)
:

Compute the Permutation Which Minimizes the Euclidean Distance Between Two Vectors

Write a program vector_best_permutation.c that:

  • reads a positive integer n
  • reads vector1 of n integers p0 p1 ... pn - 1
  • reads vector2 of n integers q0 q1 ... qn - 1
  • prints the permutation of vector1 that minimizes the Euclidean Distance with vector2
  • prints the Euclidean Distance between the permuted vector1 and vector2

Match the example output below EXACTLY:

dcc -o vector_best_permutation vector_best_permutation.c
./vector_best_permutation
Enter vector length: 4
Enter vector 1: 6 8 15 11
Enter vector 2: 42 43 17 3
Optimal permutation: 3 2 1 0
Euclidean distance = 42.836900
./vector_best_permutation
Enter vector length: 6
Enter vector 1: 18 16 19 11 42 32
Enter vector 2: 77 64 11 99 21 42
Optimal permutation: 5 2 3 4 1 0
Euclidean distance = 88.881944
./vector_best_permutation
Enter vector length: 32
Enter vector 1: 34 56 42 44 35 38 39 50 62 61 58 43 45 32 33 48 46 52 63 57 55 37 53 49 59 41 51 47 40 54 60 36
Enter vector 2: 23 30 13 16 14 33 25 41 15 32 35 26 28 40 31 38 39 11 19 21 37 18 27 12 36 17 24 34 22 20 10 29
Optimal permutation: 12 17 4 5 31 20 27 18 21 29 19 15 7 8 22 30 9 14 25 11 24 28 23 0 10 6 16 1 3 2 13 26
Euclidean distance = 124.450793

Assumptions/Restrictions/Clarifications.

The only C library functions you are permitted to use are printf, scanf and sqrt.

If there are multiple permutations of equal minimum Euclidean distance, you may print any of them.

You program must take less than 20 seconds to compute the answer on a CSE lab machine when compiled with dcc.

No error checking is necessary.

You can assume n is a positive integer less than 100.

You can assume you are given two vectors of n integers.

You can assume your input contains nothing but integers.

You may print an extra space at the end of the line when printing the permutation.

You can run an automated code style checker using the following command:
1091 style vector_best_permutation.c

When you think your program is working, you can use autotest to run some simple automated tests:

1091 autotest vector_best_permutation

In-Class Exercise — group:
Presentation

This week during lab class, you will be divided into small groups and assigned an activity from this week to give a short presentation on (2–5 minutes per group).

There is no give or autotest for the group presentation.

Submission

When you are finished each exercises make sure you submit your work by running give.

You can run give multiple times. Only your last submission will be marked.

Don't submit any exercises you haven't attempted.

If you are working at home, you may find it more convenient to upload your work via give's web interface.

Remember you have until Week 9 Monday 9:00am to submit your work.

You cannot obtain marks by e-mailing your code to tutors or lecturers.

You check the files you have submitted here.

Automarking will be run by the lecturer several days after the submission deadline, using test cases different to those autotest runs for you. (Hint: do your own testing as well as running autotest.)

After automarking is run by the lecturer you can view your results here. The resulting mark will also be available via give's web interface.

Lab Marks

When all components of a lab are automarked you should be able to view the the marks via give's web interface or by running this command on a CSE machine:

1091 classrun -sturec

Voice of the Student

✨ Help Us Improve Your Learning Experience ✨

Your feedback helps us understand what’s working well and what might need improvement. This quick, anonymous check-in has just two questions and takes less than a minute to complete.

Please answer honestly — your input makes a real difference.