Voluntary C programming exercises¶
On this page you can find old exercises so you can get extra practice in C if desired. TA's are still able to help with these exercises.
These exercises have no effect on course grading.
Basics of C¶
C-class energetic function¶
Let's write an energetic function as a warm up exercise. May the function be called
calculate_kinetic_energy. As input it takes two float parameters, the velocity and mass of an object. The function calculates the kinetic energy of the object and returns it as a floating point number. You can use the primary school strategy for calculating the exponentiations (velocity*velocity). Use the double data type for presenting the floating point numbers!Write a code file where this function is defined. Remember the prototype!
Hints
Messages
Give feedback on this content
Was this task useful for learning?
Comments about the task?
Repaircoder¶
Since interpreting messages - like many other things - gets easier by correcting errors, we offer you a wonderful opportunity to do just that. We have taken a fully working program (which solves a familiar problem) and broken it in fantastical ways! Your task is now to repair the code until it compiles without problems and also does what it was supposed to do originally.
You may have to check the original assignment to see what sort of pattern there was supposed to be so that you get one certain missing value in the code.
#include <stdio.h>
#include <math.h>
const double PI = 3.1416;
double calculate_square_area(double side);
double calculate_triangle_area(double side);
double calculate_sector_area(double radius, double angle);
float calculate_cathetus_length(float hypotenuse);
double calculate_square_area(double side) {
return pow(side, 2);
}
double calculate_triangle_area(double side) {
return pow(side, 2) / 2;
}
double calculate_sector_area(double radius, double angle) {
return PI * pow(radius, 2) * angle / 360;
}
double calculate_cathetus_length(double hypotenuse) {
return hypotenuse / sqrt(2);
}
double calculate_figure_area(double x) {
double square_1_area, square_2_area, triangle_area, sector_1_area, sector_2_area, triangle_side;
square_1_area = calculate_square_area(x);
triangle_side = calculate_cathetus_length(x);
triangle_area = calculate_triangle_area(triangle_side);
square_2_area = calculate_square_area(triangle_side * 2);
sector_1_area = calculate_sector_area(triangle_side, 45);
sector_2_area = calculate_sector_area(triangle_side * 2);
return square_1_area + square_2_area + triangle_area + sector_1_area + sector_2_area
}
int main() {
double x = 32.495;
printf("The area of the figure, when x is %f, is: %f\n", calculate_figure_area(x));
return 0;
}
Return your repaired code here.
Hints
Messages
Give feedback on this content
Was this task useful for learning?
Comments about the task?
Input and output¶
Class C of the Basic Printing School¶
Printing is not actually the most important thing on this course, but it is good to be able to handle the basics of it also. In this exercise you mainly practice choosing the right
placeholder
based on the type of the variable. The compiler
usually returns warning messages
about incorrect placeholders, but it still compiles the program through since it can be executed - the results just may be unexpected.Your task is to pick the piece of code below and add print outs so that each defined variable's contents are printed on their own line. Unlike Python's printf function, C's printf function does not automatically print line break at the end, so you have to add it there yourself - you do not need to add anything else to the print outs.
HUOM: Check that the last row includes also a new line character
int main() {
unsigned long n = 4000;
unsigned short laskuri = 0;
char luokka = 'C';
float keskiarvo = 0.0;
}
Return the code file below. The code has to compile without warnings.
Hints
Messages
Give feedback on this content
Was this task useful for learning?
Comments about the task?
Pointers¶
Printing sensor values (1p)¶
The standard library function
printf isn't available for debugging in the SensorTag, but instead, for example, the sensor data has to be written to a character array, which in turn is passed on to a print function that print to the console window of the development. We will get back to this..To practice this, we shall make a function that writes the three axis of acceleration (x, y, and z), air pressure, and temperature to a given character array. The accelerometer values are always displayed as signed values (+/-), in the pressure only the whole number is displayed (decimals are not printed), and everything else is printed in two decimal precision.
Use the prototype, where str points to the output string.
void write_sensors(char *str, float ax, float ay, float az, float press, float temp);.So, with the following function call.
write_sensors(str, 0.2536, -5.3272, -1.3277776, 101325.273261, 27.721667);The output in parameter
str should look like this.+0.25,-5.33,-1.33,101325,27.72
Hint. You can print out the string in parts..
Hints
Messages
Give feedback on this content
Was this task useful for learning?
Comments about the task?
Parse string¶
Write a function that parses a string into substrings based on a given separator and locates the index of a substring that exactly matches to another given string.
The function prototype is the following:
int8_t parse(char *str, char *sep, char *arg);
Variable
str is the givne string, sep is the substring separator and arg is the string to be matched. The function returns -1, if a match is not found, othwerise it returns the index of matching substring (starting from zero). Example. The function parameters are string "Alpha,Bravo,Charlie,Delta", separator "," and matched string is "Charlie". The function returns 2.
Hint. It pays to use the existing functions in string.h library, for example function
strncmp is good for testing two strings.
Hints
Messages
Data structures¶
I2C-messaging¶
Let's get initially familiar with our embedded device. The SensorTag uses i2c protocol to communicate with the integrated sensors. The i2c-messages are defined using the following data structure.
struct i2c_message {
uint8_t sensorRegister;
uint8_t slaveAddress;
char *writeBuf;
uint8_t writeCount;
char *readBuf;
uint8_t readCount;
};
So, whenever we want to read sensor data values, we fill out the data structure with sensor parameters and buffers for sending and receiving messages. In this exercise the length of sent and received message is between 2-6 characters.
But, lets not worry about the details just yet. Lets write a function that prints out the contents of the filled data structure. The function prototyyppi is
void print_i2c(struct i2c_message *msg);.Example. The data structure is initialized followingly:
char txBuf[] = "ab",rxBuf[] = "cd";
struct i2c_message i2c;
i2c.sensorRegister = 0x01;
i2c.slaveAddress = 0x78;
i2c.writeBuf = txBuf;
i2c.writeCount = 2;
i2c.readBuf = rxBuf;
i2c.readCount = 2;
This message should be printed out as follows, by using hexadecimal number representation.
sensorRegister:01 slaveAddress:78 writeBuf:6162 readBuf:6364
Hints
Messages
Find MaxMin¶
Use the following data structures
struct point {
int x;
int y;
};
struct rect {
struct point max;
struct point min;
struct point all_points[10];
};
Write a function that finds, from members
all_points[10], minimum and maximum members, based on euclidean distance from origo in a space of (0,0)-(99,99) and stores these into members min ja max. Use function prototype
void find_maxmin(struct rect *box);Hint. Now the function argument is a pointer.
Hint. In the library math.h, you can find function sqrt() to calculate square roots.
Hint. In the library math.h, you can find function sqrt() to calculate square roots.
Hints
Messages
Give feedback on this content
Was this task useful for learning?
Comments about the task?
Struct scan (1p)¶
Let's start digging into data structures. So, write a function that checks whether an array value (of the given index) is larger than given threshold value. If the value is larger, then print out the whole array in CSV-format with two decimal accuracy. Otherwise, do not print anything.
Use the function prototype:
void scan(struct mpudata_t mpu, uint8_t index, float threshold);
.. and the data structure
struct mpudata_t {
float data[6];
};
Example.
struct mpudata_t values = { { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 } };
scan(values, 5, 3.21);
..printing out the CSV since with index=5 -> values[5]=6.0
which is larger than threshold 3.21:
1.0,2.0,3.0,4.0,5.00,6.00
Hints
Messages
Give feedback on this content
Was this task useful for learning?
Comments about the task?