程序代写 MEC302 Embedded Computer Systems

MEC302 Embedded Computer Systems
C Programming
Dr. Sanghyuk Lee
Email: Dept. Mechatronics and Robotics

Copyright By PowCoder代写 加微信 powcoder

Special thanks to Dr. , for his sacrifice to organize this material

Introduction to C
• To run the programs, you will need access to a C compiler. This can be either on your browsing machine or on another machine you have access to.
• This uses the gnu C compiler. You can use the VPL to check your compilation and code before submission, so it is recommended you do all your work using VPL.

Compiling and Submitting
• All submitted files must have the c suffix (for example hello_world.c). Other suffixes will be rejected by the VPL.
• Files must compile on the VPL C compiler. Please check your program before submission and modify if it does not compile correctly.
• Be warned C is a sub-set of C++ but they are not the same. Any program that does not compile using the VPL c compiler will get a zero mark.
• The VPL will autograde and you will instantly get the grade after submission. You are only allowed 1 submission, but you can run your code beforehand to check its operation.

Overview of C Programming
The largest measure of C’s success seems to be based on purely practical considerations:
1. the portability of the compiler; 2. the standard library concept;
3. a powerful and varied repertoire of operators; 4. an elegant syntax;
5. ready access to the hardware when needed; 6. and the ease with which applications can be optimized by hand-coding isolated procedures

Overview of C Programming
• C is often called a “Middle Level” programming language. This is not a reflection on its lack of programming power but more a reflection on its capability to access the system’s low-level functions.
• Most high-level languages (e.g. Fortran) provides everything the programmer might want to do already built into the language.
• A middle level language, such as C, probably doesn’t supply all the constructs found in high-languages – but it provides you with all the building blocks that you will need to produce the results you want!

Structure of C Programs
Having completed this section you should know about:
. C’s character set
. C’s keywords
. the general structure of a C program
. that all C statement must end in a ;
. that C is a free format language
. all C programs use header files that contain standard library functions.
1 2 3 4 5 6

C’s Character Set

The form of a C Program
All C programs will consist of at least one function, but it is usual (when your experience grows) to write a C program that comprises several functions. (In simple terms you may consider functions to be sub-routines). The only function that must be present is the function called main. For more advanced programs, the main function will act as a controlling function calling other functions in their turn to do the dirty work! The main function is the first function that is called when your program executes.

The layout of a C Program
pre-processor directives global declarations main()
local variables to function main ; statements associated with function main ; }
{ local variables to function 1 ;
statements associated with function 1 ;
{ local variables to function f2 ;
statements associated with function 2 ;

The layout of a C Program
Note the use of the bracket set () and {}. () are used in conjunction with function names whereas {} are used as to delimit the C statements that are associated with that function. Also note the semicolon – yes it is there, but you might have missed it! A semicolon (;) is used to terminate C statements. C is a free format language and long statements can be continued, without truncation, onto the next line. The semicolon informs the C compiler that the end of the statement has been reached. Free format also means that you can add as many spaces as you like to improve the look of your programs.

C Program – Hello World!
#include main()
printf(“Hello World\n”); }
The first line is the standard start for all C programs – main(). After this comes the program’s only instruction enclosed in curly brackets {}. The curly brackets mark the start and end of the list of instructions that make up the program – in this case just one instruction.

C Program – Hello World!
Notice the semicolon marking the end of the instruction. You might as well get into the habit of ending every C instruction with a semicolon – it will save you a lot of trouble! Also notice that the semicolon marks the end of an instruction – it isn’t a separator as is the custom in other languages.
main(){printf(“Hello World\n”);} but this is unusual.
The printf function does what its name suggest it does: it prints, on the screen, whatever you tell it to. The “\n” is a special symbols that forces a new line on the screen.
Type and save it as Hello.c. Then use the compiler to compile and finally run. The output is as follows: Hello World

Hello World! – Adding comments
A comment is a note to yourself (and others) that you put into your source
code. All comments are ignored by the compiler & exist solely for your benefit.
In C, the start of a comment is signaled by the /* character pair. A comment is ended by */. For example, this is a syntactically correct C comment:
/* This is a comment. */
In C you can’t have one comment within another comment.
main() /* main function heading */
printf(“\n Hello, World! \n”); /* Display message on */ } /* the screen */

Embedded Computer Systems
Data Types

Basic Data Types
There are five basic data types associated with variables:
. int – integer: a whole number
. float – floating point value: i.e. a number with a fractional part
. double – a double-precision floating point value
. char – a single character
. void – valueless special purpose type which we will examine closely later

Data Types – Integer number variables
• An int variable can store a value in the range -32768 to +32767. You can think of it as a largish positive or negative whole number: no fractional part is allowed.
• int variable name; int a;
• To assign a value to our integer variable, use the following statement
• a = a+10;

Data Types – Integer number variables
• Compile and run the following C program in VPL #include
main() /*main programme*/
int a=10; /* declare integer a and give it a value of 10*/ printf(“%2i”, a); /* Display the value of a on the screen*/ }

