0% found this document useful (0 votes)
9 views35 pages

MCAPP Lab 01 (Student) C Programming Fundamentals (Apr 25)

This document outlines Lab 1 of a course on Microcontroller Applications, focusing on C programming fundamentals. It covers key topics such as the need for compilation, program structure, data types, and includes examples and exercises to reinforce learning. The lab aims to provide students with a foundational understanding of C programming necessary for microcontroller programming.

Uploaded by

shenhaixu2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views35 pages

MCAPP Lab 01 (Student) C Programming Fundamentals (Apr 25)

This document outlines Lab 1 of a course on Microcontroller Applications, focusing on C programming fundamentals. It covers key topics such as the need for compilation, program structure, data types, and includes examples and exercises to reinforce learning. The lab aims to provide students with a foundational understanding of C programming necessary for microcontroller programming.

Uploaded by

shenhaixu2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Diploma in BME

Diploma in CEN
Diploma in ELN

Microcontroller Applications (EMC3006)

Name: Class:

Lab 1 – C Programming Fundamentals

Objectives:
1. To learn basic C programming

Equipment & Software:


1. Computer/notebook

Introduction
In this subject, we will be using the C language to program the microcontroller. In this lab,
you will learn the basics of C programming. The basics of C will be taught through a
series of code examples.

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 1 of 35


Contents

1 Why a C Program Needs to Be Compiled 3

2 C Program Outline 4

3 Data Types 8

4 Identifiers 12

5 Operators 14

6 Decision Making 17
6.1 The if statement 17
6.2 The if, else statement 18
6.3 The if, else-if statement 19

7 Looping 20
7.1 The for loop 20
7.2 The while loop 21

8 Arrays 23

9 Functions 26

10 Summary Quiz 30

11 Lab 1 Extra 31
11.1 Use of Functions 31
11.2 Number System Conversion 33

Appendix A: C Keywords 35

Appendix B: Comparison Between C and Python 35

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 2 of 35


1 Why a C Program Needs to Be Compiled

C is a programming language that requires compilation.

A compiler is a program that translates a C program into its executable machine code in
binary format.

The compiler also ensures the program is syntactically correct (written according to the
rules of the programming language).

A different hardware (or machine) will support a different machine code format. For
example, the machine code format that runs in the Intel or AMD hardware which are used
to power our laptops is different from the machine code format of a microcontroller or
microprocessor used in our smart phones.

In other words, each computer or machine only understands its own machine code.

Hence, the program must be "translated" to its corresponding machine code by using the
compiler provider by the microcontroller company.

Figure 1-1: Machine Hardware and Software Representation

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 3 of 35


2 C Program Outline

A simple C program is shown below. This simple program does a simple print to the
console. Go through the different parts of the program.

1 // Online C compiler to run C program online Comment


2 #include <stdio.h> A pre-processor
3
Start of directive
4 int main()
main 5 {
function 6 // Write C code here main() → Entry
7 printf("Hello world"); point of a C
8 program
End of 9 return 0;
main 10 }
function
Figure 2-1: Hello World C Program

Exercise 2.1
In your laptop, go to the following webpage which contains an online C compiler:
https://www.programiz.com/c-programming/online-compiler/

Enter the program in Figure 2-1. Click Run to run the program.

The result will be display in the Output box on the right as shown below in Figure 2-2.

Figure 2-2: Hello World C Program Output

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 4 of 35


Understanding the first program:

Let us understand what each line of the program means.

• Line 1:
// Online C compiler to run C program online

The double forward slash // is used in C to indicate a single line comment.

At the beginning of a program, comments are usually written to inform the reader what
this program does. The compiler ignores comments during compiling.

• Line 2:
#include <stdio.h>

The # character in C indicates a preprocessor directive.

There are several preprocessor directives in C. A preprocessor instructs the compiler


to do a certain preprocessing task, e.g., include a file, before actual compilation
begins.

Positioned at the beginning of a program, the line, #include <stdio.h> informs the
compiler to include the standard input/output library header file, stdio.h.

A header file (one with the extension .h) is where you can place shared constants or
declarations of functions.

What is a declaration of a function?

A function declaration is a statement describing the name of the function


(identifier), its return type and parameters, if any. More on these will be explained
later.

The stdio.h header file contains the declarations for the printf() and scanf()
functions.

The printf() function is an output process (to a display) while scanf() function is an
input process (from the keyboard).

