Вы находитесь на странице: 1из 118

ECB 1063

Structured Programming and


Interfacing

Workbook
May 2013

Dept. of Electrical & Electronic Engineering


Universiti Teknologi Petronas

Abu Bakar Sayuti Mohd Saman


Azrina Abdul Aziz
Patrick Sebastian
Vijanth Sagayan Asirvadam
Yap Vooi Voon
Table of Content

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

Activity 1.1 text editor

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.

There are two methods in starting the text editor in Ubuntu.


Method 1:
First is to invoke the editor from Applications -> Accessories menu. Click on the Accessories
category which will display another sub menu which will display Text Editor. Refer to the
Figure 1.2.

Figure 1.2

May 2013 ECB 1063 Structured Programming and Interfacing 1


Department of Electrical & Electronic Engineering

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.

2 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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.

Activity 1.2 gcc compiler


This section walks through the compilation procedures using gcc.

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

gcc simple.c –o simple.o

To execute or run the program, the following has to be typed

./simple.o

May 2013 ECB 1063 Structured Programming and Interfacing 3


Department of Electrical & Electronic Engineering

Activity 1.3 Introduction to C


The following is the simplest possible C program. You cannot get a simpler program than
this.

#include <stdio.h>
main ( )
{

Load your editor and type the above program and compile it. Once the program is compiled
execute it.

Answer the following questions.

Q1.1. When compiling, what are the errors reported by the compiler? How did you fix
them? Write down three of the errors:

Code Error Message Actual problem / fix

Q1.2. Did the program run? Was there any output?

The following is an explanation of the program.

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.

Activity 1.4 Your first C program


Let us now write a program that will display a message on the monitor screen.

#include <stdio.h>
main ( )
{
printf ("Hello world!");
}

4 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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.

Notes on the above program

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.

; the semi-colon is used to terminate a C statement. In this example the


program contains only one statement.

Activity 1.5 More features of a C program


We will introduce more features to the above program. Let‟s take a look at these features in
the following program.

#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.

In the following blank space record the output of the program.

Notes on the above program

int This is a reserved word in C. In the above program it is used to

May 2013 ECB 1063 Structured Programming and Interfacing 5


Department of Electrical & Electronic Engineering

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:

Activity 1.7 Displaying text and the use of control characters

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");
}

Notes on the above program

The backlash shows that a control character is to follow. In this


"\n" program the "n" indicates that a new line is requested. The cursor
is moved one line down and to the immediate left of the monitor. This

6 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

is commonly known to as a carriage return/line feed.

In the following blank space record the output of the program.

More Control Characters

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

Activity 1.8 Displaying name and address


Write a program to display your name and address on Azrina Abdul Aziz
the monitor screen, as shown. You must have control
characters '\t', and '\n' incorporated within Universiti Teknologi
your program. Compile and run. PETRONAS

In the following blank space, write the statements that produce the above output.

May 2013 ECB 1063 Structured Programming and Interfacing 7


Department of Electrical & Electronic Engineering

Which of the following statements are correct and which are not, and why? Write
your answers in the blank space provided.

Statement Correct? Why?


printf("Vooi Yap \n Room 23-03-34");

printf("Vooi Yap Room 23-03-34 \n");

printf("Vooi Yap Room 23-03-34 "\n);

Activity 1.9 Displaying numbers on the monitor screen


/* Progam 1.9 - Displaying numbers and the use of format specifiers */

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.

In the following blank space record the output of the program.

Notes on the above program


index This is a variable name, consequently "int index" defines an integer
variable whose name is index. In this case index is an integer variable

%d This a format specifier. It tells printf ()what format to use in


printing/displaying the value. The % symbol is called a placeholder and it
tells printf ()that a variable is to be displayed. The d indicates that a
decimal value is to be obtained and displayed onto the screen.

The following is a list of format specifiers;

8 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

%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

May 2013 ECB 1063 Structured Programming and Interfacing 9


Department of Electrical & Electronic Engineering

UNIT 2: OPERATORS, ASSIGNMENTS AND INPUT


FUNCTION

This unit will cover the following topics:

(i) Arithmetic operators


(ii) Assignments
(iii) scanf function

2.1 Arithmetic operators.

C uses the following notation for arithmetic operations:

+ 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.

/ * Program 2.1 - Demonstrates the use of arithmetic operators * /

#include <stdio.h>

int main (void)


{
int FirstNo, SecondNo;
FirstNo = 5;
SecondNo = 2;
printf("\n%d + %d = %d", FirstNo, SecondNo, FirstNo+SecondNo);
printf("\n%d * %d = %d", FirstNo, SecondNo, FirstNo*SecondNo);
printf("\n%d - %d = %d", FirstNo, SecondNo, FirstNo-SecondNo);
printf("\n%d / %d = %d", FirstNo, SecondNo, FirstNo/SecondNo);
return(0);
}

10 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

In the following blank space record the output of the program.

Notes for the above program

firstno, These are variables are declared. They are each given a name
secondno, and a type. int is an integer type.

%d Is a format specifier. In this case, the output is displayed in a


decimal format. More on format specifiers later.

2.1.1 The remainder operator (%)

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.

/* Program 2.2 – The Remainder Operator */


#include <stdio.h>

int main (void)


{
int a = 5, b = 2, result;

result = a%b
printf ("result = %d\n", result);
}

May 2013 ECB 1063 Structured Programming and Interfacing 11


Department of Electrical & Electronic Engineering

In the following blank space record the output of the program.

What value did the variable result hold?

2.1.2 Assignment

The statement, result = FirstNo + SecondNo, is known as the assignment


statement and it‟s primary function is to store the result of calculation in a variable. In this
case the variable result is the sum of two variables, that is, FirstNo and SecondNo.

The basic format for assignments is as follows:


variable = expression

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.

/* Program 2.3 – Assigning values to variables */


#include <stdio.h>

int main (void)


{
int FirstNo, SecondNo, Result;
FirstNo = 5;
SecondNo = 2;
Result = FirstNo + SecondNo;
printf("\n%d + %d = %d",FirstNo,SecondNo,Result);
return (0);
}

12 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

In the following blank space record the output of the program.

2.2 Increment and decrement operators

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;

x++ is the same as x = x+1


x-- is the same as x = x-1

ACTIVITY 2.4

Load your editor and type the following program and compile it. Once the program is
compiled, execute it.

/* Program 2.4 - Demonstrates the use of increment and


decrement operators
*/
#include <stdio.h>

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);
}

May 2013 ECB 1063 Structured Programming and Interfacing 13


Department of Electrical & Electronic Engineering

In the following blank space record the output of the program.

2.2.1 Input function (scanf)

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.

/* Program 2.5 - This program reads a data from the keyboard


and displays it on the monitor screen
*/
#include <stdio.h>

int main (void)


{
double Number; /* Input data */

printf("Enter a number: ");


scanf("%d", &Number);
printf("The number entered is : %d\n", Number);
return(0);
}

Notes for the above program

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.

In the following blank space record the output of the program.

14 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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>

int main (void)


{
int FirstNo, SecondNo;
printf("Enter a number: ");
scanf("%d", &FirstNo);
printf("Enter a number: ");
scanf("%d", &SecondNo);
printf("\n%d + %d = %d", FirstNo, SecondNo, FirstNo+SecondNo);
return(0);
}

Activity 2.6

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.

May 2013 ECB 1063 Structured Programming and Interfacing 15


Department of Electrical & Electronic Engineering

