Week 09 Laboratory Exercises

Objectives

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

Activities To Be Completed

The following is a list of all the activities available to complete this week...

Worth 0.7 mark(s) in total:

  • array_sum_prod
  • my_scanf
  • summation

Worth 0.7 mark(s) in total:

  • char_index
  • stellar_information

For your interest, but not for marks:

  • remove_repeated_lines

Lab Exercises are capped at 15 marks. Marks may be deducted from your weekly lab scores at the end of term if you have not actively participated in the group presentations during Lab sessions.

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 lab09_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 14 July 09:00 to obtain the marks for this lab exercise.

Exercise
(●◌◌)
:

My Scanf

Download my_scanf.c here

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

1091 fetch-activity my_scanf

Ben Briant has decided to learn how scanf() works, and to help with his understanding, he has decided to write his own simple scanf functions!

They are much simpler than a regular scanf, as they only allow for scanning in a single integer or a single double (depending on if my_scanf_int() or my_scanf_double() is being called) at a time.

Both of these functions should:

  • take in a pointer to a variable that we want to scan our value into,
  • read a value from the user (using regular scanf), then
  • set the value of the input to be the value read from the user.

Unfortunately, Ben got overwhelmed with all the pointer syntax (* and &), so decided to just avoid writing any of it! Your job is to put all the * and & in the correct spots in the code.

You will have to edit both the main() function, my_scanf_int() and my_scanf_double(), But you can't change any part of the code aside from adding * or &.

Examples

dcc my_scanf.c -o my_scanf
./my_scanf 
Enter the amount of study you need to do this week (in decimal): 7.5
Enter the number of days you have free: 3
You have on average 2.50 hour(s) each free day to do homework.

Testing

When testing your program, we are checking more than that it simply produces the correct output. We are also testing that the functions work correctly individually (by replacing your main function with one of our own).

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

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

1091 autotest my_scanf

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

give dp1091 lab09_my_scanf my_scanf.c
    

You must run give before Monday 14 July 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
(●◌◌)
:

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 lab09_summation summation.c
    

You must run give before Monday 14 July 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/25T2/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;
}
Start by copying your read_line code into the provided function stub.

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 lab09_char_index char_index.c
    

You must run give before Monday 14 July 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 lab09_stellar_information stellar_information.c
    

You must run give before Monday 14 July 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

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

give dp1091 lab09_remove_repeated_lines remove_repeated_lines.c
    

You must run give before Monday 14 July 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 — individual:
(Not For Marks) Debugging - concatenate

Download debug_concatenate.c here

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

1091 fetch-activity debug_concatenate

Note that this exercise is not marked or worth marks!

Debugging Tips!

Some debugging tips for you:

  • dcc output - as you run into issues, dcc will point you to where the errors are. Remember that dcc gives you the line number the issue is on, and will give some sort of explanation. Make sure you read everything dcc gives you. Sometimes we get “errors carried forward”, so find your first error, fix that, then recompile.
  • print statements - sometimes it can be handy to see if the flow of your code puts you in the spot you expect it to be (ie. inside the right if statement, or going through a loop the correct amount of times). A quick way you can check this is by putting print statements in your code for testing purposes, like "the value of x is %d and y is %d". This lets you check that you got against what you expected.
  • DPST1091 debugging guide

The Task

This exercise concatenate the strings passed as command-line arguments excluding the filename. Currently it has some issues - it is your job to figure them out and fix the code. Additionally, think of ways you could refactor the starter code to produce a simpler solution.

Examples

dcc debug_concatenate.c -o debug_concatenate
./debug_concatenate A blue whales heartbeat can be heard over 2 miles away
Concatenated string: Abluewhalesheartbeatcanbeheardover2milesaway
./debug_concatenate The moon has moonquakes
Concatenated string: Themoonhasmoonquakes
./debug_concatenate Pigs cannot look up into the sky
Concatenated string: Pigscannotlookupintothesky
./debug_concatenate
Concatenated string: 

Clarifications

  • The maximum length of the resulting string is 1028 characters, including the null terminator.
You can run an automated code style checker using the following command:
1091 style debug_concatenate.c

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

1091 autotest debug_concatenate

Challenge Exercise — individual:
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

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

give dp1091 lab09_vector_best_permutation vector_best_permutation.c
    

You must run give before Monday 14 July 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.

Submission

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

You only need to do this if the exercise specifies a give command, otherwise - the exercise is not worth marks.

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 10 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.