There are other preprocessor directives, such as #define which you will encounter in
this subject later and will be widely used in microcontroller programming.

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 5 of 35


• Line 4 – 5 and Line 9 - 10:
Line 4 is the start of the function main().

The function main() is the entry point to a C program.

Every C program must have one and only one main() function.

1 // Online C compiler to run C program online


2 #include <stdio.h>
3
4 int main() Return type of
5 { function (see Section
6 // Write C code here 9)
7 printf("Hello world");
8 As return type is int

Match
9 return 0; (integer), the return
10 } value must be an
integer value.
Return value

Figure 2-3: Hello World C Program Illustrating Return Type

Notice that the function main() is defined with the return type of int (integer). This
means that at the end of the function at line 9, an integer value must be returned out
of the function. In this case, a value of 0 is being returned.

In programming, zero is usually used to indicate a status that there are no errors when
the function is being run. A non-zero returned value indicates a specifc error.

Line 5 is an open-brace character, {. This character is used to indicate the start of the
block of statements within this function. Similarly, in line 10, the close-brace character,
} is used to indicate the end of the block of statements within this function.

This brace pair { } is also used in the for-loop and if-statement, which you will see
later.

Tip: Another form of coding-style


To save on the number of lines of codes, some developers prefer to move the open
brace to the same line as main(), as seen below. This is also another form of coding
style.
Open brace on
same line
int main() {
// Write C code here
printf("Hello world");

return 0;
}

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 6 of 35


• Line 7:
1 // Online C compiler to run C program online
2 #include <stdio.h>
3
4 int main()
5 {
6 // Write C code here
7 printf("Hello world");
8 Semicolon
9 return 0; indicates
10 } end of a
statement

Indentation (e.g., 4 spaces) so that


program is easier to read

In line 7, the printf() function is called to display a text message on the console. Notice
that double quotes (" ") are used to enclose the string to be printed.

Notice too that this statement is terminated with the semicolon, which all C statements
are (except for C constructs such as if, which you will see later).

About the Function Declaration

Why is it necessary to have the #include <stdio.h> statement at line 2, which is


almost at the start of the program file?

Answer:
Before we can make use of the printf() function at line 7, it is necessary to declare
it first.

By including the header file stdio.h, we are actually substituting it with the
declaration of printf().

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 7 of 35


3 Data Types

In C, data types are declarations for variables. This determines the type and size of data
stored in the variables. In Table 3-1, you will see the different data types (not exhaustive)
as defined in the XC8 compiler. This compiler is the one that we will use to compile our
programs for the microcontroller.

Data Type Size (bytes) Range Format Specifier


char 1 -128 to 127 %c, %d
unsigned char 1 0 to 255 %c, %d
int 2 -32768 to 32767 %d
unsigned int 2 0 to 65535 %d
-1.17549435E-38 to
float 4 %f
6.80564693E+38

Table 3-1: Basic Data Types in the XC8 Compiler

• char, unsigned char


There are namely two data types of the char type. The first one is char by itself, while
the other is unsigned char. Both types are of size 1 byte, that is 8 bits. Since 28 =
256, there are 256 possible values that a variable that is declared using one of this
type, can carry. However, their ranges are different as shown in Figure 3-1.

Data type of size 1 byte

char

-128 0 127

unsigned char

0 255

Figure 3-1: Ranges of char and unsigned char data types

Variables that are declared with the first type can hold a value from -128 to 127, while
variables declared with the second type can hold a value from 0 to 255.

You can think of the word, unsigned as meaning not having a negative value.

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 8 of 35


About ASCII:

ASCII stands for American Standard Code for Information Interchange. It is a


character encoding standard for electronic communication. Figure 3-2 shows the
ASCII table with numeric codes ranging from 0 to 127. In other words, 7 bits are
sufficient to represent these numeric codes ranging from punctuations to digits and
the alphabets (both cases).

Dec Char Dec Char Dec Char Dec Char


--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL

Dec stands for decimal (i.e., a base 10 number)


Char stands for character

Figure 3-2: ASCII Table

How do we read the ASCII table? For example, the character '6' has the integer
value of 54, while the character 'h' has the integer value of 104.

When a machine wants to transmit the character 'h' to another machine, it will
transmit the encoded value of 104.

You can think of the data type, char as being "invented" in programming because
1-byte is sufficient to represent the entire 127 numeric codes in the ASCII "character"
table.

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 9 of 35


Example 1: Declaring char, unsigned char variables

char fridgeTemp; // temperature inside refrigerator


char gender; // 'f' for female, 'm' for male
unsigned char seconds; // seconds in running time
variable name
data type

Example 2: Assigning values to these variables

char fridgeTemp;
char gender;
unsigned char seconds;

fridgeTemp = -1;
gender = 'm';
seconds = 0;

Example 3: Declaring variables and initialising values to them at the same time

char fridgeTemp = -1;


char gender = 'm';
unsigned char seconds = 0;

Study the 3 examples above. In example 1, the variables are simply declared without
values assigned to them. In example 2, after the variables are declared, they are
each assigned with respective values. Finally in example 3, these variables are both
declared and initialised with respective values. Examples 2 and 3 illustrate valid and
possible methods of assigning the variables with values.

• int, unsigned int


The int (integer) type is of size 2 bytes, that is 16 bits. Since 216 = 65536, there are
65536 possible values that a variable that is declared as integer, can carry. The
associated number lines are shown below:
Data type of size 2 bytes

int

-32768 0 32767

unsigned int

0 65535

Figure 3-3: Ranges of int and unsigned int data types

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 10 of 35


Example 4: Declaring int, unsigned int variables and assigning values to them

int y_coord; // Y-coordinate in cartesian graph


unsigned int daysInYear; // Number of days in a year

y_coord = -10;
daysInYear = 365;

• float
Finally, this data type is used to declare variables that needs to store a floating-point
value, e.g., 3.456.

Example 5: Declaring a float variable and assigning a value to it

float radius; // radius of circle

radius = 3.456; // Assign value to radius variable

Exercise 3.1
Enter the program below and run it. Observe the output.

1 #include <stdio.h>
2
3 int main() {
4 char fridgeTemp = -1;
5 char gender = 'm';
6 unsigned int daysInYear = 365;
7 float radius = 3.456;
8
9 printf("Fridge temperature = %d\n", fridgeTemp);
10 printf("gender = '%c' (%d)\n", gender, gender);
11 printf("daysInYear = %d\n", daysInYear);
12 printf("radius = %.2f\n", radius);
13 return 0;
14 }

Question:
What is the effect of the format specifiers?
a) %c
b) %.2f