UNIT 3: VARIABLES
This unit will cover the following topics:

(i) Constant
(ii) Variable
(iii) Identifier
(iv) Data types in C

3.1 Constant, variable and identifier

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.

int count, number;


Long int bignumber;
Unsigned char noname, university;

/* Program 3.1 - Calculating the area of a circle */

#include <stdio.h>
#define PI 3.1415926 /* constant */

int main (void)


{
double radius; /* radius of a circle */
double area; /* calculate area of circle */

printf(“Enter radius : “);


scanf(“%lf”, &radius);
area = PI * radius * radius;
printf(“Area in floating point notation : %f\n”, area);
return(0);
}

16 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Notes on the above program

#define PI 3.1415926; #define is used define constants. It gives a name


to a value and it is usually placed after the
#includes. In this example, PI is given a value
of 3.1415926.

Activity 3.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.

3.2 Data types in C


Information used in any computer program is known as data. As mentioned earlier, in C there
are different data types. The major data types are as follows;

Data type Examples

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

/* Program 3.2 Data Type: Integers */


#include <stdio.h>

int main(void)
{
int a = 100000; // simple integer type
long int b; // long integer type
short int c; // short integer type

May 2013 ECB 1063 Structured Programming and Interfacing 17


Department of Electrical & Electronic Engineering

unsigned int d; // unsigned 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.

In the following blank space record the output of the program.

/* Program 3.3 Data Type: floats */


#include <stdio.h>

int main(void)
{
float p = 3.14159; // floating point type
double pi = 3.1415926535898; // double precision floating point

printf (" p = %f \t pi = %f \n", p, pi); // float & double outputs


printf (" p = %15.3f \t pi = %15.3f \n", p, pi); // 3 decimal place
printf (" p = %15.5f \t pi = %15.5f \n", p, pi); // 5 decimal places
printf (" p = %15.8f \t pi = %15.8f \n", p, pi); // 8 decimal places
printf (" p = %15.10f \t pi = %15.10f \n", p, pi); // 10 decimal places
printf (" p = %15.12f \t pi = %15.12f \n", p, pi); // 12 decimal places
printf (" p = %15.13f \t pi = %15.13f \n", p, pi); // 13 decimal places

return 0;
}

18 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Activity 3.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.

Notes on the above program

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.

n a number specifying minimum field width


m significant fractional digits for a float
. to separate n from m
- left justification in its field

May 2013 ECB 1063 Structured Programming and Interfacing 19


Department of Electrical & Electronic Engineering

3.3 String 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;

printf ("Hello, welcome to ECB 1063\n");

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.

/* Program 3.4 – Characters and Strings


This program demonstrate the difference between characters and strings
*/
#include <stdio.h>

int main (void)


{
char name [15];
char grade;

printf("Please enter your name : ");


scanf("%s", name);
printf("Greetings %s, please enter your grade : ");
scanf(" %c", &grade); // There's a space before %c
printf("Well done %s!, your grade is %c \n", name, grade);
}

Notes on the above program

char name[15]; name is of the type char and it is an array of 15 characters.


This means it that there is enough room for 15 characters.
scanf("%s", name); scanf reads the name from the keyboard. “%s” is the string
format specifier. name is an address and it needs the
ampersand „&‟ sign because name is the name of an array.

20 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Activity 3.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 output of the program.

3.4 User-Defined Identifiers


Identifiers are used for naming functions, constants, variables, etc. They are composed of
letters, digits and underscores.

The first character MUST be a letter.


Upper and lower case are DIFFERENT.
Names can be of any length, however, only the first eight characters of an identifier are
significant in distinguishing it from another one.
Keywords are always in lower case.

C Reserved Words (Keywords)


auto do for return switch
break double goto short typedef
case else if sizeof union
char entry int static unsignal
continue extern long struct while
default float register

May 2013 ECB 1063 Structured Programming and Interfacing 21


Department of Electrical & Electronic Engineering

Activity 3.5
On paper, design/draft a program that performs the following steps:

Display information about your program:


Given a radius, this program will calculate:
1.Area of a circle
2.Circumference of a circle
3.Volume of a sphere
Ask user to enter a value for the radius.
Calculate the area, circumference and volume.
Display the results.

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.

22 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Unit 4: Number Systems and Type of Operators


This unit will cover the following topics:

(i) Number systems


(ii) Operators in C
(iii) Mathematical operations in C

4.1 Number Systems

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.

The following table compares the number systems:

Decimal Binary Hexadecimal Octal Decimal Binary Hexadecimal Octal

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

Binary numbers grouped by three bits are easily converted to octal.

Binary 000 001 010 011 100 101 110 111


Octal 0 1 2 3 4 5 6 7

Example:

10111011 (bin)  10 111 011  10 = 2, 111 = 7, 011 = 3  273 (octal)

01100011 (bin)  01 100 011  01 = 1, 100 = 4, 011 = 3  143 (octal)

Binary numbers grouped by four bits are easily converted to octal.

Bin 0000 0001 0010 0011 0100 0101 0110 0111


Hex 0 1 2 3 4 5 6 7
Bin 1000 1001 1010 1011 1100 1101 1110 1111
Hex 8 9 A B C D E F

May 2013 ECB 1063 Structured Programming and Interfacing 23


Department of Electrical & Electronic Engineering

Examples:

10111011 (bin)  1011 1011  1011 = B, 1011 = B  BB (hex)

10100011 (bin)  1010 0011  1010 = A, 0011 = 3  A3 (hex)

/* Program 4.1 - Decimals, Hexas and Octals */

#include <stdio.h>

int main(void)
{
int a = 123;

printf(" a in decimal is %d\n", a);


printf(" a in hexadecimal is %x\n", a);
printf(" a in octal is %o\n", a);

return 0;
}

Activity 4.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.

4.2 Operators in C
Apart from the common operators discussed earlier there are other operator types, for
example:

Unary Operators (operating on only one variable)


Binary Operators
Relational Operators
Logical Operators

4.2.1 Unary Operators


- Make negative, e.g. Num2 = -Num1;

24 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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).

~ one's complement, e.g. Num2 = ~ Num1;

If Num1 has the following binary bit pattern: 0000111101010011, then Num2 will have
the opposite bit pattern: 1111000010101100

! not, e.g. Num2 = !Num1

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.

/* Program 4.2 - Unary Operators */

#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.

In the following blank space record the output of the program.

May 2013 ECB 1063 Structured Programming and Interfacing 25


Department of Electrical & Electronic Engineering

4.2.2 Binary Operators

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

FALSE condition is 0 condition, TRUE condition is a non-0 condition

Operator Action

> Greater than


>= Greater than or equal
< Less than
>= Less than or equal
== Equal
!= Not Equal

/* Program 4.3 - Relational Operators */


#include <stdio.h>

int main(void)
{
int a, b, c;
a = 100;
b = 90;
c = 0;

printf ("Is %d equal to %d : %d\n", a, b, a==b);


printf ("Is %d greater than %d : %d\n",a, b, a>b);
printf ("Is %d less than %d : %d\n", a, b, a<b);
printf ("Is %d not equal to %d : %d\n", a, b, a!=b);

return (0);
}

26 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Activity 4.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.

4.2.3 Logical operators

Operato Action
r
&& Logical AND
|| Logical OR
! Logical NOT

/* Program 4.4 – Logical Operators */


#include <stdio.h>