Data Types – Decimal number variables
• C uses two keywords to declare a variable associated with decimal number
• float/floating point – number has about seven digits of precision and a range of about 1.E-36 to 1.E+36. A float takes four bytes to store
• double/double precision – number has about 13 digits of precision and a range of about 1.E-303 to 1.E+303. A double takes eight bytes to store

Data Types – Decimal number variables • Compile and run the following C program in VPL
#include
main() /*main programme*/
float sum=0; /* declare sum and give it an initial value of 0*/ float a,b; /* declare variable a and b*/
sum=a+b; /* add b to a*/
printf(“%0.2f”, sum); /* Display the value of sum on the screen*/ }

Data Types – Character variables •

Data Types – Assignment statement
• Can store a value in a variable using name = value; like a = 10; add a+b
subtract a-b
multiply a*b
divide a/b
• Two points to note from the above calculation:
C ignores fractions when doing integer division!
When doing float calculations integers will be converted into float.

Data Types – Arithmetic ordering
• Consider the following calculation, a = 10.0 + 2.0 * 5.0 – 6.0 / 2.0
• Prefer to use brackets to avoid confusion: a = 10.0 + (2.0 * 5.0) – (6.0 / 2.0)
• Freely mix int, float and double variables in expressions
• In nearly all cases the lower precision values are converted to the highest precision values used in the expression
For example, the expression f*i, where f is a float and i is an int, is evaluated by converting the int to a float and then multiplying. The result is a float but this may be assigned to another data type and the conversion will be made automatically.

Data Types – Something to declare
• Before using a variable, you must declare it – state its type and give name
inta, b,c;
#include main()
int a,b,average; a=10;
average = ( a+b ) / 2;
printf(“Here is the answer…. %d.”,average); }

1. 2. 3. 4.
Data Types – More on initializing
• You can assign an initial value to a variable while declaring it: inti=1; sameas inti;
• Variable names
should be lowercase for local variables
should be UPPERCASE for symbolic constants (to be discussed later) only the first 31 characters of a variables name are significant
must begin with a letter or _ (under score) character

Input and Output Functions
scanf(“%d”,&a);
• When the program reaches the scanf statement, it pauses to give the user time to type something on the keyboard and continues only when users press , or .
printf(“%The value stored in a is %d”,a);
The %d, both in the case of scanf and printf, simply lets the compiler know that the value being read in, or printed out, is a decimal integer

Input and Output Functions
• The printf and scanf functions do differ……………. printf(string,variable,variable,variable…)
• The string is all-important because it specifies the type of each variable in the list and how you want it printed – usually called control or format string
• The way that this works is that printf scans the string from left to right and prints on the screen, or any suitable output device, any characters it encounters – except when it reaches a % character.
• % character is a signal that what follows, specification for printing variable

Input and Output Functions
• printf(“Hello World”);
only has a control string and no % characters – it results in Hello World The specifier %d means convert the next value to a signed decimal integer • printf(“Total = %d”,total);
will print Total = and then the value passed by total as a decimal integer.
• The %d isn’t just a format specifier, it is a conversion specifier. It indicates the data type of the variable to be printed and how that data type should be converted to the characters that appear on the screen.

The % Format Specifiers
The % specifiers in ANSI (American National Standards Institute) C are %c char single character %d (%i) int signed integer
%e (%E) float or double exponential format
%f float or double signed decimal
%g (%G) float or double use %f or %e as required
%o int unsigned octal value %p pointer address stored in pointer %s array of char sequence of characters %u int unsigned decimal %x (%X) int unsigned hex value

Formatting your output
If you print a string using the %s specifier then all of the characters stored in the array up to the first null will be printed. If you use a width specifier then the string will be right justified within the space. If you include a precision specifier then only that number of characters will be printed.
printf(“%s,Hello”) will print Hello,
printf(“%25s ,Hello”) will print 25 characters with Hello right justified and printf(“%25.3s,Hello”) will print Hello right justified in a group of 25 spaces.
———–Write C program that uses printf as described above————

Formatting your output
Try these lines in an appropriate point in your programme:
char Hello[] = “Hello”; printf(“%25s”, Hello);
• The first line above creates a character array called Hello, which contains the word “Hello”.
• The second line will print the contents of the array HELLO.

Control codes
\b backspace
\n new line [Note: Remember this control code because you will need it
for submitting code using the VPL]
\t horizontal tab \’ single quote \0 null
If you include any of these in the control string then the corresponding ASCII control code is sent to the screen, or output device, which should produce the effect listed.

Control codes
scanf(control string,variable,variable,…)
• The scanf function works in much the same way as the printf.
• The most obvious is that scanf must change the values stored in the parts of computers memory that is associated with parameters (variables).
• Wait until we cover functions in more detail
• The second difference is that the control string has some extra items to cope with the problems of reading data in. However, all the conversion specifiers listed in connection with printf can be used with scanf.

Control codes
• Rule is that scanf processes the control string from left to right & each time it reaches a specifier it tries to interpret what has been typed as a value
➢ If you input multiple values then these are assumed to be separated by white space – i.e. spaces, newline or tabs. This means you can type:
and it doesn’t matter how many spaces are included between items.