____________________________________________________________________
____________________________________________________________________
____________________________________________________________________

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 11 of 35


4 Identifiers

Identifier:
An Identifier refers to a name given to entities in C such as variables, arrays, and
constants. It is a sequence of letters and/or digits and must start with a letter. Identifiers
are case sensitive. For example, termA is different from TermA.

Variable:
We have seen earlier how a variable can be declared with a specific data type. Upon
being declared, it is allocated a memory location in the computer's memory to store its
value. Take for instance the statement below:

unsigned char seconds = 0;


Statement
value
variable name
data type

The variable, seconds is allocated a memory location in RAM to store the value of 0 as
shown in Figure 3-4.

RAM

1-byte data is stored in memory location

0 Memory What
Locations happens in
seconds computer
variable is allocated a
memory?
memory location

Figure 4-1: Memory being allocated for a declared variable

In general, each variable should be given a unique name.

It is called variable because your program can change its value.

Constant:
A constant’s value cannot be changed during the execution of a program. The #define
directive allows the programmer to use a symbolic name in place of a constant.
An example is the constant π used in calculation of perimeter or area of circles:

#define PI 3.142

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 12 of 35


C Naming Rules

• An identifier must start with:


 A letter (upper or lower case), or
 $ or underscore (_)
It can contain digits. Examples are:
 sum
 Class
 _class
 new_Var
 number001Class

• An identifier cannot contain operators, such as +, -, * and .


For example, sum+, power-tone, love.Bug are not valid identifiers

• An identifier cannot be a keyword (reserved word). For examples, main, new, true,
false, null.

• An identifier can be of any length.

The #define directive should be placed just before main() in your program.

Exercise 4.1
Enter the program below and run it. Observe the output.

1 #include <stdio.h>
2
3 #define PI 3.142
4
5 int main () {
6 float radius = 1.2, area;
7
8 area= PI * radius * radius;
9 printf("Given the radius %.1f,\n", radius);
10 printf("The area of circle is %.2f\n", area);
11 return 0;
12 }

Question:
Why would you not declare PI as a variable?