int main(void)
{
int a, b, c;
a = 100;
b = 90;
c = 0;

printf ("Logical AND of %d to %d : %d\n", a, b, a&&b);


printf ("Logical AND of %d to %d : %d\n", a, c, a&&c);
printf ("Logical OR of %d to %d : %d\n", a, b, a||b);
printf ("Logical OR of %d to %d : %d\n", a, b, a||c);
printf (“Logical NOT of %d is : %d\n”, a, !a);
printf (“Logical NOT of %d is : %d\n”, c, !c);

return (0);
}

May 2013 ECB 1063 Structured Programming and Interfacing 27


Department of Electrical & Electronic Engineering

Activity 4.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 output of the program.

4.3 Mathematical Formulas in C

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

a=b− c/d+e (ii)

Brackets or parenthesis are used to separate the numerator from the denominator. Equation
(ii) is written as

a= 
b− c 
/
d+e (iii)

The following are some mathematical formulas rewritten in C.

Table 4.1 Mathematical Formulas in C

Mathematical Formula C Expression


x + y -z x + y -z
2 a * a + 5 * c * d
a + 5cd
4 4 / (3 + c * c)
3+c 2

28 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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 24 

4.4 Program Development


The purpose of this section is to introduce you to a problem-solving method. The reason for
this is that programming is mainly a problem-solving activity. There are a variety of problem-
solving methods but we will adopt a problem-solving method that is suitable for
programming. The method that we are concern with is the software development method.

(i)Identify the requirements of problem


(ii)Analyze the problem
(iii)Design the algorithm
(iv)Coding – write the program
(v)Test the code written in step (iv).

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.

Case Study: Compute the inductive reactance of an inductor.

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

X l = 2πfL where f is frequency and L is the inductance.

May 2013 ECB 1063 Structured Programming and Interfacing 29


Department of Electrical & Electronic Engineering

Data Required:
Input(s): frequency /* frequency */
inductance /* inductance */
Output(s): iReactance /* inductive reactance */
Constant(s): Two_PI 2 x 3.14159

Design: Initial Algorithm


Get the frequency and inductance
Compute the inductive reactance
Display the inductive reactance

Algorithm Refinements

Step 2: in the initial algorithm can be further refined, that is more detail can be
added.
iReactance = Two_PI * frequency * inductance

Coding: Write the code in C

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

Frequency Inductive Inductive


reactance reactance

Inductance

30 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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.

May 2013 ECB 1063 Structured Programming and Interfacing 31


Department of Electrical & Electronic Engineering

UNIT 5: SELECTION STRUCTURES

This unit will cover the following topics:

(i)Program constructs
(ii)if statement
(iii)Relational operators
(iv)Boolean operators
(v)switch statement

5.1 Program Constructs


So far the programs that you have encountered are small and simple programs. However,
when writing large programming tasks, things can get very complex. It is therefore, vital that
when writing programs for complex programs, a more structured approach should be adopted
otherwise the alternative is chaos. Programmers are capable of writing programs that can leap
from one line to another as illustrated in the following BASIC code fragment.

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.

printf ("a = %d\n", a); /* decimal output */


printf ("b = %ld\n",b); /* decimal long output */
printf ("c = %d\n", c); /* decimal short output */
printf ("d = %u\n", d); /* unsigned output */

32 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

printf ("e = %c\n", e); /* character output */


printf ("f = %f\n", f); /* float output */
printf ("g = %f\n", g); /* double float output */

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.

/* Program 5.1 - To demonstrate the use of „if‟ */

#include <stdio.h>

int main (void)


{
int guess_input;

printf("\nPlease enter a whole number: ");


scanf("%d", &guess_input);

if (guess_input == 1)
printf("Right number!\nWell done.\n");

May 2013 ECB 1063 Structured Programming and Interfacing 33


Department of Electrical & Electronic Engineering

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)

34 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

The else statement

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.

/* Program 5.2 - To demonstrate the use of if-else */

#include <stdio.h>

int main (void)


{
int guess_input;

printf("\n Please enter a whole number: ");


scanf("%d", &guess_input);

if (guess_input == 1)
printf("You got it right!\n");
else
printf("Wrong number, dude!\n");

return (0);
}

May 2013 ECB 1063 Structured Programming and Interfacing 35


Department of Electrical & Electronic Engineering

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.

5.2 Relational and Logical Operators


Relational operators are used to ask questions about the variables. The programmer may use
conditions such as Result > 10. Such condition involves comparison between real and
integer expressions. If the relationship holds, the expression is true; otherwise the expression
is false. Thus the expression is true, if value of the variable „Result‟ is greater than 10.
Expressions that use relational operators will return a 0 for false or else a 1 for true. The
following is a summary of relational operators used in C;

Operator Action
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
== Equal
!= Not equal

36 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

The following program illustrates the operation of these operators.

/* Program 5.4 - Relational Operators and 'if' */

#include <stdio.h>

