6CCE3RSC/7CCEMRTS
Coursework Primer
24th January 2022
This document provides you with (i) instructions for setting up a working environment to complete the first coursework assignment: Real-time Programming with pthreads, and (ii) a primer aimed ad refreshing your knowledge and skills in the ‘C’ programming language. You should read through the information contained here carefully, and make sure you are able to complete all the tasks before the cousework is released.
Copyright By PowCoder代写 加微信 powcoder
1 Getting Started
To enable flexible, remote working, you have each been provided with a Linux virtual machine (VM) suitable for real time programming. Your first task is to access your VM.
Take the following steps:
1. Open a browser and navigate to https://student-vms.nms.kcl.ac.uk/.
2. You should see a dashboard similar to the above. Click the Turn on button.
3. The VM will take a short time to turn on, at which point you will see the status change to On. An Open in browser button will appear. Click this.
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
4. A new tab will open, in which you should see the VM screen similar to above. Find the Activities menu at the top left.
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
5. Click on Activities menu at the top left and enter Terminal into the search box that appears. Hit return and a terminal window will open.
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
6. Click on Activities menu again and enter gedit into the search box that appears. Hit return and a text editor window will open.
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
7. Use your mouse to arrange the windows side-by-side. You are now ready to start programming.
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
Further instructions on how to access student VMs can be found here:
https://apps.nms.kcl.ac.uk/wiki/doku.php?id=computingsupport:services:student_vms:start&
rev=1632412361
It is recommended that you use either the browser interface (as detailed above) or ssh to access the VM. Remote desktop protocol has not been set up for these machines.
Important note that the machines are set with a limited run time of 7200 seconds, after which they will automatically shut down. Make sure you save your work regularly!
2 Using Linux
The key things that you need to be able to do are:
1. Open and use a terminal. Instructions are above. The terminal is a command line interface. That is, you type commands directly in this window. This is where you will compile and run your code. Some useful commands that you need to know are:
• ls this command lists the contents of (i.e., the files and subdirectories in) the current directory. • cd
• cp
• mkdir
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
• gcc
• ./
2. Open and/or create a new file in a text editor. Instructions are above. The text editor is where
you will view and edit your C code.
3 C Programming Primer
This primer is provided with the aim of refreshing your knowledge and skills in the ‘C’ programming language1. It is aimed at those with little programming experience, or for whom it has been some time since last doing any programming. It is not assessed, however, the basic skills it covers will be required for the module coursework. You should work through the exercises at your own pace, and complete the exercise in your own time. The following are brief notes: for further details about the syntax of more advanced commands, look at other sources for C programming under Linux (there are many books and websites on the subject). You can also use the module Yammer page to post any questions or problems about this to gain help from your peers/teaching staff.
3.1 Compiling C
The code for the C program (i.e., the bit that you write) lives in a file with the extension .c. This can be compiled into an executable using the gcc command whose syntax is as follows:
gcc file name.c [options]
There are various options that will be important. Running the command as is will generate an executable called a.out (typing ./a.out and then pressing return will run your program).
To name the executable something else you can use the -o option: gcc hello_world.c -o hello_world
Typing ./hello_world and then pressing return will then run your program.
Another important option that we will come across later is the library option: later we will need to use
commands that belong to the pthread library. To do this we would write: gcc hello_world.c -o hello_world -lpthread
As we go on we will come across other libraries of importance, such as the math library (-lm), which we need to include if we want to use things like sin(x).
Any compilation errors in your program will be displayed when you run gcc. For example, not including the math library when using a math function will give the following message:
Undefined first referenced Symbol in file sin file_name.o
ld: fatal: Symbol referencing errors. No output written to file_name
If you get an Undefined symbol message you should look at information for that function (e.g., sin) using the man command (e.g., man sin). The man pages will inform you what library to include.
1Note that, a basic knowledge of programming is considered a prerequisite for this course.
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
Exercise 1 Write and compile the following “Hello World” program. Use the text editor to input the following code:
#include
7 printf(“Hello␣World\n”); 8 return(0);
Save the code in a file named hello world.c and compile it with the command previously given.
Note that, C and the Linux command line are case sensitive.
3.2 Program Structure
Comments are enclosed by /* and */. Preprocessor Commands
The pre-processor acts on programs before the compiler. It acts on commands that have a # as the first character. Its main uses are to define various macros (or special tokens) and to include header files (which specify various functions).
For example, if we wished to use the sin(x) function we would need to include #include
• ctype.h – character classification and conversion.
• stddef.h – defines several common data type and macros.
• stdio.h – standard input and output to/from files, screen and keyboard. • stdlib.h – miscellaneous routines.
• string.h – character string manipulation functions.
• time.h – time functions.
Programs are normally split into sub-routines called functions. The command main() defines the main function. Other functions (such as printf) can be called from within this function.
Braces {, } mark the beginning and end of a block of code.
Note that, the code of the main function is enclosed by braces. All C programs have a main() function which defines the entry point into the program and controls general program flow. The void within the parentheses means that no values are passed to the program from the operating system.
The syntax for a function is as follows:
* This is the main program routine
int main(void)
type function_name (parameters) {
local variables; C Statements;
The statement terminator ; is used to end a statement. Return Value
Finally the command return(0); exits the main function, returning a value of 0 to the system or calling program (this value may be used in debugging). The int keyword preceding main() defines that the program returns an integer value.
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
Statements
3.3 Variables in C
Variables need to be declared in C at the beginning of the function in which they are used. A comma groups variables of the same data type. To declare a variable in C, do variable type variables, e.g.,
int i,j,k; float x,y,z; char ch;
// i, j and k are all integers
// x, y and z are all floating point numbers // ch is a char
Variablescanbegivenaninitialvaluewhenthevariableisdeclaredusingastatementsuchasint offset=32;. Global variables can be declared at the top of the program after the library and include directives. C has the following simple data types:
unsigned char
unsigned short int
Size (bytes) Minimum Value Maximum Value 1–
1 2 2 4 4 8
−231 − 1 −3.2 × 1032 −1.7 × 10302
−3.2 × 1032 −1.7 × 10302
Note that, there is no Boolean type in C: you can use char, int or unsigned char instead. 3.4 Basic Input/Output
Use your text editor to create a file welcome.c, and enter the following code into it:
2 * welcome.c * 3**
4 * Displays the users initials and the current year
5 * in a welcoming message
8 #include
10 int main(void)
12 char letter_1, letter_2, letter_3; /* 3 letters
13 int year; /* current year */
15 printf(“Enter␣your␣3-letter␣initials␣and␣press␣return:␣”);
16 scanf(“%c%c%c”, &letter_1, &letter_2, &letter_3);
17 printf(“Enter␣the␣current␣year␣and␣press␣return:␣”);
18 scanf(“%d”, &year);
19 printf(“Welcome ,␣%c%c%c.␣%d␣is␣a␣great␣year␣to␣study␣Real␣Time␣Systems!␣\n”,
20 letter_1, letter_2, letter_3, year);
21 return(0);
Listing 1: welcome.c
Compile and run this code.
Exercise 2 Experiment with the program. Try different input and output statements. Try using floating point variables.
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
The printf function outputs text and variables to the screen (or standard output). The percent sign (%) specifies the format of the output. For example, %c outputs an ASCII character, %f a floating point number, and %d an integer. The \n generates a carriage return.
There are 2 other basic output functions in C:
• puts(“string”) outputs a text string to the standard output and appends it with a newline.
• putchar(ch) outputs a single character to the standard output.
The scanf function takes input from the keyboard. Note that, in general, a call to scanf requires that the name of each variable is preceded by an & character. This is the address operator, and tells the scanf function where to find each variable into which it is to store a new value.
There are 2 other basic input functions:
• gets(string) reads a text string from keyboard into string.
• ch=getchar() reads a single character into ch.
For structured input/output to files we have to do the following:
1. Include the preprocessor statement #include
2. Define a variable of type FILE,
e.g., FILE * input_file; (the * denotes a pointer).
3. To open a file use the command:
input_file = fopen(“data.in”,”r”);}
The first term is the name of the file to be opened in quotes. The second term specifies whether the
file is to be written to (“w”) or read from (“r”).
4. To write to the file use the command fprintf, which is virtually identical to printf,
e.g., fprintf(input file,”the␣number␣of␣objects␣is␣%d”, N_objects);.
5. To read from the file use the command fscanf which is virtually identical to scanf,
e.g., fscanf(input file,”%f”,&data_value);.
6. Finally the file should be closed before terminating the program:
fclose(input_file);.
3.5 Basic Operations in C
3.5.1 Arithmetic Operations
C supports the standard operations + – * /. The remainder for integer division is given by % (e.g., 5 % 3 gives the result 2). Integer division (e.g., x = 5 / 3) gives an integer result (e.g., 1, even if x is declared a float).
Expressions are evaluated left to right, with division and multiplication having the same level of precedence. Thus5 / 3* 2evaluatestoadifferentresultto2 * 5/ 3.
The statement i = i + 1; can be rewritten using the compound assignment operator +=, allowing it to be expressed i += 1;.
Similarly,i = i – 5;canbereplacedbyi -= 5;andn = n * (x + 2);canbereplacedbyn *= x + 2;. Increment ++ and decrement — operators add or subtract a value of one. Hence, x++ is equivalent to
x+=1 and to x=x+1.
Exercise 3 Compile and run the program arith.c (below). Experiment with the program. Try some operations on floating point variables. Try some functions from math.h, such as abs, cos, sin, pow, rand, sqrt, sinh, atan, log, log10, floor, etc.
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
1 /* arith.c */
3 /* Performs arithmetic operations */
5 #include
7 int main(void)
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
int x,y,z;
z=x+y; printf(“%d␣=␣%d␣+␣%d␣␣\n”,z,x,y);
z=x*y; printf(“%d␣=␣%d␣*␣%d␣␣\n”,z,x,y); z=x*y/4; printf(“%d␣=␣%d␣*␣%d/4␣␣\n”,z,x,y); z=y/4*x; printf(“%d␣=␣%d/4␣*␣%d␣␣\n”,z,y,x); z=x*(y/4); printf(“%d␣=␣%d␣*␣(%d/4)␣␣\n”,z,x,y); z=x*y%4; printf(“%d␣=␣%d␣*␣%d%4␣␣\n”,z,x,y); z=x*(y%4); printf(“%d␣=␣%d␣*␣(%d%4)␣␣\n”,z,x,y);
printf(“\n␣x␣=␣%d␣\n␣”,x); x+=1; printf(“x+=1,␣x=␣%d␣␣\n”,x); printf(“x␣=␣%d␣\n␣”,x); x*=2; printf(“x*=2,␣x=␣%d␣␣\n”,x);
printf(“\n␣x␣=␣%d␣\n␣”,x); ++x; printf(“++x,␣x=␣%d␣␣\n”,x); printf(“x␣=␣%d␣\n␣”,x); z=++x; printf(“z=++x,␣x=␣%d␣,␣z=␣%d␣␣\n”,x,z); printf(“x␣=␣%d␣\n␣”,x); z=x++; printf(“z=x++,␣x=␣%d␣,␣z=␣%d␣␣\n”,x,z);
Comparison Operators
Listing 2: arith.c
The test for equality is ==. Thus, x==y returns a value of 1 (TRUE) if variables x and y have the same value, and returns 0 (FALSE) otherwise.
Beware of using = when you mean to use ==. x=y will set x to the same value as y.
Other operators: != (not equal), < (less than), > (greater than), <= (less than or equal), >= (greater than
or equal).
3.5.3 Logical Operators
Logical operators are usually used with conditional statements which we shall meet next. The two basic logical operators are: && for logical AND, || for logical OR.
Beware: & and | have a different meaning.
3.6 The if statement
The if statement has the following syntax:
if (expression){ statement
Dr Matthew Howard & Dr Hak-
Deparment of Engineering King’s College London
if (expression){ first_statement
second_statement
if (expression){ first_statement
}else if (expression){ second_statement
third_statement
Where the statements will be executed if the expression takes a non-zero (TRUE) value. This will usually consist of comparative and logical operators as described above.
3.7 Looping and Iteration
3.7.1 The for statement
The C for statement has the following form:
for(initialisation_expression; termination_test; modifier) { statement;
initialisation_experssion initialises the loop; termination_test is the terminate test; modifier
is the modifier (which may be more than just simple increment). For example:
for (x=3;x>0;x–){ printf(“x=%d\n”,x);
will execute the printf statement three times with the value of x equal to 3, 2 and 1 on each iteration. More complicated examples of for expressions are:
for(x=0;((x>3) && (x<9)); x++) and
for(x=0,y=4;((x>3) && (y<9)); x++,y+=2).
3.7.2 The while statement
The C while statement has the following form:
while (x>0){ printf(“x=%d\n”,x);
Dr Matthew Howard & Dr Hak-
Deparment of Engineering King’s College London
Note that, if there is only one statement in the body of the loop, the braces may be dropped. C also provides a do-while construct:
printf(“x=%d\n”,x–); } while (x>0);
In this, the first iteration of the loop is executed prior to checking the termination condition.
Exercise 4 Write a program to read in integer numbers until the number -999 is encountered. The sum of all the numbers input up until this point should then be printed out.
3.8 Arrays, Strings and Structures 3.8.1 Single and Multi-dimensional Arrays Let us first define an array in C:
int listofnumbers[50]; /* listofnumbers is an array of 50 integers */ Beware: In C, array subscripts start at zero and end one less than the array size. For example, in the above
case valid subscripts range from 0 to 49. Elements can be accessed in the following ways:
thirdnumber=listofnumbers[2]; or
listofnumbers[5]=100; Two-dimensional arrays can be defined as follows:
int tableofnumbers[50][50]; Elements can be accessed in the following ways:
anumber=tableofnumbers[2][3]; or
tableofnumbers[25][16]=100;
Single dimensional arrays can be passed to functions as follows:
float findaverage(int size,float list[]) {
float sum=0.0;
for (i=0;i
int max(int a1, int a2) /* determine maximum of 2 integers */ { if (a1 >= a2)
return(a1);
return(a2); }
int min(int a1,
else return(a2); }
/* determine minimum of 2 integers */
int a2) { if (a1 <= a2)
return(a1);
/* notify pre-processor to replace each use of N_VEC by value 10 */
Dr Matthew Howard & Dr Hak- Deparment of Engineering King’s College London
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#define N_VEC 10
/* determine maximum element of a real vector */
void MinMaxVector(const int x[], {
int i; /* counter int MaxSoFar , MinSoFar;
int *minp, int *maxp) */
MaxSoFar = x[0]; MinSoFar = x[0]; for (i=1;
i< N_VEC; ++i)
MaxSoFar = MinSoFar = };
*maxp=MaxSoFar; *minp=MinSoFar; }
int main(void) {
/* initialization */ /* loop repetition condition */ /* update */
max(MaxSoFar ,x[i]); min(MinSoFar ,x[i]);
int x[N_VEC], /*declare array of 10 elements */ min_x , max_x ,
i; /* counter */
printf("\nEnter␣%d␣integers ,␣press␣return␣after␣each:␣\n",N_VEC);
/* initialization */ /* loop repetition condition */ /* update */
scanf("%d", &x[i]);
MinMaxVector(x, &min_x, &max_x); printf("The␣maximum␣value␣is␣%d␣\n",max_x); printf("The␣minimum␣value␣is␣%d␣\n",min_x);
Listing 3: minmax.c
Note the following:
• More than one output argument for functions: The return statement cannot be used to return
more than one value from a function. This is because of the way C uses the stack to pass input and output data to functions. To return several values from a function, precede the declaration of the output variables in the list of parameters in the function definition statement by an asterisk *. In the assignment statements in the function that uses these parameters to send back the results, also precede the parameter name by an asterisk. The function type is void and the function does not include a return statement.
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com