Академический Документы
Профессиональный Документы
Культура Документы
Workbook
May 2013
1. C programming 1
2. Operators, assignments and input functions 10
3. Variables 16
4. Number systems and types of operators 23
5. Selection structures 32
6. Program constructs and repetitions 43
7. Nested loops 52
8. Introduction to functions 57
9. User-defined functions with arguments 63
10.Basic on pointers 69
11.Functions, pass by value and pass by reference 74
12.Arrays 79
13.Strings 87
14.Files 94
15.Structure in C 100
16.Appendix A: Operating system-Linux 103
17.Appendix B: Interfacing 110
Universiti Teknologi PETRONAS
UNIT 1: C PROGRAMMING
This unit will cover the following topics:
(i) Introduction to text editor
(ii) Generating a simple C program
(iii) Compiling a C program
Figure 1.1
Before examining the text editor, let us examine the Ubuntu desktop, Figure 1.1 is from a
typical Ubuntu Desktop. Yours might differ slightly from the one shown.
gedit text editor
Text files or source files in Ubuntu can be created with the „gedit‟ text editor. The editor can
edit the text files.
Figure 1.2
Method 2:
The second method is through a Terminal, which can be seen in Figure 1.4.
Once the Terminal has been activated, the following window would be created. In the
Terminal, gedit can be typed to activate the editor.
Once the editor application starts, the following editor window would open in order to create
a file.
Figure 1.3
In creating a file, after typing the code the file can be saved by clicking on File -> Save As
option to save a new file.
Figure 1.4
In saving a new file, the file has to be saved with an extension of “.c”. Also Figure 1.5
indicates that the file can be located at the appropriate folder by clicking on the correct folder.
For example, create a new file called simple.c with no entry or source code.
Figure 1.5
After the saving of the file, the editor can be used to open other files by opening files using
the pull-down menu options and the editor can terminated using the pull-menu options.
To invoke or start gcc, a terminal has to be started or use the terminal already started earlier.
In the terminal, at the „$‟ prompt, the following can be typed to compile a file called
simple.c
./simple.o
#include <stdio.h>
main ( )
{
Load your editor and type the above program and compile it. Once the program is compiled
execute it.
Q1.1. When compiling, what are the errors reported by the compiler? How did you fix
them? Write down three of the errors:
main () The word main must appear once and only once in every C program.
It is the point where program execution begins. It must exist as an
entry point to the program. The () is a pair of parentheses which
indicates to the compiler that this is a function.
{ The two curly brackets or braces, are used to define the boundaries or
}
limits of the program. Program statements go between the two
braces. In this program there are no statements as a result the
program does nothing.
#include <stdio.h>
main ( )
{
printf ("Hello world!");
}
Load your editor and type the above program and compile it. Once the program is compiled
execute it.
printf ( ) is a function for displaying text to the monitor screen. The text to be
displayed is put within the function parentheses and enclosed by
quotation marks.
#include <stdio.h>
int main (void)
{
printf ("Hello world!");
return (0);
}
Load your editor and type the above program and compile it. Once the program is compiled
execute it.
show that the main function returns an integer value. More on int
later.
main (void) The word void indicates that the main function receives no data
from the operating system.
return 0 This reserved word terminates the main function and returns the
control from the main function to the operating system.
Activity 1.6
Modify the previous program so that it displays the message Welcome to ECB 1063. Record
the modification that you made in the blank space below:
Load your editor and type the following program and compile it. Once the program is
compiled execute it.
/* Program 1.7 – Displaying Text Using Control Characters */
#include <stdio.h>
main ( )
{
printf("This is a line of the text to output .\n")
printf("And this is another");
printf("line of text .\n\n");
printf("This is a third line .\n");
}
The following some of the backslash character constant that are used with C programs;
Code Purpose
\b Backspace
\f Form feed
\r Carriage return
\t Horizontal tab
\0 Null
\\ Backslash
In the following blank space, write the statements that produce the above output.
Which of the following statements are correct and which are not, and why? Write
your answers in the blank space provided.
main ( )
{
int index;
index = 13;
printf ("The value of the index is %d\n", index);
index = 27;
printf ("The value of the index is %d\n", index);
index = 10;
printf ("The value of the index is %d\n", index);
}
Load your editor, type in the above program and compile it. Fix all the errors that the
compiler reported. Once the program is compiled successfully, execute it.
%c single character
%s string
%d signed decimal
%f floating point (decimal notation)
%e floating point (exponential notation)
%g floating point (%f or %e, whichever is shorter)
%u unsigned decimal integer
%x unsigned hexadecimal integer (uses “abcdef”)
%o unsigned octal integer
+ addition
- subtraction
* multiplication
/ division
% modulus division
The modulo operator (%), gives the remainder if two variables are divided. It can only be
applied to "int” or "char" type variables and of course "int" extensions such as "long"
and "short" etc.
Activity 2.1
Load your editor and type the following program and compile it. Once the program is
compiled execute it.
#include <stdio.h>
firstno, These are variables are declared. They are each given a name
secondno, and a type. int is an integer type.
The reminder operator which is also known as the modulo operator is not so common. For
example, in the following program fragment, the variable answer is assigned the value of 3,
since that‟s the remainder when 13 is divided by 5;
answer = 13 % 5
Activity 2.2
Load your editor and type the following program and compile it. Once the program is
compiled execute it.
result = a%b
printf ("result = %d\n", result);
}
2.1.2 Assignment
Other examples:
x=z;
numl = 4.5;
half = number/2;
Activity 2.3
Load your editor and type the following program and compile it. Once the program is
compiled execute it.
The increment (++) and decrement (--) operators are very useful. The ++ operator adds one to
the operand and the – operator subtract one from the operand. The following illustrate the
operation;
ACTIVITY 2.4
Load your editor and type the following program and compile it. Once the program is
compiled, execute it.
int main(void)
{
int Answer1, Answer2, Number1, Number2;
Number1 = 4;
Number2 = 4;
Answer1 = Number1++;
Answer2 = Number2--;
printf("\n%d,%d", Answer1, Number1);
printf("\n%d,%d", Answer2, Number2);
return(0);
}
Up until now the programs that we have been using are non-interactive, that is, the program
user is not require to „communicate‟ with the program. In a lot of situations the program user
is require to input data into the program. To do this in a C program the scanf() function
can be used. The scanf() copies or reads data and store it in a variable. The following code
shows how C reads data and assigns it to variable.
ACTIVITY 2.5
Load your editor and type the following program and compile it. Once the program is
compiled, execute it.
scanf("%d", scanf reads formatted input from a standard input, which is usually
&Number); the keyboard. scanf arguments are a formatting control string,
enclosed in quotation marks. In this example, ‘%d‟ is formatting control
string for signed decimal. The variable‟s address is „&Number‟. The
symbol & is known as the ampersand. The scanf function requires the
use of the ampersand before the variable name.
Let us see how scanf can be used in a more meaningful way. Consider the following
program.
/* Program 2.6 - This program reads two numbers from the keyboard
and displays the sum on the monitor screen
*/
#include <stdio.h>
Activity 2.6
Load your editor and type the above program and compile it. Once the program is compiled
execute it.
UNIT 3: VARIABLES
This unit will cover the following topics:
(i) Constant
(ii) Variable
(iii) Identifier
(iv) Data types in C
Variables and constants are manipulated by operators within a program to form expressions.
In C, constants refer to fixed values that cannot be changed by the program. Constants can be
of any basic data types. How these constants are represented depends on its type. The way
each constant is represented depends upon its type. More on types later.
A variable is a data which changes in value when the program is executed. A variable can
also be viewed as a space in memory that contains different value at different times.
Generally a variable is given a name. The names of the constants, variables and function
names are called identifiers. An identifier in the C language can vary from one to several
characters.
Before a constant or variable can be used, they must first be declared. This is known as
declaration. The general form of a variable declaration statement is as follows;
type variable_list
The type must be a valid C data type and the variable_list may consist of one or more
identifier names with comma separators. The following program fragment is an example of a
typical C variable declaration.
#include <stdio.h>
#define PI 3.1415926 /* constant */
Activity 3.1
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
1. Character (char) constants „a‟ and „%‟ are both character constants
2. Integer (int) constants 10 and -100
3. Floating point (float) constants 10.246
4. Long integer (long int) 35000 or any number great than
5. Double-precision floating point 123.33, 12312333, -0.9876324
(double)
6. Short integer (short int) 10 -12 90
7. Unsigned integer (unsigned int) 10000 987 40000
int main(void)
{
int a = 100000; // simple integer type
long int b; // long integer type
short int c; // short integer type
printf("\n\tVAR\tINT\t\tLONG\t\tUNSIGNED\n");
printf ("\t a %15d %15ld %15u \n", a, a, a);
b = a*10000;
printf ("\t b %15d %15ld %15u \n", b, b, b);
b = a*100000;
printf ("\t b %15d %15ld %15u \n", b, b, b);
c = a/10;
printf ("\t c %15d %15ld %15u \n", c, c, c);
d = a/10;
printf ("\t d %15d %15ld %15u \n", d, d, d);
c = a;
printf ("\t c %15d %15ld %15u \n", c, c, c);
d = a;
printf ("\t d %15d %15ld %15u \n", d, d, d);
return 0;
}
Activity 3.2
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
int main(void)
{
float p = 3.14159; // floating point type
double pi = 3.1415926535898; // double precision floating point
return 0;
}
Activity 3.3
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
It should be obvious from the program how various types are output using the "printf"
statement.
The following is a list of format specifiers or conversion characters that can be used with the
"printf" statement. Each of these is used with an ampersand sign to indicate the type of output
conversion
%d decimal notation
%o octal notation
%x hexadecimal notation
%u unsigned notation
%c character notation
%s string notation
%f floating point notation
In addition the following fields may be added between those two characters.
A string is a type of data used in programming language for storing and manipulating text,
such as words, names, and sentences. In C string is an array of type char. Consider the
following program fragment;
where “Hello, welcome to ECB 1063” is the string. The following is another
example;
printf ("%s","Hello");
"Hello" is known as a string constant and that means that the string itself is stored
someplace in memory.
Activity 3.4
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
Activity 3.5
On paper, design/draft a program that performs the following steps:
Load your editor and type in your program and compile it. Fix any compilation
errors reported by the compiler. Once the program is compiled successfully,
execute it.
Computer hardware is closely connected to the binary number system. However for computer
programmers, binary numbers are difficult to work with. There are other useful number
systems that can help programmers overcome the awkwardness of the binary number system.
0 0000 0 0 10 1010 A 12
1 0001 1 1 11 1011 B 13
2 0010 2 2 12 1100 C 14
3 0011 3 3 13 1101 D 15
4 0100 4 4 14 1110 E 16
5 0101 5 5 15 1111 F 17
6 0110 6 6 16 1 0000 10 18
7 0111 7 7 17 1 0001 11 19
8 1000 8 10 18 1 0010 12 20
9 1001 9 11 19 1 0011 13 21
Example:
Examples:
#include <stdio.h>
int main(void)
{
int a = 123;
return 0;
}
Activity 4.1
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
4.2 Operators in C
Apart from the common operators discussed earlier there are other operator types, for
example:
If Num1 has the value of 3 then Num2 will have the value of - 3. This operator also makes
a negative number positive (it takes the two's complement).
If Num1 has the following binary bit pattern: 0000111101010011, then Num2 will have
the opposite bit pattern: 1111000010101100
If Num1 has the value 0 then Num2 will be given the value 1.If Num1 has a non-zero value
then Num2 will be given the value 0.
#include <stdio.h>
int main(void)
{
int a, b, c;
a = 3;
b = 0x1;
c = 0x1;
b = !b; /* not operation */
c = ~c; /* complementary */
a = -a; /* make negative */
printf ("%d\n",a);
printf ("%x\n",b);
printf("%#x\n",c);
return (0);
Activity 4.2
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
A binary operator is an operator that operates with two operands. For example, when the +
and – are used to carried out addition and subtraction, they are known as binary operators.
Example,
a=b+c
a=b-c
are binary operators.
Relational operators
Operator Action
int main(void)
{
int a, b, c;
a = 100;
b = 90;
c = 0;
return (0);
}
Activity 4.3
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
Operato Action
r
&& Logical AND
|| Logical OR
! Logical NOT
int main(void)
{
int a, b, c;
a = 100;
b = 90;
c = 0;
return (0);
}
Activity 4.4
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
One of the problems in C is writing out mathematical expressions or formulas. For example
for formulas with division, we normally write the numerator on top of the denominator
separated by a line,
b− c
a=
d+e (i)
However, in C, the numerator and denominator are written on the same line. Equation (i) is
be written as
Brackets or parenthesis are used to separate the numerator from the denominator. Equation
(ii) is written as
a=
b− c
/
d+e (iii)
Activity 4.5
Rewrite the following mathematical formulas in C.
1. 5a 2
x=
2. 5
2. b+c
a=
d+0 . 3
3.
2+j 3
k=
5
4. y= 7
6x 24
You are advised to follow the above method when undertaking programming tasks. The
method requires you to produce program documentation prior to the actual coding of a
program. The documentation should include a description of the problem that you trying to
solve, identifying the input(s) and output(s) of the program (analysis phase), the proposed
algorithm to solve the problem (design phase). In addition, you are also required to produce a
fully commented code and a test plan.
We will use the following case study to illustrate the above mentioned software development
method.
Problem: Get the inductance of an inductor. Compute and display inductive reactance of
the circuit.
Analysis: The inputs to this problem are frequency and inductance of the inductor. Only
one output is required, that is, the inductive reactance. The inputs and output
of this problem may be decimal fraction, so the data type is float or double.
The mathematical relationship can be expressed as
Data Required:
Input(s): frequency /* frequency */
inductance /* inductance */
Output(s): iReactance /* inductive reactance */
Constant(s): Two_PI 2 x 3.14159
Algorithm Refinements
Step 2: in the initial algorithm can be further refined, that is more detail can be
added.
iReactance = Two_PI * frequency * inductance
Testing: Decide on the type of inputs, example integer, floating-point, string, char and
etc. Write down the expected output. Run the program with the inputs you
have listed earlier. Record the actual outputs and compare the expected output
with the actual output.
Test Plan:
Input(s) Expected output(s) Actual output(s) Comments
Inductance
Activity 4.6
Based on the above case study, draft a C program in the blank space below
Load your editor and type in your program and compile it. Fix any compilation
errors reported by the compiler. Once the program is compiled successfully,
execute it.
In the following blank space, record a sample output of the program based on the
test plan provided. Fill in the test plan table with the acquired values and add
comments about the test result.
(i)Program constructs
(ii)if statement
(iii)Relational operators
(iv)Boolean operators
(v)switch statement
LET a = b
IF a = 10 GOTO 15
LET y = a
IF y = 20 GOTO 10
PRINT “Why am I here?”
GOTO 12
. . .
If large programs are written in the above style, it can be difficult to follow and understand.
To encourage programmers to write programs that are easy to follow, structured programming
is encouraged. With structured programming, programs have a single entry and single exit.
There are three basic programming constructs which describe the flow of any computer
programs. These program constructs are;
(i)Sequence
(ii)Selection
(iii)Repetition
5.1.1 Sequence
Up until now the programs that you have written, program statements are executed
sequentially, that is each program statement is executed one after another. This illustrated in
the following program fragment.
With reference to the above code fragment the printf ("a = %d\n", a); is executed first
and then printf ("b = %ld\n",b); is executed and the next statement is executed and
so on.
5.1.2 Selection
With the selection construct, the direction of the flow of control of the program is dependent
on the outcome of a logical test. One way of implementing the selection construct in C
programming is the use of if statement.
The if statement
This section will deal with the simplest form of an if statement and the other form will be
covered later.
FORMAT:
if (condition)
{
Statement(s);
}
MEANING: If the expression or condition after the word „if‟ is true then the statement that,
follows after the condition will be executed. If the condition is false then the statement(s)
will be ignored. This is illustrated in the following flow-chart.
#include <stdio.h>
if (guess_input == 1)
printf("Right number!\nWell done.\n");
return(0);
}
In the above program, if the user types in the digit then the statement, printf("Right
number!\nWell done.\n"); will be executed. If guess_input is not equal to 1 then the
statement will be ignored and the program will terminate.
The expression guess_input == 1 in the above program make use of a „==‟ operator. This a
relational operator.
Activity 5.1
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
In the following blank space record the output of the program. (Underscore
your input to differentiate it from the outputs)
Activity 5.2
Modify the above program so that the message „Correct number‟ will
be displayed when the user types in the number 101.
In the following blank space record the statements that you have modified in
order to achieve the above task. (Underscore your input to differentiate it from
the outputs)
The else statement can be associated with if. The format is as follows;
FORMAT :
if (condition)
{
statement(s);
}
else
{
statement(s);
}
MEANING: If the condition expression is true then the following statements after the if will
be executed. If it is false, then the statements after else will be executed. This is illustrated
in the following flow-chart.
#include <stdio.h>
if (guess_input == 1)
printf("You got it right!\n");
else
printf("Wrong number, dude!\n");
return (0);
}
Activity 5.3
Load your editor and type the above program and compile it. Once the
program is compiled execute it twice. For the first time, enter a number other than
101 as the input. For the second time, enter 101 as the input.
In the following blank space record the inputs and outputs of the program.
(Underscore the inputs to differentiate them from the outputs)
In the above program, if guess_input is equal to 1 then the statement printf ("You
got it right!\n"); is executed. If guess_input is not equal to 1, then the
statement printf("Wrong number, dude!\n"); will be executed.
Operator Action
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
== Equal
!= Not equal
#include <stdio.h>
int main(void)
{
int a, b;
if( a == b )
printf("The numbers are equal\n");
if( b != b )
printf("The numbers are NOT equal\n");
if( a < b )
printf("%d is less than %d\n", a, b);
if( a > b )
printf("%d is more than %d\n", a, b);
return(0);
}
Activity 5.4
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
In the following blank space record the inputs and outputs of the program.
(Underscore the inputs to differentiate them from the outputs)
The logical operators are used to support basic logical operations like AND, OR, and NOT.
There are three logical or Boolean operators in C;
Operator Action
&& AND
|| OR
! NOT
#include <stdio.h>
int main(void)
{
int num, ans;
return(0);
}
Activity 5.5
Load your editor and type the above program and compile it. Once the
program is compiled, execute it.
In the following blank space record the inputs and outputs of the program.
(Underscore the inputs to differentiate them from the outputs)
Activity 5.6
Modify the previous program by replacing the && (and) symbol with a || (or)
symbol.
A lot of programs require a user to make a choice from a list of possibilities. There are two
methods to do this:
5.3.1 if-else-if
A common programming construct is the if-else-if. Using this method, the program
will run through a list of if-else-if statements until a „match‟ is found. The problem
associated with this method is that each if-else-if statement must be written out in full and
this makes the program long and uneconomical.
if (user_entry ==1){
printf("Number One\n");
}
else {
if (user_entry ==2){
printf("Number Two\n");
}
else {
if (user_entry ==3){
printf("Number Three\n");
}
else {
if (user_entry==4){
printf("Number Four\n");
}
}
}
}
return (0);
}
Activity 5.7
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
In the following blank space record the inputs and outputs of the program.
(Underscore the inputs to differentiate them from the outputs)
Although the if-else-if construct can perform multiple tests, it is hardly elegant.
Structurally, the important thing to note is that the if-else-if constructs are nested. Refer
to the above program. As the number of if-else-ifs’ increases, the nesting and the
resulting indentation gets quite deep, making the program difficult to read.
if (user_entry ==1) {
printf("Number One\n");
}
else if (user_entry ==2) {
printf("Number Two\n");
}
else if (user_entry ==3) {
printf("Number Three\n");
}
else if (user_entry==4){
printf("Number Four\n");
}
return (0);
}
The above program will operate exactly same as the previous program. The only difference is
that indentation is rearranged to the program easier to read.
switch (user_entry){
case 1:
printf("Number One\n");
break;
case 2:
printf("Number Two\n");
break;
case 3:
printf("Number Three\n");
break;
case 4:
printf("Number Four\n");
break;
default:
printf("Number is out of range");
break;
}
return (0);
}
Activity 5.8
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
In the following blank space record the inputs and outputs of the program.
(Underscore the inputs to differentiate them from the outputs)
Exercise 5.1 Design a program that will convert a single integer 0 to 9, into the resistor
colour code. The relationship is as follows:
Input(s):
Output(s):
Pseudo-code:
Load your editor and type the above program and compile it. Once the
program is compiled, execute it.
In the following blank space record the inputs and outputs of the program.
(Underscore the inputs to differentiate them from the outputs)
Definition of a loop
while statement
do while statement
for statement
The programs covered so far are limited in that they can only be executed once for a given set
of data. This problem can be overcome with loops. A loop may be defined as a smaller
program that can be executed several times in the main program. There are several techniques
in achieving this in C. This unit will describe these techniques.
FORMAT :
while (condition){
Statement(s)
}
MEANING:With the while statement, the condition is first tested and if the condition is true
then the statement or statements within the loop will be executed. The condition will be tested
repeatedly until the condition is false.
Example
Activity 6.1
Before running the program, list its output(s):
Load your editor and type the above program, complete it and compile it. Once
the program is compiled execute it.
Activity 6.2
Amend Program 6.1 with the following changes and list the output of the
amended programs.
Q3. If variable „count‟ in not maintained or updated, determine the effect on the
execution of the program. Change line „count = 8„ back to its original form
„count = 0„ ; and delete line „count = count + 1 „. Compile and run
the program.
FORMAT:
do {
Statement(s)
} while (condition);
MEANING
The do-while loop checks the condition at the end of the loop. This means that the
statement or statements inside the do-while loop will be executed if the condition is true. If
the condition is false, the do-while loop will not be executed.
Example
The following program is an example of a do-while;
main ()
{
int num;
do {
scanf(“%d”, &num);
} while (num>10);
}
Activity 6.3
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
In the following blank space record the output of the program. (Underscore your
input to differentiate it from the outputs)
while (num>10) This is the condition that will check for the end of the loop.
The above program will read numbers that are being keyed in
by the user until the number is less than 10.
The difference between do-while and while construct is that, the program to be repeated
within the do-while loop will always be executed at least once. Whereas the while loop
allows for the condition where the program to be repeated is never executed. The following
flow-charts illustrate the difference.
for statement
The for statement is used when the number of executions of a loop is known.
FORMAT
MEANING: Initialization is used to set the loop control variable to an initial value. Condition
is an expression that is tested each time the loop repeats. As long as it is true (non zero), the
loop will be executed repeatedly. The increment part increments the loop control variable.
main ( )
{
int index;
for (index = 0; index < 4; index = index + 1)
printf (“The value of the index is %d\n”, index);
}
Activity 6.4
Before running the program, list its output(s):
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
Activity 6.5
Amend Program 8.3 with the following changes and list the output of the
amended programs.
EXERCISES
Exercise 6.1 In the following blank space, design a program that lists all the odd numbers
between 0 and 100.
Enter the program and compile it. Once the program is compiled execute it. In
the following blank space record the output of the program.
Exercise 6.2 In the following blank space, design a program that lists all numbers between
0 and 100 that can be divided by 3.
Enter the program and compile it. Once the program is compiled execute it. In
the following blank space record the output of the program.
Repeat
Ask user to enter a number (from 1 to 100)
input n
total = ......
Until user entered n<1 or n>100
A nested loop is often described as “a loop within a loop”. The way how it works is that
during the first pass of the outer loop, the inner loop is triggered, which executes until it is
completed. Then the second pass of the outer loop triggers the inner loop again. This will
carry on until the outer loop finishes. This process can be interrupted if a break occurs within
either the inner or outer loop. The following activities will illustrate this.
Activity 7.1
Consider the following program segment:
for (row=0;row<4;row++)
{
for(col=0;col<4;col++)
printf("# ");
printf("\n");
}
Load your editor and type the above program, complete it and compile it. Once
the program is compiled execute it.
Activity 7.2
Consider the following program segment:
for (row=1;row<5;row++)
{
for(col=1;col<row+1;col++)
{
printf("& ");
}
printf("\n");
}
Load your editor and type the above program and compile it. Once the program is
compiled execute it.
outer
inner
loop
loop
Activity 7.3
Write a program using nested loops that produce the following output:
7777777
666666
55555
4444
333
22
1
Show your program and its output to a Teaching Assistant for verification.
Activity 7.4
Write a program that produces the following output:
--------->
-------->>
------->>>
------>>>>
----->>>>>
---->>>>>>
--->>>>>>>
-->>>>>>>>
->>>>>>>>>
Show your program and its output to a Teaching Assistant for verification.
Activity 7.5
Consider the following program segment:
printf("start \n");
do {
printf("j = %i \n", j--);
}while (j > 0);
printf("end.\n");
printf("\nAnd again\n");
j = 5;
printf("Start \n");
do {
printf("j = %i \n", j);
j--;
}while (j > 0);
printf("end \n");
return 0;
}
Load your editor and type the above program and compile it. Once the program is
compiled execute it.
Activity 7.6
Write a program that produces the following output:
>
-->
---->
------>
-------->
---------->
------------>
---------->
-------->
------>
---->
-->
>
Show your program and its output to a Teaching Assistant for verification.
EXERCISES
Write a program that print a multiplication table of the size determined by the
user, up to to 18 x 23. Your program must produce output similar to the
following example:
1 2 3 4 5
+--------------------
1 | 1 2 3 4 5
2 | 2 4 6 8 10
3 | 3 6 9 12 15
4 | 4 8 12 16 20
5 | 5 10 15 20 25
6 | 6 12 18 24 30
7 | 7 14 21 28 35
A function may be given any name, with the exception of main(). Remember, main() is
reserved for the function that begins execution (starting point) of any C program. As a rule,
no function can have the same name as a reserved word.
function call
X = log (y);
function argument
name
The log() function is used to perform the natural logarithm of y. Note y is known as the
argument which is used to convey information to the log() function. The subject of
argument will be discussed in more detail later.
The following table lists some of the common C mathematical functions used in electrical
and electronics engineering problems. Note, not all mathematical functions are listed.
x = exp(0.1);
y = log10(100);
z = sin(90);
printf("%f\n",x);
printf("%lf\n",y);
printf("%f\n",z);
return (0);
}
Activity 8.1
Load your editor and type the above program and compile it. Once the program
is compiled execute it.
What is the complete command that you use to compile the program?
main()
Function definition
A function must be declared before it can be called. To declare a function, you have to insert
the function prototype before the main() function. The purpose of the prototype is to inform
the compiler the data type of the function, the name of the function, and information about
the arguments.
Note that a special data type called void is used in the function prototype and function
definition. Declaring a function with a void return type indicates that the function does not
return any kind of data.
Function name
{
body of code
}
The above is an example of a user defined function where we use the function name,
display_hello.
Activity 8.2
Load your editor and type the above program (Program 8.2) and compile it. Once
the program is compiled execute it.
main()
display_hello()
Basically a structured chart is used to show how a program can be divided into functions as
illustrated in the above diagram. The main() function or any other C function can call more
than one function.
At the top of the chart is a box that represents the entire program. At the next level the boxes
represents the smaller programs or sub-programs (or functions). Each sub-program or box
represents some function in the system, and therefore it is advisable to use meaningful verb
phrase to describe its function, for example, "display_name".
main ()
Top level
display_hello () display_name ()
Quiet often structured charts are mistaken for flow charts. This not the case, a structured chart
is NOT a flowchart and it does not show the order in which tasks are performed. A structured
chart is a graphical representation of different functions of a program.
#include <stdio.h>
Activity 8.3
Write a C program to print your name, address and telephone number in the
following format:
Name . . . . . .
Address . . . . . .
Telephone . . . . . . . .
Use three functions to complete the above programming task. You must draw
the structured chart for the program.
Load your editor, type in your program and compile it. Once the program is
compiled execute it. Show your program and its output to a Teaching Assistant
for verification.
C functions were introduced in Unit 8 and this unit will continue with the discussion of
functions whilst introducing more advanced features of C functions. The topics that will be
covered are:
The following program shows how a value is passed to a user-defined function. The value is
passed using the function‟s argument. In this case, there is only one single argument. The
function itself does not return any result.
/* Program 9.1
Function with single argument, no result
*/
#include <stdio.h>
// function prototype
void disp_cube(int n);
int main()
{
int x = 2;
disp_cube(x); // function call
printf("x = %d\n", x);
return(0);
}
// function definition
void disp_cube(int n)
{
printf("%d^3 = %d\n", n, n*n*n);
}
Activity 9.1
Load your editor and type the above program and compile it. Once the program is
compiled execute it.
In the program, the data, x, is passed to the user-defined function, disp_cube(), and the
value of x³ is displayed. This is an example of function with single argument and no result is
returned, as illustrated by the following figure.
The following program shows how a value from a user-defined function is returned to the
main function.
/* Program 9.2
Function with single argument, single result
*/
#include <stdio.h>
// function prototype
int main()
{
int x = 2, y;
return(0);
}
// function definition
int cube(int n)
{
return(n*n*n);
}
Activity 9.2
Load your editor and type the above program and compile it. Once the program is
compiled execute it.
Notes: When the function cube() is called, the value of x is passed (copied) to argument
n. The function cube() returns the value of n³ to the calling function, that is the
main() function.
The following diagram illustrates this situation, where the value of x copied over to n is 2.
Thus, the function cube returns a value of 8.
Activity 9.3
As mentioned earlier an argument refers to the value that is inside the brackets of the function
being called. The variable that receives the value of the argument used in the called function
is known as a formal parameter of the function. The number of arguments used to call a
function must be the same number as formal parameters listed in the function prototype. The
order of arguments determines the correct assignment of data.
The following program demonstrates how two arguments are passed to a function. It also
highlights the relationship between formal parameters and arguments.
/* Program 9.4
Multiple Arguments vs Formal Parameters
*/
#include <stdio.h>
Activity 9.4
Load your editor and type the above program and compile it. Once the program is
compiled execute it.
The following activity is another example of how a value from a function is returned to the
main() function.
/* Program 9.5
Multiple Arguments, single result
*/
#include <stdio.h>
/* Declaring a function */
int power_f(int x1 , int y2);
Activity 9.5
Load your editor and type the above program and compile it. Once the program is
compiled execute it.
Q1. Did the output of the program confirm your answer? YES / NO
result = power_f(x,y);
to
result = power_f(y,x);
Write down the output:
You should note that return can only return one value at a time. This can be a serious
limitation. We will look into how to return more than one value in the next unit.
EXERCISES
Exercise 9.1 Write a program that calculates and print all the values of sine x where x is 0 to
180 degrees. The calculation of sine in degrees must be done via a user-
defined function (see one of previous programs).
A pointer provides a way of accessing variables without directly referring to the variable. A
pointer variable is declared by placing an asterisk in front of the variable name:
In the above example, *var1 holds the variable value, while var1 holds the address
(location) where the variable is stored in the system memory. The address of a pointer
variable not that useful in a program but the compiler uses that information to have access to
the actual value held by the variable.
To get the address of a variable that is not of pointer type, the symbol ampersand (&) can be
used. The symbol %p is used with printf() to display the address of a pointer:
The following program shows the relationship between variables and their memory
addresses.
/* Program 10.1
Pointers and Their Memory Addresses
*/
#include <stdio.h>
int main()
{
int x, y;
int *xptr, *yptr;
xptr = &x;
yptr = &y;
return 0;
}
Activity 10.1
Load your editor and type the above program and compile it. Once the program
is compiled, execute it. Observe the difference in the output of each time the
program is modified.
Q2. Change the data type int with float for all the data and pointers.
List the output of the program.
Q3. Now, change the data type to char. List the output of the program.
Q4. Now, change the data type to double. List the output of the program.
The following program shows how memory addresses are utilized when a function is
involved.
/* Program 10.2
Pointers and Their Memory Addresses II
*/
#include <stdio.h>
int main()
{
int x;
int *xptr;
xptr = &x;
return 0;
}
Activity 10.2
Load your editor and type the above program and compile it. Once the program is
compiled, execute it. Observe the outputs.
What do you think happens when the data is passed to the function?
If a function parameter is of basic type (int, float etc.), when an argument is through this
parameter (during function call), the argument is passed by value. If a function parameter is
a pointer, the argument is passed by reference. The following program demonstrates the two
types of argument passing.
/* Program 10.3
Function arguments: Passing by value and passing by reference
*/
#include <stdio.h>
// Function prototype
void change_values(int, int *);
// Main function
int main()
{
int x = 1, y = 2; // integers
return 0;
}
// Function definition
void change_values(int any, int *anyptr)
{
printf("\tStart of function: any = %d, *anyptr = %d \n", any, *anyptr);
any = 100;
*anyptr = 2000;
printf("\tBefore function ends: any = %d, *anyptr = %d \n", any, *anyptr);
}
Activity 10.3
Load your editor and type the above program and compile it. Once the program is
compiled, execute it. Observe the outputs.
What do you think happens when the data is passed to the function?
/* Program 10.4
More about function call and pointers
*/
#include <stdio.h>
// Function prototype
void swap_them(int *, int *);
// Main function
int main()
{
int x = 1, y = 2; // integers
int *xptr, *yptr; // integer pointers
xptr = &x; // point xptr to address of x
yptr = &y; // point yptr to address of y
return 0;
}
// Function definition
void swap_them(int *a, int *b)
{
int tmp;
Activity 10.4
Load your editor and type the above program and compile it. Once the program is
compiled, execute it.
This unit will demonstrate how multiply values can be passed to a function using pointers.
Early session showed how a single value can be passed from the main program to a function
and vice versa. As we have mentioned in previous units, the return() statement has a
limitation, that is, it can only return one value from a function to the calling function. Pointers
are used to address this limitation.
Activity 11.1
Consider the following program:
int main()
{
int var1=3;
int var2=4;
passing(var1,var2);
printf("The value of var1 is %d \n",var1);
printf("The value of var2 is %d \n",var2);
return 0;
}
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
The above program simply displays the two values that is been passed from the
passing(var1,var2). However it does demonstrates one important point, that is, the
function received two values from the calling function.
Note that the function gives the two values different names. In this case var1 and var2 are
rename num1 and num2 in the function passing(var1,var2). The function then can
operate the new variables, num1 and num2, without affecting the original var1 and var2.
int main()
{
int var1=3;
int var2=4;
passing(var1,&var2); Calling Function
printf("The value of var1 is %d \n",var1);
printf("The value of var2 is %d \n",var2);
return 0;
}
3 4 Function
void passing(int num1, int num2)
{
printf(“First no. is %d, second no. is %d”, num1, num2);
return 0;
}
Activity 11.2
Consider the following program:
int main()
{
int var1=3;
int var2=4;
int answer;
answer = passing(var1,var2);
printf("The value of var1 is %d \n",var1);
printf("The value of var2 is %d \n",var2);
printf("The sum of var1 and var2 is %d \n",answer)
return 0;
}
Load your editor and type the above program and compile it. Once the program is
compiled, execute it.
The program in Activity 11.2 is expanded from Activity 11.1 where the values of var1 and
var2 have been passed to function passing. And only one data is returned from the
passing function which is assigned to the answer variable.
int main()
{
int var1=3;
int var2=4;
int answer;
answer = passing(var1,var2);
printf("The value of var1 is %d \n",var1);
printf("The value of var2 is %d \n",var2);
printf(“The sum of var1 and var2 is %d \n”,answer);
return 0;
}
Calling Function
Activity 11.3
Load your editor and type the above program and compile it. Once the program is
compiled, execute it.
Like the previous program, the above program does not do anything spectacular. The calling
function, main(), calls the Pass_values() function. The Pass_values() function
passes two values, 3 and 5, to the main () function. The calling function, that is,
main(), then displays the two values.
Like all variables, the places set aside for these addresses, px and py, must be declared. The
variables must first be declared so that the compiler will know how much memory space to
set aside for them and what names to give them. Declaring a pointer set aside two bytes of
memory. A typical pointer declaration is as follows:
The asterisk (*) is used to indicate the variable is a pointer, that is, it will hold an address.
Note the asterisk must be used before each variable.
The following program demonstrates how multiple values are passed to a function and also
how multiple values are passed to the calling function.
#include <stdio.h>
void calc(int n1,int n2,int *mul_res, int *div_res)
int main(void)
{
int num1,int num2;
Activity 11.4
Load your editor and type the above program. Make corrections as necessary.
List the errors (and corrections) that you found (made) in the program:
After you have successfully compiled the program, execute it. List the input(s)
and output(s) of the program.
Q1. Which variables were used in the program to pass values into the calc()
function?
Q2. Which variables were used as pointers to pass values out from the calc()
function?
Up until now you have been using simple data types in all your programs, which use a single
memory cell to store a variable. For example, the variables number, score, and
temperature can be declared as
int number;
long score;
float temperature;
These variables are of different types, and each variable can only store one value. However,
you will find that you may deal with groups of similar data elements. A group of similar data
elements is known as an array. An array provides a way to refer to individual element in a
group by using the same variable name, but with a different index.
Let us assume that you are required to compute the sum of a group of prime numbers. If each
prime number had a unique variable name, you may end up with the following;
Using an array allows you to name the variables as a set with the same name but can be
distinguished from each other by using an index like this:
PrimeNumber[n]
where n is a positive integer. The value of n starts from 0 (zero) up to a limit determined
when declaring the array.
The following is a list of prime numbers, all of the same data type, int.
Prime Numbers
1
2
3
5
7
11
The above list of prime numbers of same data type is known as a one-dimensional array. All
the numbers in the above list can be declared as a single unit and stored under a common
variable name commonly known as the array name. The array must be declared before they
Activity 12.1
int main()
{
int index;
int PrimeNumber[6] = {1, 2, 3, 5, 7, 11};
for ( index=0 ; index <6 ; index ++)
{
printf("Prime [%d] = %d\n",index, PrimeNumber[index]);
}
return 0;
}
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
The second portion of the statement, = {1, 2, 3, 5, 7, 11}, initialized the elements in
the array with specific values. The values are initialized into the array in the order they are
written. Thus PrimeNumber[0] = 1, PrimeNumber[1] = 2, PrimeNumber[2] = 3,… and so
on.
Activity 12.2
Consider the following program:
int main()
{
int i;
int total = 0 ;
int primes[6] = {1, 2, 3, 5, 7, 11};
Load your editor and type the above program and compile it. Once the program is
compiled, execute it.
Activity 12.3
Consider the following program:
int main()
{
int number;
int primes[6];
return 0;
}
Before running the program, list the inputs and outputs of the program.
Load your editor and type the above program and compile it. Once the program is
compiled, execute it.
Activity 12.4
Modify Program 12.3 so that:
Load your editor and type the above program and compile it. Once the program is
compiled, execute it.
Activity 12.5
Consider the following program:
int main ()
{
int primes[6] = {2, 3, 5, 7, 11, 13};
DisplayArray(primes);
return 0;
}
Load your editor and type the above program and compile it. Once the program is
compiled, execute it.
Activity 12.6
Consider the following program:
#define ROW 2
#define COL 3
int main ()
{
int row,col;
int matrix1[ROW][COL] = {{1, 2, 3}, {4, 5, 6}};
return 0;
}
Load your editor and type the above program and compile it. Once the program is
compiled, execute it.
Activity 12.7
Consider the following program:
AddMatrix(matrix1,matrix2,matrix_ans);
DisplayResult(matrix_ans);
return 0;
}
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
EXERCISES
Exercise 12.1
(a) Modify Program 12.5 to add a function that have the following
characteristics:
Name: ComputeArray
Type: void
Parameters: int array[ ], int length
Computation: Calculate the sum of elements in an
integer array. Number of elements is passed via length.
Output to screen: The sum of elements in the above
mentioned array.
Exercise 12.2
(a) Based on the following program fragment, write a program that ask the
user to enter a series of characters and store them in the array myarray[].
(b) The program stops reading the input when the user entered a . (full
stop).
(c) The program also must ensure that the number of characters entered do
not exceed the array size.
(d) Display the array contents in reverse order.
#define SIZE 10
int main()
{
char myarray[SIZE];
return(0);
}
printf("%s", "Hello");
“Hello” is known as a string constant. This string is stored in memory as ASCII (American
Standard Code for Information Interchange) codes of the characters. Typically, each character
is stored as a byte. The following figure shows what the string might look like in memory.
Character H e l l o
Memory 0x000000 0x000004 0x000008 0x000012 0x000016
address
ASCII 48 65 6c 6c 6f
code
This section will briefly revisit the string variable. The following activity is example that
reads in a string from the keyboard, and using the scanf() function to get the input from
the keyboard.
Activity 13.1
return 0;
}
Load your editor and type the above program and compile it. Once the program is
compiled, execute it. Observe the differences in the outputs from the different string
input functions.
Jackie Chan
Q3. Did the program give you get the expected output? YES / NO
With reference to the above exercise, you will have noticed that the second name, Chan, was
dropped. This is because scanf() uses white space to terminate the entry of a variable. In
C, there are many functions that are designed to manipulate strings. These functions are
needed because the scanf() function has limitations when it comes to handling strings.
There is solution to this limitation, please carry on with the next exercise.
Activity 13.2
In the part Q3, the gets() function is used to get a string from the keyboard. This function
specializes in reading a string from the keyboard. The gets() function is terminated only
when the [enter] key is pressed. So the whitespaces and tabs are acceptable as part of the
input string. This overcomes the whitespaces problem encounter with the scanf() function.
There are many library functions provided for the manipulations of strings. Some of them
are:
Copies the string s2 into the character array s1. The value of s1 is returned.
Copies at most n characters of the string s2 into the character array s1. The value of s1 is
returned.
Appends the string s2 to the end of character array s1. The first character from s2 overwrites
the '\0' of s1. The value of s1 is returned.
Appends at most n characters of the string s2 to the end of character array s1. The first
character from s2 overwrites the '\0' of s1. The value of s1 is returned.
Compares the string s1 to the string s2. The function returns 0 if they are the same, a number <
0 if s1 < s2, a number > 0 if s1 > s2.
strncmp() int strncmp( const char *s1, const char *s2, size_t n)
Compares up to n characters of the string s1 to the string s2. The function returns 0 if they are
the same, a number < 0 ifs1 < s2, a number > 0 if s1 > s2.
Determines the length of the string s. Returns the number of characters in the string before the
'\0'.
Activity 13.3
Consider the following program:
main( )
{
char name1 [40]; /*the length of name 40 chars long*/
char name2 [40];
char name3 [40];
strcpy(name2,name1);
strncpy(name3,name1,5);
return 0;
}
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
Q1. List the input and output of the program.
Q2. What can you observe from the above output regarding a
problem of using strncpy()?
Write the statement that can be used to fix this problem. (Show the statement in
relation to the strncpy() statement in your program)
Activity 13.4
Consider the following program:
main( ){
char name1 [40]; /*the length of name 40 chars long*/
char master [40] ={"Alpha high"}; /*master code*/
result= strcmp(name1,master);
if (result==0)
printf("Code entered was correct ! \n");
else
printf("Code entered was incorrect ! Try again !
\n");
return 0;
}
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
Q1. List some of the input and output of the program.
List the input and output of the program. Enter short versions of the master code
to see the different outputs until the correct input has been entered.
Activity 13.5
Consider the following program:
s3 = s1;
printf("\n %s, %d chars long \n", s3, strlen(s3) );
return 0;
}
Load your editor and type the above program, make corrections as necessary and
compile it. Once the program is compiled successfully, execute it.
Activity 13.6
Consider the following program:
main()
{
char s1[] = "This is a string";
char *s2 = "This is another string";
print_string( s1 );
print_string( s2 );
return 0;
}
Load your editor and type the above program, make corrections as necessary and
compile it. Once the program is compiled successfully, execute it.
List the output of the program.
EXERCISES
Exercise 13.1
(b) Using the reverse() function, write a program that continuously ask
the user to enter a sentence, and reverse the sentence. Repeat until the user
entered “end”.
This activity sheet handles writing and reading data to and from a text file.
Activity 14.1
int main()
{
FILE *fp; //file pointer
int test1;
if (fp==NULL) {
printf("Cannot Open file \n");
exit(1);
}
for(test1=0;test1<5;test1++)
fprintf(fp,"%d %d \n",test1, test1*4);
fclose(fp);
}
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
Open the output file of a.txt and list the contents of the file.
Activity 14.2
#include <stdio.h>
int main(){
FILE *fp;
int test1,inp1,inp2;
fp=fopen("a.txt","r");
if (fp==NULL) {
printf("Cannot Open file \n");
exit(1);
}
for(test1=0;test1<5;test1++){
fscanf(fp,"%d %d \n",&inp1, &inp2);
printf("%d %d\n",inp1,inp2);
}
fclose(fp);
}
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
List the output of the program.
C handles the special '\n' character differently than the <EOF> character. The control
character '\n' marks the end of a line of text. The <EOF> marks the end of the entire file. The
'\n' character can be processed like any other character. It can be input using scanf() with the
%c specifier. It can be compared for equality. It can be output using printf().
The following program fragment shows how to detect EOF using fscanf():
Using this method, fscanf() will need the number of items specified. Thus it is only suitable
to read data from a file where the number of data per line is known and in fixed format. The
following program demonstrate the use of the above technique:
/*
Program 14.3
Reading data from a file usinf fscanf() and detecting EOF
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char filename[] = "a.txt";
int dat1, dat2, n = 0;
fclose(fp);
printf("\n File %s closed.\n", filename);
Activity 14.3
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.
EOF can also be detected using fgets() and the NULL character:
In the above example, fgets() will read the file's content line by line. Thus it is suitable for
data file without a fixed format.
Activity 14.4
Modify previous program so that it uses fgets() instead of fscanf()
Another special purpose function that can be used o detect EOF is feof( ):
Example of use:
do {
fscanf(fp, "%d %f", &a, &b);
if( !feof(fp) ) {
printf("%d %f\n", a, b);
}
} while( !feof(fp) );
In the above example, the EOF need to be tested twice: once after fscanf() and once more
for the while() loop condition.
Activity 14.5
EXERCISES
Exercise 14.1
(a) Write a program that read user's input of the following data:
(b) Use suitable arrays to store all the data (maximum 999 students). Then,
write all the data into a text file.
read_input() -- to read the input from user and store inside the arrays
write_file() -- write data to a file.
Exercise 14.2
(a) Based on the program from previous exercise, modify the write_file()
function so that it has two new arguments:
(b) Use the modified function to write the data into two files:
Exercise 14.3
Exercise 14.4
Any particular structure type is given a name, called a structure-name and the variables
(called members) within a structure type are also given names. Finally, every variable which
is declared to be a particular structure type has a name of its own too.
Activity 15.1
// Structure1.c
#include <stdio.h>
#include <string.h>
#define STRSIZ 10
typedef struct {
char name[STRSIZ];
double diameter; // equatorial diameter in km
int moons; // number of moons
double orbit_time, // years to orbit sun once
rotation_time; // hours to complete one
// revolution on axis
} planet_t;
int main(void)
{
planet_t current_planet;
strcpy(current_planet.name, "Jupiter");
current_planet.diameter = 142800;
current_planet.moons = 16;
current_planet.orbit_time = 11.9;
current_planet.rotation_time = 9.925;
printf("%s‟s equatorial diameter is %.1f km.\n",
current_planet.name, current_planet.diameter);
}
Load your editor and type the above program and compile it. Once the program is compiled
execute it.
Q1. Did the output of the program confirm your answer? YES / NO
Activity 15.2
Amend the program from Activity 15.1 with the following changes and list the output of the
amended programs.
Q2. Define a function print_planet() to print out all the planets data. Test this
function by calling it from the main() function.
Q3. Define a function named grab_planet() that will compare a string with the planet
names stored in the planet[] array. The function will return a 1 if there is a match
and 0 if the names do not match.
Q4. With the grab_planet()function, modify the program to prompt user for a planet
name and return the planet data when a match of name is found. Re-prompt user for
planet name if there were no match of name. Include the feature where the program
would quit if the user types the word: “quit”.
ls (list)
When you first login, your current working directory is your home directory. Your home
directory has the same name as your user-name, for example, ee, and it is where your
personal files and subdirectories are saved.
ls (listing)
There may be no files visible in your home directory, in which case, the LINUX prompt will
be returned. Alternatively, there may already be some files inserted by the System
Administrator when your account was created.
ls does not, in fact, cause all the files in your home directory to be listed, but only those ones
whose name does not begin with a dot (.) Files beginning with a dot (.) are known as hidden
files and usually contain important program configuration information. They are hidden
because you should not change them unless you are very familiar with Linux!!!
To list all files in your home directory including those whose names begin with a dot, type
% ls -a
We will now make a subdirectory in your home directory to hold the files you will be
creating and using in the course of this tutorial. To make a subdirectory called
Linuxstuff in your current working directory type
% mkdir Linuxstuff
% ls
cd (change directory)
The command cd directory means change the current working directory to 'directory'.
The current working directory may be thought of as the directory you are in, i.e. your
current position in the file-system tree.
% cd Linuxstuff
Exercise A1.1
Make another directory inside the Linuxstuff directory called backups. List the
commands used to do this exercise
% ls -a
As you can see, in the Linuxstuff directory (and in all other directories), there are
two special directories called (.) and (..)
% cd .
This may not seem very useful at first, but using (.) as the name of the current
directory will save a lot of typing, as we shall see later in the tutorial.
% cd ..
will take you one directory up the hierarchy (back to your home directory). Try it now.
Note: typing cd with no argument always returns you to your home directory. This is
very useful if you are lost in the file system.
Pathnames enable you to work out where you are in relation to the whole file-
system. For example, to find out the absolute pathname of your home-directory, type
cd to get back to your home-directory and then type
% pwd
/home/ee
which means that ee (your home directory) is in the sub-directory of the home sub-
directory, which is in the top-level root directory called " / " .
Exercise A1.2
Use the commands cd, ls and pwd to explore the file system.
(Remember, if you get lost, type cd by itself to return to your home-directory)
Understanding pathnames
% ls Linuxstuff
Now type
% ls backups
The reason is, backups is not in your current working directory. To use a command
on a file (or directory) not in the current working directory (the directory you are
currently in), you must either cd to the correct directory, or specify its full pathname.
To list the contents of your backups directory, you must type
% ls Linuxstuff/backups
Home directories can also be referred to by the tilde ~ character. It can be used to
specify paths starting at your home directory. So typing
% ls ~/Linuxstuff
will list the contents of your Linuxstuff directory, no matter where you currently are in
the file system.
What do you think % ls ~ would list? List the information that appears on screen.
What do you think % ls ~/.. would list? List the information on the screen
cp (copy)
cp file1 file2 is the command which makes a copy of file1 in the current working
directory and calls it file2
What we are going to do now, is to take a file stored in an open access area of the
file system, and use the cp command to copy it to your Linuxstuff directory.
First, cd to your Linuxstuff directory.
% cd ~/Linuxstuff
% cp /home/ee/sample.txt .
Note: Don't forget the dot . at the end. Remember, in Linux, the dot means the
current directory. Just create a sample or empty text file called sample.txt
The above command means to copy the file sample.txt to the current directory,
keeping the name the same.
Exercise A1.3
mv (move)
It can also be used to rename a file, by moving the file to the same directory, but
giving it a different name.
We are now going to move the file science.bak to your backup directory.
First, change directories to your Linuxstuff directory (can you remember how?).
% mv science.bak backups/.
% cp science.txt tempfile.txt
% ls
% rm tempfile.txt
% ls
You can use the rmdir command to remove a directory (make sure it is empty first).
Try to remove the backups directory. You will not be able to since UNIX will not let
you remove a non-empty directory.
Exercise A1.4
Create a directory called tempstuff using mkdir , then remove it using the rmdir
command.
Before you start the next section, you may like to clear the terminal window of the
previous commands so the output of the following commands can be clearly
understood.
At the prompt, type
% clear
This will clear all text and leave you with the % prompt at the top of the window.
Appendix B: Interfacing
Introduction
The personal computer (PC) parallel port is a useful input/output (I/O) channel for connecting
circuits to PC. However, care must be taken connecting circuits to the PC parallel port. The
reason for this is that the PC parallel can be easily damaged.
Typically, the PC parallel port is a 25 pin D-shaped female connector at the back of the
computer which is normally used for connecting the printer. It is often called the printer port.
The port has 12 digital outputs and 5 digital inputs. The following is a pin-out diagram of the
parallel port.
The Data Port can be accessed via Pin 2 to pin 9 data (D0 – D7).
(ix) Five input pins (one inverted), that is pin 10 to pin 13 and pin 15 (S3 - S7) can
be accessed via the Status Port
(x) Additional four output pins (three inverted), that is, pin 1, 14, 16 and 17 (C0 –
C3) can be accessed via the Control Port
(xi) The remaining 8 pins (pin 18 – pin 25) are all grounded.
D0 – D7 are TTL level output pins which means that these pins output 0V when they are at
logic 0 and +5V when they are at logic 1. The output current capacity of the parallel port is
limited to only a few milliamperes.
You must grant permission to your program before you can access any ports. The Linux
ioperm system call allows user to access to the PC parallel port and is designed to be called
with root privileges only. Thus you need to either run it as the root user. Here is some code
parts for Linux to write 25510 to printer port:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>
int main(void)
{
int value 1 /* numeric value to send to printer port */
if (ioperm(BASE,3,1))
fprintf(stderr, "Couldn't get the port at %x\n", BASE), exit(1);
outb(value, BASE);
return 0
}
Activity B2.1
Load your editor and type the above program and compile it. Once the program is compiled
execute it.
The above program will turn the least significant bit (LSB) led on.
Exercise B2.1
Modify the above sources code to turn on the most significant bit (MSB) led on.
The following program will demonstrate how to use the switches on the interface board.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>
int main(void)
{
if (ioperm(BASE,3,1))
fprintf(stderr, "Couldn't get the port at %x\n", BASE), exit(1);
outb(0x01,SELECT);
in_out();
}
void in_out()
{
long a=0,read;
do {
read = inb(SWITCH);
if(read==120) //no input
outb(0x00, BASE);
else if(read==248) //input 1
outb(0x0F, BASE);
else if(read==56) //input 2
outb(0xF0, BASE);
else if(read==88) //input 3
outb(0xAA, BASE);
else if(read==104) //input 4
outb(0x55, BASE);
else if(read==112) //input 5
outb(0x99, BASE);
else outb(0xFF, BASE);
a++;
}while (a<999999999);
Activity B2.2
Load your editor and type the above program and compile it. Once the program is compiled
execute it.
The following program will demonstrate how to use the buzzer on the interface board.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>
void sound();
void delay(int);
int main(void)
{
if (ioperm(BASE,3,1))
fprintf(stderr, "Couldn't get the port at %x\n", BASE), exit(1);
sound();
return 0;
}
void sound()
{
int a;
for(a=0;a<30;a++) {
outb(BUZZER,SELECT);
delay(1);
outb(ALLOFF,SELECT);
delay();
outb(BUZZER,SELECT);
delay(1);
outb(ALLOFF,SELECT);
delay(5);
}
return;
}
void delay(int n)
{
long b, c;
for(b=0; b < n*1000000; b++)
c = b; // Do something unnecessary to waste time
return;
}
Activity B2.3
Load your editor and type the above program and compile it. Once the program is
compiled execute it.
The following program will demonstrate how to use the 7-segment display and buzzer on the
interface board.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>
int main(void)
{
if (ioperm(BASE,3,1))
fprintf(stderr, "Couldn't get the port at %x\n", BASE), exit(1);
outb(SEVSEG, SELECT);
int a=0, count;
do {
for(count=0;count<10;count++) {
display(count);
delay(3);
}
a++;
}while(a<10); //count 0 to 9, 10 times
}
void delay(int n)
{
long b, c;
for(b=0; b < n*1000000; b++)
c = b; // Do something unnecessary to waste time
return;
}
Activity B2.4
Load your editor and type the above program and compile it. Once the program is
compiled execute it.