int main(void)
{
int a, b;

printf("\n Enter two numbers.");


printf("\n (Leave a space between the two numbers): ");
scanf("%d%d", &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

May 2013 ECB 1063 Structured Programming and Interfacing 37


Department of Electrical & Electronic Engineering

The following table illustrates three logical operations;

input 1 input 2 input 1 AND input 2 input 1 OR input 2 NOT input 1


0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0

/* Program 5.5 - Logical AND and 'if-else' */

#include <stdio.h>

int main(void)
{
int num, ans;

printf("Enter a number: ");


scanf("%d", &num );

if( num>=1 && num<=10 ) { // is the number out of range?


ans = num*num;
printf("%d to the power of 2 is %d\n", num, ans);
}
else {
printf("The number is out of range.\n");
printf("Please try again!\n\n");
}

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.

Does it work as previously?

Modify your program until it works like the previous one.

38 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

5.3 Multiple Selections

A lot of programs require a user to make a choice from a list of possibilities. There are two
methods to do this:

(i) Use a series of if-else-if statements


(ii) Use the switch-case construct

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.

The following is an example of if-else-if;


/* Program 5.7 if-else-if construct */
#include <stdio.h>

int main (void)


{
int user_entry;

printf("Please enter a whole number between 1 and 4 \n");


scanf("%d", &user_entry);

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);
}

May 2013 ECB 1063 Structured Programming and Interfacing 39


Department of Electrical & Electronic Engineering

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.

The above program can be reformatted using an imaginary else-if construct.

/* Program 5.7B if-else-if construct II */

int main (void)


{
int user_entry;

printf("Please enter a whole number between 1 and 4 \n");


scanf("%d", &user_entry);

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.

40 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

5.3.2 switch-case construct

C has a built-in multiple-branch decision programming construct called switch-case.


With the switch-case, a variable is successively tested against a list of predefined integer
or character constants. When a match is found, the statement or a series of statements
associated with that constant is then executed. The following is a modified version of the
above program using switch-case.

/* Program 5.8 switch-case construct*/


#include <stdio.h>

int main (void)


{
int user_entry;

printf("Please enter a whole number between 1 and 4 \n");


scanf("%d", &user_entry);

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)

May 2013 ECB 1063 Structured Programming and Interfacing 41


Department of Electrical & Electronic Engineering

Notes for the above program.

break This is generally included inside a switch. The break statement is


optional. However, if the break statement is omitted, execution will
continue on into the next case’s statement until either a break or the
end of the switch is reached.

default This will cause a statement or a series of statements to execute if no


matches are found.

TAKE HOME EXERCISE

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:

0 = Black, 1 = Brown, 2 = Red, 3 = Orange, 4 = Yellow,


5 = Green, 6 = Blue, 7 = Violet, 8 = Grey and 9 = White

Use the following template to do your design:

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)

42 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

UNIT 6: PROGRAM CONSTRUCTS: REPETITION

This unit will cover the following topics:

Definition of a loop
while statement
do while statement
for statement

6.1 Repetition (Loops)

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.

6.1.1 While statement

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

Consider the following program.

/* PROGRAM 6.1 WHILE LOOP */


MAIN ( )
{
INT COUNT;
COUNT = 0;
WHILE (COUNT < 6){
PRINTF (“THE VALUE OF COUNT IS %D\N”, COUNT);
COUNT = COUNT + 1;
}
}

May 2013 ECB 1063 Structured Programming and Interfacing 43


Department of Electrical & Electronic Engineering

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.

In the following blank space record the output of the program.

Did the output of the program confirm your answer? YES / NO

Activity 6.2
Amend Program 6.1 with the following changes and list the output of the
amended programs.

Q1. Change the line of „count = 0‟ to „count = 2‟

In the following blank space record the output of the program.

44 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Q2. Now, change that line to „count = 8‟

In the following blank space record the output of the program.

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.

In the following blank space record the output of the program.

Comment on the effect of not maintaining or updating the variable „count‟.

6.1.2 do-while statement

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.

May 2013 ECB 1063 Structured Programming and Interfacing 45


Department of Electrical & Electronic Engineering

Example
The following program is an example of a do-while;

/* Program 6.3 do-while example */


#include <stdio.h>

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)

Notes for the above program

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.

46 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Difference Between do-while and while

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.

do-while Loop while Loop

for statement

The for statement is used when the number of executions of a loop is known.

FORMAT

for (initialization, condition, increment)


{
Statement(s)
}

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.

Consider the following program.

/* Program 6.4 - for loop example */

main ( )
{
int index;
for (index = 0; index < 4; index = index + 1)
printf (“The value of the index is %d\n”, index);
}

May 2013 ECB 1063 Structured Programming and Interfacing 47


Department of Electrical & Electronic Engineering

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.

In the following blank space record the output of the program.

Did the output of the program confirm your answer? YES / NO

Activity 6.5
Amend Program 8.3 with the following changes and list the output of the
amended programs.

Q1. Change the line of „index= index +1 ‟ to „index = index +2‟

In the following blank space record the output of the program.

Q2. Change the line of „index = 0‟ to „index = 2‟

In the following blank space record the output of the program.

48 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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.

May 2013 ECB 1063 Structured Programming and Interfacing 49


Department of Electrical & Electronic Engineering

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.

50 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Exercise 6.3 Write a C program based on the following pseudo-code:

Repeat
Ask user to enter a number (from 1 to 100)
input n
total = ......
Until user entered n<1 or n>100

print Total (sum) of all the VALID numbers entered by user


print Average of the numbers

In the following blank space record the output of the program.

May 2013 ECB 1063 Structured Programming and Interfacing 51


Department of Electrical & Electronic Engineering

UNIT 7: NESTED LOOPS

This unit will cover the following topics:

(i) Definition of a nested loop


(ii) Using nested loops

7.1 Nested Loop

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.

Using Nested Loop

Activity 7.1
Consider the following program segment:

int row, col;

for (row=0;row<4;row++)
{
for(col=0;col<4;col++)
printf("# ");
printf("\n");
}

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.

Did the output of the program confirm your answer? YES / NO

52 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Activity 7.2
Consider the following program segment:

int row, col;

for (row=1;row<5;row++)
{
for(col=1;col<row+1;col++)
{
printf("& ");
}
printf("\n");
}

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.

Did the output of the program confirm your answer? YES / NO

Notes for the above program:

outer
inner
loop
loop

May 2013 ECB 1063 Structured Programming and Interfacing 53


Department of Electrical & Electronic Engineering

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:

int main (void)


{
int j = 5;

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;
}

54 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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.

Did the output of the program confirm your answer? YES / NO

Activity 7.6
Write a program that produces the following output:

>
-->
---->
------>
-------->
---------->
------------>
---------->
-------->
------>
---->
-->
>

Show your program and its output to a Teaching Assistant for verification.

May 2013 ECB 1063 Structured Programming and Interfacing 55


Department of Electrical & Electronic Engineering

EXERCISES

Exercise 7.1 Table of Multiplication

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:

This program print a multiplication table in the size of X times Y,


where X is from 1 to 18 and Y is from 1 to 23.

Please enter table size X (1~18), Y (1~23) : 5 7

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

56 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

UNIT 8: INTRODUCTION TO FUNCTIONS

This section of the notes will cover the following topics:

(iii) Definition of a function


(iv) C built-in functions
(v) Writing your own function
(vi) Structured Chart

8.1 Definition of a C function


Typically a C program is made up of one or more functions. A function is a program that
contains one or more executable statement. Ideally, a function should perform only one task.
Each function has a name and a list of arguments that it will receive. More discussion on
arguments will follow later.

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.

8.2 Library Functions


C provides many pre-defined functions to perform many operations including mathematical
calculations. These pre-defined mathematical functions are grouped in various libraries. Once
included in a program, a library function can be called at any place in the program and they
return a value where it is needed.

A common mathematical function used is the log function,

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.

May 2013 ECB 1063 Structured Programming and Interfacing 57


Department of Electrical & Electronic Engineering

Mathematical function Meaning


log (x) Returns the natural logarithm of x
log10 (x) Returns the base 10 logarithm of x
x
exp (x)
Returns e where e is 2.71828
sqrt (x) Returns the square root of x
cos (x) Returns the cosine of angle x
sin (x) Returns the sine of angle x
tan (x) Returns the tangent of angle x

Consider the following program segment:

/* Program 8.1 Using built-in mathematical library functions*/


#include <stdio.h>
#include <math.h>
int main(void)
{
float x, y, z;

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?

In the following blank space record the output of the program.

58 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

8.3 Writing Your Own Function


Each function should have a parentheses (brackets) after the function name. For example, if
the function‟s name is hello then it will be written as hello(). A function is written in
the same way as the main() function. The function can be called or invoke anywhere in the
main() function.

The following is typical format of a user defined function:

Function declarations/function prototype

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.

/* Program 8.2 - A simple program with function */


#include <stdio.h>

/* -------- Declaring a prototype ------- */


void display_hello ();

/* -------- Main function ---------- */


int main (void){
display_hello(); /* Call the hello function */
return (0);
}

/* ------ Function definition --------- */


void display_hello(){
printf(“Hello\n”);
}
Notes for the above program

void display_hello(); This known as the function prototype. In this example, it


simply contains the name of the function. A function
prototype is generally declared at the beginning of the
program and this is accepted programming practice.
display_hello(); This is a function call. The function is executed to display
the message, “Hello” on the screen.

void display_hello() This is a function definition. It contains the complete body


{ of the function and it may contain data passed to and from
printf(“Hello\n”);
} the function. Note that function definitions generally
appear/located at the bottom of the program, after
main().

May 2013 ECB 1063 Structured Programming and Interfacing 59


Department of Electrical & Electronic Engineering

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.

The general form of a user defined function (function definition) is as follows;

Function name
{
body of code
}

Consider the function in the previous program:


function name
void display_hello( )
{
printf(“Hello\n”); 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.

In the following blank space record the output of the program.

8.4 Structured Chart


A structured chart art is a useful tool particularly when it comes to solving complex program.
The structured chart for Program 8.2 is as follows:

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.

60 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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.

Drawing Structured Charts


The following symbols are used to represent a structured chart.

Rectangle. Represents the basic building block or


function function. It contains a series of program statements. The
function name is written inside the rectangle. A meaningful
verb phrase should be used to describe its function.

Connecting line. Used to connect modules

Data indicator. Used to show data communicated from


one module to another.

Same program with structured chart.


/* A simple program with two functions */

#include <stdio.h>

/* -------- Declaring a prototype ------- */


void display_hello ();

main( ) /* -------- Main function ---------- */


int main (void){
display_hello(); /* Call the hello function */
return (0);
}

display_hello( ) /* ------ Function definition --------- */


void display_hello(){
printf(“Hello\n”);

May 2013 ECB 1063 Structured Programming and Interfacing 61


Department of Electrical & Electronic Engineering

Using Structured Chart

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.

62 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

UNIT 9: USER-DEFINED FUNCTIONS WITH ARGUMENTS


This unit will cover the following topics:
(i) Functions with arguments
(ii) Various types of functions

9.1 Passing Data to a Function Using Arguments

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:

 Functions with arguments


 Formal parameters

9.1.1 Function with a single argument, no result

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);
}

May 2013 ECB 1063 Structured Programming and Interfacing 63


Department of Electrical & Electronic Engineering

Activity 9.1

Before running the program, list the output of the program.

Load your editor and type the above program and compile it. Once the program is
compiled execute it.

Did the output of the program confirm your answer? YES / NO

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.

9.1.2 Function with a single argument, single result

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

64 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

int cube(int n);

int main()
{
int x = 2, y;

y = cube(x); // function call


printf("\n %d^3 = %d\n", x, y);

return(0);
}

// function definition
int cube(int n)
{
return(n*n*n);
}

Activity 9.2

Before running the program, list the output of the program.

Load your editor and type the above program and compile it. Once the program is
compiled execute it.

Did the output of the program confirm your answer? YES / NO

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.

May 2013 ECB 1063 Structured Programming and Interfacing 65


Department of Electrical & Electronic Engineering

Activity 9.3

Based on previous program, write a user-defined function mysine(x) that


calculates and returns the value of sin x where x is in degrees.
Record the output of your program in the space provided below:

9.2 Function with multiple arguments

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>

/* ---------------- Declaring function --------------- */


int multiply (int num1, int num2);

/* ---------------- Main Function --------------------- */


main ()
{
multiply (10,11);
return(0);
} arguments

/* ------------------ Function definition -------------- */


int multiply (int num1, int num2)
{
printf("%d", num1*num2);
Formal
return(0); parameters or
} parameter list

Activity 9.4

Before running the program, list the output of the program.

Load your editor and type the above program and compile it. Once the program is
compiled execute it.

66 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Did the output of the program confirm your answer? YES / NO

9.2.1 Function with multiple arguments, single result

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);

int main( ) /* This is the main program */


{
int x,y;
int result;
x = 10; y = 2;
result = power_f(x,y); /* Compute the value of x^y */
printf("%d to the power of %d is %d \n", x,y,result);
return(0);
}

int power_f(int x1 , int y2) /* function to get the power */


{
int square;

square = pow (x1 ,y2);


return(square);
}

Activity 9.5

Before running the program, list the output of the program.

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

Q2. Amend the statement line

May 2013 ECB 1063 Structured Programming and Interfacing 67


Department of Electrical & Electronic Engineering

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).