____________________________________________________________________
____________________________________________________________________
____________________________________________________________________

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 13 of 35


5 Operators

An operator is a symbol that informs the compiler to perform a specific arithmetic or


logical function. C has a wide range of operators to perform various operations. Table 5-
1 shows the different operators.

Operator Type Operators


Arithmetic + - * / %
Assignment =
Increment/Decrement ++ --
Relational < <= == != >= >
&& Logical AND
Logical || Logical OR
! Logical NOT
& Bitwise AND
| Bitwise OR
~ Bitwise NOT
Bitwise
^ Bitwise XOR
>> Right Shift
<< Left Shift

Table 5-1: Operators

Exercise 5.1:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 int a = 9, b = 4, c;
5 float y = 4.0, z;
6
7 c = a/b;
8 printf("a/b = %d \n", c);
9
10 z = a/b;
11 printf("a/b = %.2f \n", z);
12
13 z = a/y;
14 printf("a/y = %.2f \n", z);
15
16 c = a%b;
17 printf("Remainder when a divided by b = %d \n", c);
18
19 return 0;
20 }

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 14 of 35


Question:
What is the difference between the statements at line 10 and line 13?

____________________________________________________________________
____________________________________________________________________
____________________________________________________________________

Exercise 5.2:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 int a = 9, b = 4, c, d;
5
6 a++;
7 printf("The incremented value of a is: %d \n", a);
8
9 b--;
10 printf("The decremented value of b is: %d \n", b);
11
12 c = 500;
13 printf("c = %d\n", c); Relational
14
15 d = (c == 500); operator
16 printf("d = %d\n", d);
17
18 return 0;
19 }

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 15 of 35


Question:
What is the difference between the following 2 statements?
 c = 500 at line 12, and
 c == 500 at line 15?
____________________________________________________________________
____________________________________________________________________

Exercise 5.3:
Enter the program below and run it. Observe the output.
1
#include <stdio.h>
2
3
int main()
4
{
5
int a = 5, b = 5, c = 10, result;
6
7
result = (a == b) && (c > b);
8
printf("(a == b) && (c > b) is %d \n", result);
9
10
result = (a == b) || (c < b);
11
printf("(a == b) || (c < b) is %d \n", result);
12
13
return 0;
14

Question:
Suggest a scenario in the microcontroller where the && operator can be used.
____________________________________________________________________
____________________________________________________________________

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 16 of 35


6 Decision Making

Reference: https://www.geeksforgeeks.org/decision-making-c-c-else-nested-else/

The if and if...else constructs are used to make decisions in a program. Based on the
outcome of a test expression, some codes will be executed, while some will be ignored.

6.1 The if statement

Test False
Expression
True

Body of if

Statements
below if..else

Figure 6-1: Flow of if-statement

The if statement checks whether the test expression inside the parenthesis ( ) is
true or not.
if (test expression)
{ Test expression
// statement(s) to be executed if test needs to evaluate to
// expression is true either true or false
}

The enclosing { and } are optional if there is only one statement inside the statement
block.

Exercise 6.1:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 int a = 5, b = 5;
5
6 if (a == b)
7 printf("== is a Relational operator");
8
9 return 0;
10 }

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 17 of 35


6.2 The if, else statement

Test False
expression

True

Body of if Body of else

Statements
below if..else

Figure 6-2: Flow of if...else statement

The if… else is used when you want to execute some statement/s if the test expression
is true and execute some other statement/s if it is false.
if (test expression)
{
// statement(s) to be executed if test expression is true
}
else
{
// statement(s) to be executed otherwise
}

Exercise 6.2:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 int a = 5, b = 5, c = 10;
5
6 if ((a == b) || (c < b)) {
7 printf("|| is a Logical OR operator\n");
8 }
9 else {
10 printf("Both conditions (a == b) and (c < b) are false\n");
11 }
12 return 0;
13 }

Modify the values of a or b so that the flow can go to the else block.

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 18 of 35


6.3 The if, else-if statement

For multiple options, if, else if statement can be used. The if and else-if statements are
executed from top down. As soon as one of the conditions is true, the statement
associated with that if is executed, and the rest of the else if is bypassed. If none of the
conditions are true, then the final else statement will be executed.