Control codes
For example: scanf(“%d %d”,&i,&j);
• It will read in two integer values into i and j. The integer values can be typed on the same line or on different lines if there is at least one white space character between them.
• The only exception to this rule is the %c specifier which always reads in the next character typed no matter what it is. You can also use a width modifier in scanf. Its effect is to limit number of characters accepted to the width.
For example: scanf(“%l0d”,&i)

Control codes
➢ Problem: Try to write your own program
Write a C Program to read three integers, add them
together and display the result on the screen.
Write a C Program to find the average, to 2 decimal points, of three floating point numbers inputted via the keyboard.
—————— Practice this problem ——————

—————— Practice this problem ——————
MEC302 Embedded Computer Systems
Conditional Execution, Functions & Prototypes

Program Control
• Its time to turn our attention to a different problem – conditional execution.
if (total<0) printf(“OK”); • If the condition is false, then the program continues with the next instruction. In general, the if statement is of the following form: if (condition) statement; and of course, the statement can be a compound statement Program Control • Here is an example program using two if statements: Program Control • The if statement lets you execute or skip an instruction depending on the value of the condition. • Another possibility is that you want to select one of two possible statements • one to be obeyed when the condition is true • one to be obeyed when the condition is false if (condition) statement1; else statement2; Logical expressions • To compare two values, you can use the standard symbols such as > (greater than) >= (greater than or equal to)
< (less than) <= (less than or equal to) == (to test for equality) if (a=10) instead of if (a==10) • The situation is made worse by the fact that the statement if (a = 10) is legal and causes no compiler error messages! Logical expressions An example program showing if else construction now follows: Logical expressions ➢ Problem:Trytowriteyourownprogram Write a program to read an integer from the screen and decide if it is odd or even [Hint: An expression a % b produces the remainder when a is divided by b; and zero when there is no remainder] Break and continue within loops • The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression. • break is also used in conjunction with functions and case statements which are covered in later sections. • Continue forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of the loop. • In while and do-while loops, a continue statement will cause control to go directly to the test condition and then continue the looping process Break and continue within loops Break and continue within loops Select paths with switch Select paths with switch Structure and Nesting • It is one of the great discoveries of programming that you can write any program using just simple while loops and if statements. • Of course, it is nice to include some other types of control statement to make life easy - for ex: you don't need the for loop, but it is good to have! • So as long as you understand the if and the while loop in one form or another you can write any program you want to. • If you think that a loop and an if statement are not much to build programs, then you are missing an important point. Structure and Nesting – Think a number • Now let's have a go at writing the following program: 'It thinks of a number in the range 0 to 99 and then asks the user to guess it'. This sounds complicated, especially the 'thinks of a number' part, but all you need to know is that the statement: r = rand() will store a random number in the integer variable r. The standard library function rand() randomly picks a number within the range 0 to 32767, but this might vary from machine to machine. Structure and Nesting – Think a number If you look at the last two digits of all these numbers, they will form our random set! To select just these numbers, we can use an arithmetic calculation of the following form: r = rand() % 100 That is, to get the number into the right range you simply take the remainder on dividing by 100, i.e., a value in the range 0 to 99. You should remember this neat programming trick; you'll be surprised how often it is required. Structure and Nesting – Think a number Functions and Prototypes • A function is simply a chunk of C code (statements) that you have grouped together and given a name. The value of doing this is that you can use that "chunk" of code repeatedly simply by writing its name printf("Hello"); demo() total = total + l; { printf("Hello"); total = total + 1; } Functions and Local Variables • As it stands the demo function will not work. The problem is that the variable total is not declared anywhere. • Now this raises the question of where exactly total is a valid variable. Getting Data In and Out of a function • To be useful there must be a way of getting data into and out of a function • Parameters a and b are used within the function – local variables •sum(1,2); – is a call to the sum function with a set to 1 and b set to 2. • sum(x+2,z*10); – will set a to whatever x+2 works out and b to z*10 Getting Data In and Out of a function • Parameters are the way of getting values into a function, but how do we get values out? • There is no point in expecting the result variable to somehow magically get its value out of the sum function. You may want to try this But it does not work.! Getting Data In and Out of a function • The simplest way to get value out of function is to use return instruction return value; which can occur anywhere within the function, not just as last instruction • The return always terminates the function and returns control back to calling function Getting Data In and Out of a function Functions and Prototypes • Where should function’s definition go – before or after? The only requirement is function’s type must be known before it is used • Onewayistoplacethefunctiondefinitionearlierintheprogramthanitisused Standard library function Standard library function Global variables Global variables are created by declaring them outside any function int max; main() ........ } { ....... } The int max can be used in both main and function f1 and any changes made to it will remain consistent for both functions Constant Data Types • Constant refer to fixed values that may not be altered by the program MEC302 Embedded Computer Systems Arrays, Pointers, Strings, Structures Advanced Data Types Suppose you want to read five numbers and print them in reverse order 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com