68 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

UNIT 10: BASIC ON POINTERS


This unit will cover the following topics:

(i) Pointers and their use


(ii) Use of pointers for passing by reference

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:

int *var1; //defines var1 as pointer to an integer variable

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:

int *var1; // defines var1 as pointer to an integer variable


int var2; // defines var2 variable of type integer

printf("Address of *var1 is %p \n", var1 ); //display address of var1


printf("Address of var2 is %p \n", &var2 );

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;

printf("Add. of x is %p \n", &x);


printf("Add. of y is %p \n", &y);

printf("Add. of x through pointer is %p \n", xptr);


printf("Add. of y through pointer is %p \n", yptr);

return 0;
}

May 2013 ECB 1063 Structured Programming and Interfacing 69


Department of Electrical & Electronic Engineering

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.

Q1. List the output of the program.

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.

Q5. Describe the differences of the outputs from Q1 to Q4 for each


situation.

70 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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>

void pointer_address(int, int *);

int main()
{
int x;
int *xptr;

xptr = &x;

printf("Add. of x is %p \n", &x);


printf("Add. of x through pointer is %p \n", xptr);
pointer_address(x, xptr);
printf("After the function call, value of x is %d \n", x);

return 0;
}

void pointer_address(int any, int *anyptr)


{
printf("In this function, value of any is %d \n", any);
printf("In this function, address of X is %p \n", &any);
printf("In this function, address of X via pointer is %p \n", anyptr);
*anyptr = 100;
}

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?

List the output of the program.

May 2013 ECB 1063 Structured Programming and Interfacing 71


Department of Electrical & Electronic Engineering

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

printf("Before function call: x = %d, y =%d \n", x, y);

change_values(x, &y); // call the function using 'address of'

printf("After function call: x = %d, y =%d \n", x, y);

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?

List the output of the program.

72 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

/* 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

printf(" x xptr y yptr\n");


printf("--------- --- --------- --- ---------\n");
printf("BEFORE %3d %9p %3d %9p\n", x, xptr, y, yptr);

swap_them(&x, &y); // call the function using 'address of'


printf("AFTER I %3d %9p %3d %9p\n", x, xptr, y, yptr);

swap_them(xptr, yptr); // call the function using pointers


printf("AFTER II %3d %9p %3d %9p\n", x, xptr, y, yptr);

return 0;
}

// Function definition
void swap_them(int *a, int *b)
{
int tmp;

printf("Inside %3d %9p %3d %9p\n", *a, a, *b, b);


tmp = *a;
*a = *b;
*b = tmp;
}

Activity 10.4
Load your editor and type the above program and compile it. Once the program is
compiled, execute it.

List the output of the program.

May 2013 ECB 1063 Structured Programming and Interfacing 73


Department of Electrical & Electronic Engineering

UNIT 11 – FUNCTIONS: PASS BY VALUE AND PASS BY


REFERENCE
This unit will cover the following topics:

(i) Use of pointers for passing by reference


(ii) Use of pointers for returning more than one values

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.

11.1 Passing Values to a Function

Activity 11.1
Consider the following program:

/* Program 11.1 Passing Values */


#include <stdio.h>

void passing(int num1, int num2);

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;
}

void passing(int num1, int num2)


{
printf(“First no. is %d, second no. is %d”, num1, num2);
return 0;
}

Before running the program, list the output of the program.

Load your editor and type the above program and compile it. Once the program
is compiled, execute it.

74 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Did the output of the program confirm your answer? YES / NO

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;
}

11.2 Returning a Value from a Function

Activity 11.2
Consider the following program:

/Program 11.2 Passing Values and Returning a Value */


#include <stdio.h>

int passing(int num1, int num2);

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;
}

int passing(int num1, int num2)


{

May 2013 ECB 1063 Structured Programming and Interfacing 75


Department of Electrical & Electronic Engineering

printf(“First no. is %d, second no. is %d”, num1, num2);


return (num1+num2);
}

Before running the program, list the output of the program.

Load your editor and type the above program and compile it. Once the program is
compiled, execute it.

Did the output of the program confirm your answer? YES / NO

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