Exercise 6.3:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 float x = 100.0;
5
6 if (x > 100)
7 printf("%.2f is greater than 100.", x);
8 else if (x < 100)
9 printf("%.2f is less than 100.", x); Note that the else
10 else construct is not
11 printf("%.2f is equal to 100.", x); followed with a
12 condition next to it.
13 return 0;
(Unlike if and else-
14 }
if).

Change the value of x so that the statements at line 7 and 9 can also be executed.

Note on final else:

Note that it is not mandatory to have the final else. For example, the following statements are
also valid.

if (test expression 1)
// statement(s) to be executed if test expression 1 is true
else if (test expression 2)
// statement(s) to be executed if test expression 2 is true
else if (test expression 3)
// statement(s) to be executed if test expression 3 is true

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 19 of 35


7 Looping

Reference: https://www.geeksforgeeks.org/loops-in-c-and-cpp/?ref=lbp

In programming, to repeatedly do a certain task, we can use a repetition construct such


as for and while. These two constructs execute a block of code statements repeatedly.

7.1 The for loop

A for loop is a repetition control structure which allows a loop body to be executed a
specific number of times.

Flow 1 2 3


• After executing loop body, this
If condition evaluates to
• expression increments or
true, execute the body of decrements the loop variable
Initialise loop counter to the loop and go to update by some value. For example:
some value. For statement. If false, exit a++;. The flow then goes back
example: int a = 1;. from the loop. to check the test condition

for ( initialization statement ; test-condition ; update-statement )


{
/* loop body */
}

Exercise 7.1:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main()
4 {
5 int a;
6
7 for (a = 1; a <= 5; a++)
8 {
9 printf("Loop #%d\n", a);
10 }
11 return 0;
12 }

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 20 of 35


Question:
What is the value of a when the program exits the for loop?
____________________________________________________________________
____________________________________________________________________

7.2 The while loop

For for loop, the number of iterations is known beforehand. On the other hand, while
loops are used in situations where we do not know the exact number of iterations of loop
beforehand. The loop execution is terminated based on the test condition.

Similar to the for loop, the syntax of the while loop consists of three statements –
initialisation statement, test condition, update statement. The main difference is the
placement of these three statements.

Initialisation statement Test


condition
while (test condition) needs to
{ evaluate to
// loop-body either true
update statement or false
}

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 21 of 35


Exercise 7.2:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main()
Initialisation statement
4 {
5 int n = 1;
6 Test condition
7 while (n <= 4)
8 {
9 printf ("%d \n", n);
10 n = n + 1;
11 }
12 return 0; Update statement
13 }

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 22 of 35


8 Arrays

Reference: https://www.geeksforgeeks.org/c-arrays/

An array in C is a collection of similar data items stored at contiguous memory locations.


The elements can be accessed randomly using the indices of an array.

Array Elements

Array 1 3 6 23 99
0 1 2 3 4 Array Indices

Declaring an Array
An array is declared like any other variable before we can use it.

We declare an array by specifying its name, the data type of its elements, and the size
(number of elements). When an array is declared, the compiler allocates a memory block
of the specified size to the array name.

Examples of Array Declaration:

// Declare an array of 5 integers


int marks[5];

// Declare an array of 2 unsigned char numbers


unsigned char sevseg_pattern[2];

Initialising the Array


When an array is declared, the allocated memory contents are random values. It is thus
necessary to initialise them to meaningful values according to your program.

 During Declaration...
An array can be initialised when it is declared. This is shown in the two examples
below.
Initialising array:

int marks[5] = {1, 3, 6, 23, 99};


unsigned char sevseg_pattern[2] = {0b00110101, 0b11010011};

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 23 of 35


 Without Stating Size...
We can also leave the size of the array blank during initialisation. In this case, the
compiler will automatically compute the size of the array by looking at the number of
array elements. An example is as follows:
Initialising array without stating the size:

unsigned char sevseg_pattern[] = {0b00110101, 0b11010011};


Compiler will compute the
size of array by looking at the
number of elements.
 After Declaration...
If the array elements are not initialised during declaration, they can be assigned to
values individually later.
Initialising array after declaration:

unsigned char sevseg_pattern[2];

sevseg_pattern[0] = 0b00110101;
sevseg_pattern[1] = 0b11010011;

Accessing Array Elements


Array elements are accessed by using the index value of the element. Array index starts
at 0 and goes until N – 1, where N is the number of elements in the array.

An example of accessing array element:

Array Elements