int passing(int num1, 4


3 int num2)
{
printf(“First no. is %d, second no. is %d”, num1, num2);
return (num1+num2);
}

11.3 Passing by Reference (passing Pointers)


As mentioned in earlier section, pointers can be used to pass multiple values from a function
to the calling functions. The called function, instead of passing values to the calling function,
passes its address. These are the address of the variables in the calling function where the user
will store the return values. The following program demonstrates how this is done:

/* Program 11.3 Passing Pointers */


#include <stdio.h>

/* ---------------- Declaring Function --------------- */


int Pass_values (int *px, int *py);

/* ------------------ Main Program ------------------- */


main ()
{
int x, y;
Pass_values(&x, &y);

76 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

printf(“First no is %d, second no is %d.”, x, y);


return 0;
}

/* ---------------- Function definition -------------- */


Pass_values (int *px, in *py)
{
*px = 3;
*py = 5;
return 0;
}

Activity 11.3
Load your editor and type the above program and compile it. Once the program is
compiled, execute it.

List the output of the program.

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:

int *px, *py; /* Declaration of two pointers */

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.

11.4 Passing Multiple Values Using Pointers

The following program demonstrates how multiple values are passed to a function and also
how multiple values are passed to the calling function.

/* Program 11.4 Passing Multiple Values*/

#include <stdio.h>
void calc(int n1,int n2,int *mul_res, int *div_res)

int main(void)
{
int num1,int num2;

May 2013 ECB 1063 Structured Programming and Interfacing 77


Department of Electrical & Electronic Engineering

int mul_result, int div_result;


printf ("Enter a number :");
scanf (“%d”, &num1);
printf ("Enter a number :");
scanf (“%d”, &num2);
calc (num1, num2, int &mul_result, int &div_result);
printf ("The result of multiplication is %d \n", mul_result);
printf ("The result of division is %d \n", div_result);
return (0);
}

void calc(int n1, int n2,int *mul_res, int *div_res)


{
*mul_res = n1 * n2;
*div_res = n1 / n2;
}

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?

78 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

UNIT 12: ARRAYS


This unit will cover the following topics:

(i) One dimensional arrays


(ii) Storing data into arrays
(iii) Use arrays as arguments of functions

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;

PrimeNumberOne, PrimeNumberTwo, PrimeNumberThree, … and so on.

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.

12.1 One-Dimensional 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

May 2013 ECB 1063 Structured Programming and Interfacing 79


Department of Electrical & Electronic Engineering

are used and the general form of declaration is:


type array_name[6]
In the format above, type specifies the type of THE ELEMENTS that is in the array. Examples
of types are int, long or char. THE NUMBER IN THE SQUARE BRACKETS indicates the
maximum number of elements that can be stored inside the array.

Activity 12.1

Consider the following program:

/* Program 12.1 Prime Numbers in an Array */


#include <stdio.h>

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;
}

Before running the program, list the output of the program.

Load your editor and type the above program and compile it. Once the program
is compiled, execute it.

Did the output of the program confirm your answer? YES / NO

In the above program, look at the statement:

int PrimeNumber[6] = {1, 2, 3, 5, 7, 11};

The portion int PrimeNumber[6] declares the array, PrimeNumber, to be an array


containing 6 elements. Any subscripts 0 to 5 are valid can be used to refer to the individual
element in the array. In C the array elements index or subscript begins with a zero. So
PrimeNumber[0] refers to the first element of the array. PrimeNumber[1], the second
element and so on until PrimeNumber[5], the last element.

The second portion of the statement, = {1, 2, 3, 5, 7, 11}, initialized the elements in

80 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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:

/* Program 12.2 Sum of Prime Numbers in an Array */


#include <stdio.h>

int main()
{
int i;
int total = 0 ;
int primes[6] = {1, 2, 3, 5, 7, 11};

for ( i=0 ; i<6 ; i++) {


total = total + primes[i];
printf("primes [%d] = %d\n",i, primes[i]);
}
primes[0] = total ;
printf("The sum of the array is %d \n", primes[0]);
return 0;
}

Before running the program, list the output of the program.

Load your editor and type the above program and compile it. Once the program is
compiled, execute it.

Did the output of the program confirm your answer? YES / NO

May 2013 ECB 1063 Structured Programming and Interfacing 81


Department of Electrical & Electronic Engineering

12.2 Storing Values into an Array

Activity 12.3
Consider the following program:

/* Program 12.3 Storing Values into an Array */


#include <stdio.h>

int main()
{
int number;
int primes[6];

for ( number=0 ; number<6 ; number++) {


printf("Enter a prime number here %d: ",number);
scanf("%d", &primes[number]);
}
printf("\nDisplaying prime numbers: \n\n");
for ( number=0 ; number<6 ; number++){
printf("primes [%d] = %d\n",number, primes[number]);
}

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.

Did the output of the program confirm your answer? YES / NO

82 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Activity 12.4
Modify Program 12.3 so that:

The size of the array is 100 elements


(vii) It asks the user to enter the first 10 prime numbers (and stores them
into the first 10 elements of the array)
(viii) It displays the first 10 elements of the array.

Write the modification that you plan to do:

Load your editor and type the above program and compile it. Once the program is
compiled, execute it.

Did the output of the program confirm your answer? YES / NO

12.3 Array as Function Argument

Activity 12.5
Consider the following program:

/* Program 12.5 Array as Function Argument */


#include <stdio.h>

void DisplayArray(int PrimeNumber[]);

int main ()
{
int primes[6] = {2, 3, 5, 7, 11, 13};
DisplayArray(primes);
return 0;
}

void DisplayArray(int PrimeNumber[])


{
int index;

for (index = 0; index < 6; index++) {


printf("PrimeNumber [%d] = %d\n",index,PrimeNumber[index]);
}
}

May 2013 ECB 1063 Structured Programming and Interfacing 83


Department of Electrical & Electronic Engineering

Before running the program, list the outputs of the program.

Load your editor and type the above program and compile it. Once the program is
compiled, execute it.

Did the output of the program confirm your answer? YES / NO

Activity 12.6
Consider the following program:

/* Program 12.6 Two-dimensional Array */


#include <stdio.h>

#define ROW 2
#define COL 3

int main ()
{
int row,col;
int matrix1[ROW][COL] = {{1, 2, 3}, {4, 5, 6}};

for (row = 0; row < ROW; row++) {


for (col = 0; col< COL; col++) {
printf("%d ", matrix1[row][col]);
}
printf("\n");
}

return 0;
}

Load your editor and type the above program and compile it. Once the program is
compiled, execute it.

Record the output of the program:

84 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Activity 12.7
Consider the following program:

/* Program 12.7 Passing 2D Arrays to a Function*/


void AddMatrix(int mtx2[2][2], int mtx2[2][2],int [2][2]);
void DisplayResult(int [2][2]);

int main (){


int matrix1[2][2] = {{1, 2}, {3, 5}};
int matrix2[2][2] = {{4, 7}, {2, 9}};
int matrix_ans [2][2];

AddMatrix(matrix1,matrix2,matrix_ans);
DisplayResult(matrix_ans);
return 0;
}

void AddMatrix(int mtx1[2][2], int mtx2[2][2],int a_mtx[2][2]){


int row,col;

for (row = 0; row < 2; row++){


for (col = 0; col< 2; col++){
a_mtx[row][col]=mtx1[row][col]+mtx2[row][col];
}
}
}

void DisplayResult(int d_mtx[2][2]){


int row,col;

for (row = 0; row < 2; row++){


for (col = 0; col< 2; col++){
printf("%d ", d_mtx[row][col]);
}
printf("\n");
}
}

Before running the program, answer the following questions:

Q2. What is the answer of matrix1 + matrix2 ?.

Load your editor and type the above program and compile it. Once the program
is compiled, execute it.

Did the output of the program confirm your answer? YES / NO

May 2013 ECB 1063 Structured Programming and Interfacing 85


Department of Electrical & Electronic Engineering

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.

(b) Write the function definition of your ComputeArray() function:

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);
}

86 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

UNIT 13: STRINGS


This unit will cover the following topics:

(i) Introduction of strings


(ii) Various string functions
(iii) Strings as pointers

In C, a string is treated as an array of characters terminating with a \0. In other words, a


string is a series of characters. You have encounter strings in the earlier units, for example:

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

13.1 String Variables

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

Consider the following program:

/* Program 13.1 Reading a string entered by user */

main( ) /* This is the main program */


{
char name1 [40]; /*the length of name 40 chars long*/

printf ("Please enter your name : ");


scanf(“%s”, name1);

printf(“Hello, %s \n”, name1);

return 0;
}

May 2013 ECB 1063 Structured Programming and Interfacing 87


Department of Electrical & Electronic Engineering

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.

Q1. List the input and output of the program.

Q2. Try typing the following name

Jackie Chan

List the input and output of the program

Q3. Did the program give you get the expected output? YES / NO

Q4. Can you explain output of the program?

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

88 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Change the line: scanf("%s", name1); with gets(name1);


List the input and output of the program

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.

13.2 String Functions

There are many library functions provided for the manipulations of strings. Some of them
are:

strcpy() char *strcpy( char *s1, const char *s2)

Copies the string s2 into the character array s1. The value of s1 is returned.

strncpy() char *strncpy( char *s1, const char *s2, size_t n)

Copies at most n characters of the string s2 into the character array s1. The value of s1 is
returned.

strcat() char *strcat( char *s1, const char *s2)

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.

strncat() char *strncat( char *s1, const char *s2, size_t n)

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.

strcmp() int strcmp( const char *s1, const char *s2)

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.

strlen() size_t strlen( const char *s)

Determines the length of the string s. Returns the number of characters in the string before the
'\0'.

May 2013 ECB 1063 Structured Programming and Interfacing 89


Department of Electrical & Electronic Engineering

Activity 13.3
Consider the following program:

/* Program 13.3 Using strcpy() and strncpy() functions */