1 3 6 23 99
0 1 2 3 4 Array Indices

int marks[5] = {1, 3, 6, 23, 99};

// access element at index 2 i.e 3rd element


printf("Element at marks[2]: %d\n", marks[2]);

// access element at index 4 i.e 5th element


printf("Element at marks[4]: %d\n", marks[4]);

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 24 of 35


Exercise 8.1:
Modify the program to compute the average value.
1 #include <stdio.h>
2
3 int main()
4 {
5 int pattern[5] = {7, 8, 3, 4, 2};
6 int i;
7
8 for (i=0; i<5; i++)
9 printf("pattern[%d] = %d\n", i, pattern[i]);
10
11 return 0;
12 }

Write your inserted statements below:


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 25 of 35


9 Functions

Reference: https://www.geeksforgeeks.org/c-functions/

A function is a group of code that does a specific task. The earliest example of a function
that you have encountered in C was the main() function.

Besides the main() function, you can also write other functions or make use of provided
functions. The former is known as user defined functions, while the latter is known as
library functions. For example, printf() is a library function.

As you have seen in Section 2, the block of a statements belonging to a function are
enclosed within the { } braces.

Modular Program Design

It is encouraged to use functions in program design. A function is the basic building block
that provides modularity and code reusability especially in large and complex programs.

The advantage of modular program design is that functions:


 Can be assembled, tested and verified independently.
 Can be reused by other parts of a program.

Using Functions

In order to define a function and use it in your program, the following three items are
essential.
1. Function declaration
2. Function definition
3. Function call

1. Function Declaration
Just like a variable, a function declaration tells the compiler that there is a function
with the given name residing somewhere in the program. If this function is to be called
in this program file, it needs to be declared in the file.

Declaring a function:
The following illustrates how a function to calculate the volume of a box, is declared.

ending
return type parameter type semicolon
int volume(int len, int width, int height);

function name parameter name

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 26 of 35


In a function declaration, what is needed by the compiler is the return type of the
function and the data type of its parameters. As such, the name of the variables can
be left blank. In short, the declaration can also be:

int volume(int, int, int);

2. Function Definition
The function definition consists of the actual statements that are executed whenever
the function is called.

Defining a function:
return
type
int volume(int len, int width, int height)
{
int vol;
Body
vol = len * width * height;
return (vol);
}
return value

In the above example, take note that the return value of the function must be of the
same data type as the return type of the function.

3. Function Call
A function call is a statement that instructs the compiler to execute the function.

Exercise 9.1:
Enter the program below and run it. Observe the output.

#include <stdio.h>

int volume(int, int, int);

int main() {
int result;
Function call
result = volume(3, 4, 5);
printf("Volume = %d\n", result);
return 0;
}

int volume(int len, int width, int height) {


int vol;

vol = len * width * height;


return (vol);
}

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 27 of 35


Return Types and Arguments

In C, functions can be designed either with or without parameters. While we have seen
an example of a function returning a value from the exercise above, functions may also
be designed such that they do not return values to the calling functions.

The general form of a function is:


return_type function_name(arg1_type arg1_name, arg2_type arg2_name, ... )
{
// code
}

The list below shows the various types of functions that can possibly be designed:

1. Function with no parameters and no return value.


E.g.:
void blinkLED(void) {
// blink the LEDs
. . .
}

2. Function with no parameters and with return value


E.g.:
unsigned char getNumber(void) {
unsigned char num;
// get the number formed by 2 switches
// this number will range from 0 – 3
. . .
return(num);
}

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 28 of 35


3. Function with parameters and with no return value
E.g.:
void setLEDState(unsigned char state) {
// set the LED state
. . .
}

4. Function with parameters and with return value


E.g.:
int volume(int len, int width, int height) {
int result;
// calculate the volume of a box
. . .
return(result);
}

Exercise 9.2:
Enter the program below and run it. Observe the output.

The return type for


main() is int. It is thus
#include <stdio.h>
necessary to return an
void myFunction(void); // Function declaration integer value before
the main() function
int main() exits. This is done
{ through the “return 0;”
myFunction(); // Function call statement in main().
return 0;
} The return type for
myFunction() is void.
void myFunction(void) // Function definition This means that the
{ function does not need
printf("Hello function\n"); to return value.
}

Question:
What is the difference between the functions in Exercise 9.1 and 9.2?
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 29 of 35


10 Summary Quiz

1. What does a C compiler do? Tick the options that applies.


Ensures that the program is syntactically correct
Compress the size of the C source file
Encrypt the C source file so that it is not human readable to prevent cyber attacks
Translates the program into its hardware executable machine code

2. The compiler will automatically compute the size of the following array as 3 integer
elements. Is it True or False?
int scores[ ] = {36, 45, 53};
Ο True
Ο False

3. What are the different types of a C function according to its return type and
parameters? Tick the options that applies.
Function with no parameters and no return value.
Function with few parameters and no return value.
Function with two parameters and two return values.
Function with one parameter and a return value.

~ End of Lab 1 ~

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 30 of 35


11 Lab 1 Extra

11.1 Use of Functions

Exercise 11.1:

The Morse code is a system that uses a series of dots and dashes to represent numbers
and alphabets.

Figure 9-3 Morse Code

The C program below prints the alphabet ‘S’ in the Morse code, which is represented by
3 dots.

#include <stdio.h>

// Function declaration
void dot(void);

void main()
{
dot(); // Function call
dot();
dot();
}

void dot(void) // Function definition


{
printf(".");
}

Internationally recognized as a way to request help in an emergency situation, an “S O


S” signal is a well-known distress signal.

The alphabet 'O' is formed by 3 dashes.

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 31 of 35


Modify the above program to send out the signal, “S O S” repeatedly.

Write your modified program below.

Hint: Make use of the while loop to fulfil the repeated requirement.

Reflection:
1. Have you added any additional function to complete your task? How does doing so
assisted you?

2. Using what you have learnt in C programming, what would you do if you have to
encode all the alphabets in the Morse code to make it easy for one to send out any
codes?

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 32 of 35


11.2 Number System Conversion

In this section, you will revise what you have learnt in Year 1 on converting between one
number system to another. This number system can be decimal, binary or hexadecimal.

To indicate a binary number in program writing, we use the 0b prefix, then followed by
the binary number. For example:
0b00001111 is the binary number for 15.

To indicate a hexadecimal number, we use the 0x prefix, then followed by the


hexadecimal digits. For example:
0x0F is the hexadecimal number for 15.

Ponder: Why do you think microcontrollers use binary instead of the most common
decimal system?

___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________

1. Decimal to Binary
Divide the number by 2, keep track of the remainder

12510 = ?2 Least Significant Bit (LSB)

Most Significant Bit (MSB)


12510 = 0b1111101 15710 = 0b10011101

Note: Binary numbers are usually prefixed with 0b' characters.

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 33 of 35


2. Binary to Decimal:
0b101011 => 1 x 20 = 1
1 x 21 = 2
LSB 0 x 22 = 0
1 x 23 = 8
0 x 24 = 0
1 x 25 = 32
------
4310

3. Binary to Hexadecimal
Technique
• Group bits in fours, starting on right

10101110112 = ?16

10 1011 1011
2 B B

10101110112 = 0x2BB

Note: Hexadecimal numbers are usually prefixed with 0x characters.

4. Hexadecimal to Binary
Technique
• Convert each hexadecimal digit to a 4-bit equivalent binary representation

10AF16 = ?2

1 0 A F
0001 0000 1010 1111

10AF16 = 00010000101011112

Exercise 11.2:
Convert the following: Note: Do not use a calculator!
Decimal Binary Hexadecimal
33
0b1110101
0x1AF

~ End of Lab 1 Extra ~

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 34 of 35


Appendix A: C Keywords

These are the reserved words or keywords in C programming language, and they must
be written in lower case.

auto break case char continue const


default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while
while

Appendix B: Comparison Between C and Python

The table below compares the basic structure of a C program with one in Python.

C Program Python
Uses // for comment. Uses the # symbol.

 Uses printf() for printing to console.


• Uses print().
 Uses #include to tell compiler to include
• Uses the import statement to
the stdio.h header file before actual
include other Python modules
compilation.

A header file (with the extension .h) is one


where you can place shared constants or Does not have header files.
declarations of functions.

The main() function is the entry point to the Not necessary to have a main
program. Every program must have one and function. The Python interpreter
only one main() function. executes from the top of the file.

Removed the need to terminate a


Terminates a statement with the semicolon ;
statement with this punctuation.

MCAPP (EMC3006) Apr 25 Property of TP, Copyright © Lab 1 (C Programming) | Page 35 of 35

You might also like