main( )
{
char name1 [40]; /*the length of name 40 chars long*/
char name2 [40];
char name3 [40];

printf ("Please enter a short phrase : ");


gets(name1);

printf(“The phrase entered was %s \n”, name1);

strcpy(name2,name1);
strncpy(name3,name1,5);

printf(“The phrase copy or assigned was %s \n”, name2);

printf(“The shortened phrase was %s \n”, name3);

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.

Note: The strcpy() function copies one string to another while


th
strcpy()copies part of the string, up to the n character.

Q2. What can you observe from the above output regarding a
problem of using strncpy()?

90 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

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:

/* Program 13.4 Using strcmp() function */

main( ){
char name1 [40]; /*the length of name 40 chars long*/
char master [40] ={"Alpha high"}; /*master code*/

printf ("Please enter code name : ");


gets(name1);
printf("The code entered was %s \n", name1);

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.

Q2. Change the line:


strcmp(name1,master); with strncmp(name1,master,
7);

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.

May 2013 ECB 1063 Structured Programming and Interfacing 91


Department of Electrical & Electronic Engineering

13.3 Strings as Pointers


Strings, like any other arrays can be declared and used as pointers.

Activity 13.5
Consider the following program:

/* Program 13.5 Strings and Pointers */


main()
{
char s1[] = "This is a string";
char *s2 = "This is another string";
char *s3;

printf("\n %s, %d chars long \n", s1, strlen(s1) );


printf("\n %s, %d chars long \n", s2, strlen(s2) );

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.

List the output of the program.

92 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Activity 13.6
Consider the following program:

/* Program 13.6 String Pointers as Function Argument */

main()
{
char s1[] = "This is a string";
char *s2 = "This is another string";

print_string( s1 );
print_string( s2 );

return 0;
}

void print_string(char *str)


{
printf("\"%s\"\n", str);
}

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

(a) Write a function called reverse() that has the following


characteristics:

Function type: string


Argument: str (type: string)
Returns the reverse of string str (eg. “Hello World” becomes “dlroW olleH”)

(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”.

May 2013 ECB 1063 Structured Programming and Interfacing 93


Department of Electrical & Electronic Engineering

Unit 14: Files


This unit will cover the following topics:
(i) Introduction to Files
(ii) Reading data from files
(iii) Writing data to files
(iv) Detecting End of File (EOF)

This activity sheet handles writing and reading data to and from a text file.

14.1 Writing data to a text file

Activity 14.1

Consider the following program:

/* Program 14.1 Writing a file */


#include <stdio.h>

int main()
{
FILE *fp; //file pointer
int test1;

fp=fopen("a.txt","w"); //open file to write data

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.

Note about the above program:

94 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

In the statement fp=fopen("a.txt","w");, the second argument indicates the mode of


file access. These are the valid modes:

Mode Purpose Remarks


“r” Read access File must exist
“w” Write access If file exists, old contents are destroyed
“a” Append access If file exists, new data written at end, file created if it did not
exist
“r+” Read and write File must exist
“w+” Write and read If file exists, old file data destroyed
“a+” Append and File created if it did not exist
read

14.2 Reading data from a text file

Activity 14.2

Consider the following program:

#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.

14.3 Detecting End of File (EOF)

May 2013 ECB 1063 Structured Programming and Interfacing 95


Department of Electrical & Electronic Engineering

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().

14.3.1 Detecting EOF using fscanf()

The following program fragment shows how to detect EOF using fscanf():

while( fscanf(fp, "%d %f", &a, &b)!=EOF ) {


printf("%d %f\n", a, b);
}

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;

printf("\n Opening file %s...", filename);


fp = fopen( filename, "r"); // open file for reading
if (fp==NULL) {
printf("Error: Cannot Open file %s.\n", filename);
exit(1);
}

printf("\n Reading data\n");


while( fscanf(fp,"%d %d \n", &dat1, &dat2)!=EOF ) {
printf("%d --> %d %d\n", n+1, dat1, dat2);
n++;
}

fclose(fp);
printf("\n File %s closed.\n", filename);

printf("\n The data are: %d %d\n", dat1, dat2);

96 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Activity 14.3
Load your editor and type the above program and compile it. Once the program
is compiled, execute it.

List the output of the program.

14.3.2 Detecting EOF with fgets()

EOF can also be detected using fgets() and the NULL character:

while( fgets(line, 80, fp)!=NULL ) {


printf("%s \n", line);
}

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()

Write down the modification that you have made.

14.3.3 Detecting EOF with feof()

Another special purpose function that can be used o detect EOF is feof( ):

feof (FILE *pointer)

feof() returns 0 if end-of-file not reached


feof() returns non-0 when end-of file reached

May 2013 ECB 1063 Structured Programming and Interfacing 97


Department of Electrical & Electronic Engineering

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

Modify previous program so that it uses feof() to detect EOF.

Write down the modification that you have made.

EXERCISES

Exercise 14.1

(a) Write a program that read user's input of the following data:

matric -- to store student's matric number (ID)


name -- to store student's name
score -- to score student's score/marks

(b) Use suitable arrays to store all the data (maximum 999 students). Then,
write all the data into a text file.

(c) The program must make use of user-defined functions:

read_input() -- to read the input from user and store inside the arrays
write_file() -- write data to a file.

Exercise 14.2

98 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

(a) Based on the program from previous exercise, modify the write_file()
function so that it has two new arguments:

(1) filename – to specify the name of the data file


(2) order – to specify the order the data is written to the file: normal
order or reversed order

(b) Use the modified function to write the data into two files:

(1) names.txt – data is written in order they are entered


(2) reversed.txt – data is written in reversed order.

Exercise 14.3

Based on the program from previous exercise, add a function


add_grade() that specify the grade for each score according to UTP's grading
system. Use a suitable array to score the grades.

Exercise 14.4

(a) Based on the program from previous exercise, add a function


sort_data() that sort the data according to the matric number. After getting the
data from the user, sort the data using sort_data().

(b) Write the data into two files:

(1) names.txt – data is written in the order they are sorted.


(2) reversed.txt – data is written in reversed order.

May 2013 ECB 1063 Structured Programming and Interfacing 99


Department of Electrical & Electronic Engineering

UNIT 15: STRUCTURE {STRUCT} IN C


This unit will cover the following topic:

(i) Introduction to structure and how to use it

15.1 Introduction to Structure


A structure is a package of one or more variables which are grouped under a single name.
Structures are not like arrays: a struct can hold any mixture of different types of data: it can
even hold arrays of different types. A struct can be a as simple or as complex as the
programmer desires.

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

Consider the following program:-

// 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);
}

100 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Before running the program, list the output of the program.

Load your editor and type the above program and compile it. Once the program is compiled
execute it.

Answer the following questions.

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.

Q1. Include a declaration of an array of struct called planet[] based on planet_t


which could hold the data of eight planets of the solar system. The data of the eight
planets are as follow:-

Name Diameter moons Orbit Rotation


(km) (Hours) (Years)
Mercury 4,880 0 0.241 1,408.8
Venus 12,103 0 0.61548 5,832
Earth 12,756 1 1 24
Mars 6,794 2 1.8821 24.6598
Jupiter 142,800 16 11.9 9.925
Saturn 120,536 61 29.5 10.543
Uranus 51,118 27 84.323326 17.24
Neptune 49,532 13 164.79 16.11

Q2. Define a function print_planet() to print out all the planets data. Test this
function by calling it from the main() function.

In the following blank space record the output of the program.

May 2013 ECB 1063 Structured Programming and Interfacing 101


Department of Electrical & Electronic Engineering

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”.

102 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Appendix A: Operating System - Linux

Activity A1.1 Listing Files and Directories

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.

To find out what is in your home directory, type

ls (listing)

The ls command lists the contents of your current working directory.

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

As you can see, ls -a lists files that are normally hidden.

May 2013 ECB 1063 Structured Programming and Interfacing 103


Department of Electrical & Electronic Engineering

ls is an example of a command which can take options: -a is an example of an option. The


options change the behaviour of the command. There are online manual pages that tell you
which options a particular command can take, and how each option modifies the behaviour of
the command. (See later in this tutorial)

Activity A1.2 Making Directories

mkdir (make directory)

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

To see the directory you have just created, type

% ls

104 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Activity A1.3 Changing to a different directory

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.

To change to the directory you have just made, type

% cd Linuxstuff

Type ls to see the contents (which should be empty)

Exercise A1.1
Make another directory inside the Linuxstuff directory called backups. List the
commands used to do this exercise

Activity A1.4 The directories . and ..


Still in the Linuxstuff directory, type

% ls -a

As you can see, in the Linuxstuff directory (and in all other directories), there are
two special directories called (.) and (..)

The current directory (.)

In LINUX, (.) means the current directory, so typing

% cd .

[NOTE: there is a space between cd and the dot]

means stay where you are (the Linuxstuff directory).

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.

May 2013 ECB 1063 Structured Programming and Interfacing 105


Department of Electrical & Electronic Engineering

The parent directory (..)

(..) means the parent of the current directory, so typing

% 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.

Activity A1.5 Pathnames

pwd (print working directory)

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

The full pathname will look something like this -

/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)

Activity A1.6 More about home directories and pathnames

Understanding pathnames

First type cd to get back to your home-directory, then type

% ls Linuxstuff

to list the conents of your Linuxstuff directory.

106 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Now type

% ls backups

You will get a message like this -

backups: No such file or directory

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

~ (your home directory)

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

May 2013 ECB 1063 Structured Programming and Interfacing 107


Department of Electrical & Electronic Engineering

Activity A1.7 Copying Files

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

Then at the Linux prompt, type,

% 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

Create a backup of your sample.txt file by copying it to a file called sample.bak

Activity A1.8 Moving Files

mv (move)

mv file1 file2 moves (or renames) file1 to file2


To move a file from one place to another, use the mv command. This has the effect
of moving rather than copying the file, so you end up with only one file rather than
two.

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?).

108 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Then, inside the Linuxstuff directory, type

% mv science.bak backups/.

Type ls and ls backups to see if it has worked.

Activity A1.9 Removing files and directories

rm (remove), rmdir (remove directory)

To delete (remove) a file, use the rm command. As an example, we are going to


create a copy of the science.txt file then delete it.
Inside your unixstuff directory, type

% 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.

Activity A1.10 Displaying the contents of a file on the screen

clear (clear screen)

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.

May 2013 ECB 1063 Structured Programming and Interfacing 109


Department of Electrical & Electronic Engineering

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.

110 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

The PC Parallel Interface Board

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:

May 2013 ECB 1063 Structured Programming and Interfacing 111


Department of Electrical & Electronic Engineering

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>

#define BASE 0x378 /* Base address of the parallel port*/

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.

In the following blank space record the output of the program.

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.

Input and Output

The following program will demonstrate how to use the switches on the interface board.

112 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>

#define BASE 0x378


#define SWITCH 0x379
#define SELECT 0x37A
#define LED 0x01

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.

In the following blank space record the output of the program.

May 2013 ECB 1063 Structured Programming and Interfacing 113


Department of Electrical & Electronic Engineering

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>

#define BASE 0x378


#define SWITCH 0x379
#define SELECT 0x37A
#define LED 0x01
#define SEVSEG 0x08
#define BUZZER 0x0F
#define ALLOFF 0x09

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;
}

114 ECB 1063 Structured Programming and Interfacing May 2013


Universiti Teknologi PETRONAS

Activity B2.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.

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>

#define BASE 0x378


#define SWITCH 0x379
#define SELECT 0x37A
#define LED 0x01
#define SEVSEG 0x08
#define BUZZER 0x0F
#define ALLOFF 0x09

#define zero 0xC0


#define one 0xF9
#define two 0xA4
#define three 0xB0
#define four 0x99
#define five 0x92
#define six 0x82
#define seven 0xF8
#define eight 0x80
#define nine 0x98

void display(int count);


void delay(int);

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);

May 2013 ECB 1063 Structured Programming and Interfacing 115


Department of Electrical & Electronic Engineering

}
a++;
}while(a<10); //count 0 to 9, 10 times
}

void display(int count)


{
int ary[10]={ zero, one, two, three, four, five, six, seven, eight,
nine};
outb(ary[count],BASE);
delay();
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.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 output of the program.

116 ECB 1063 Structured Programming and Interfacing May 2013

Вам также может понравиться