You are on page 1of 89

Faculty of Science and Technology

CDCP2202
C Programming II

Copyright © Open University Malaysia (OUM)


CDCP2202
C PROGRAMMING II
Marini Abu Bakar
Dr Sufian Idris
Nor Leyza Jailani
Roziah Latih

Copyright © Open University Malaysia (OUM)


Project Directors: Prof Dato’ Dr Mansor Fadzil
Assoc Prof Dr Norlia T. Goolamally
Open University Malaysia

Module Writers: Marini Abu Bakar


Dr Sufian Idris
Nor Leyza Jailani
Roziah Latih
Universiti Kebangsaan Malaysia

Moderators: Yuzery Yusoff


Open University Malaysia

Kalaivani K. Radakrishnan

Developed by: Centre for Instructional Design and Technology


Open University Malaysia

First Edition, August 2014 (rs)

Copyright © Open University Malaysia (OUM), August 2014, CDCP2202


All rights reserved. No part of this work may be reproduced in any form or by any means without
the written permission of the President, Open University Malaysia (OUM).

Copyright © Open University Malaysia (OUM)


Table of Contents
Course Guide vii - x

Topic 1 Selection Control Structure 1


1.1 if Statement 1
1.1.1 if Selection Structure 2
1.1.2 if-else Selection Structure 3
1.1.3 Nested if Selection Structure 5
1.2 switch and break Statement 6
1.3 Differences Between if and switch Statements 8
Summary 16
Key Terms 16

Topic 2 Repetition 17
2.1 while Statement 17
2.2 do-while Statement 21
2.3 for Statement 24
2.3.1 The Relationship between for and
while Statements 27
2.4 Controlling Loops 28
2.4.1 Endless Loop 29
2.4.2 while Loop Controlled by Condition 30
2.4.3 while Loop Controlled by Sentry 31
2.5 continue Statement 32
2.6 break Statement 33
Summary 34
Key Terms 35

Topic 3 Functions 36
3.1 What are Functions? 37
3.2 Function Definition 38
3.3 Function Prototype 40
3.4 Function Calls 43
3.4.1 Functions without Returned Data Type
and without Parameters 43
3.4.2 Functions without Returned Data Type
but with Parameters 45
3.4.3 Functions with Returned Data Type
and with Parameters 47
3.5 Library Functions of C 48

Copyright © Open University Malaysia (OUM)


iv  TABLE OF CONTENTS

Summary 51
Key Terms 51

Topic 4 Files 52
4.1 File Support in C Programs 52
4.1.1 Binary File 53
4.1.2 Text File 53
4.2 File Operations 53
4.2.1 fopen() 53
4.2.2 fclose() 55
4.2.3 fprintf() 56
4.2.4 fscanf() 57
Summary 61
Key Terms 62

Appendix 63

Copyright © Open University Malaysia (OUM)


COURSE GUIDE

Copyright © Open University Malaysia (OUM)


Copyright © Open University Malaysia (OUM)
COURSE GUIDE DESCRIPTION
You must read this Course Guide carefully from the beginning to the end. It tells
you briefly what the course is about and how you can work your way through
the course material. It also suggests the amount of time you are likely to spend in
order to complete the course successfully. Please keep on referring to the Course
Guide as you go through the course material as it will help you to clarify
important study components or points that you might miss or overlook.

INTRODUCTION
CDCP2202 C Programming II is an advanced course and a continuation of
CDCP2101 C Programming I, which is offered by the Faculty of Information
Technology and Multimedia Communication at Open University Malaysia
(OUM). This course is worth 2 credit hours and should be covered within 8 to 15
weeks.

COURSE AUDIENCE
This course is offered to all learners taking the Diploma in Information
Technology. Learners are required to attend this course and master the subject.
This course is crucial for them to apply knowledge and skills from previous
modules by implementing programming commands, syntax and techniques.

As an open and distance learner, you should be able to learn independently and
optimise the learning modes and environment available to you. Before you begin
this course, please confirm the course material, the course requirements and how
the course is conducted.

STUDY SCHEDULE
It is a standard OUM practice that learners accumulate 40 study hours for every
credit hour. As such, for a two-credit hour course, you are expected to spend 80
study hours. Table 1 gives an estimation of how the 80 study hours could be
accumulated.

Copyright © Open University Malaysia (OUM)


viii  COURSE GUIDE

Table 1: Estimation of Time Accumulation of Study Hours

Study
Study Activities
Hours
Understanding course content and initial discussions 5
Read four topics and complete exercises given at a rate of 10 hours per 40
topic
Attend four tutorial sessions at a rate of 2 hours per session 8
Access to Websites 7
Complete one assignment at a rate of 10 hours per assignment 10
Revision 10
TOTAL STUDY HOURS 80

COURSE OUTCOMES
By the end of this course, you should be able to:
1. Apply computer programming concepts and problem solving methods
using common programming techniques; and
2. Write, compile and run computer programming using C language.

COURSE SYNOPSIS
This course is divided into four topics. The synopsis for each topic is presented as
follows:

Topic 1 describes the control feature in programming where learners can make
selection programs based on certain conditions.

Topic 2 explains the control feature in programming where learners can make
repetition programs based on certain conditions.

Topic 3 explains the meaning of function and how it works in programming,


especially for a big scale programming.

Topic 4 describes the concept, principles and techniques in manipulating files in


C programming.

Copyright © Open University Malaysia (OUM)


COURSE GUIDE  ix

TEXT ARRANGEMENT GUIDE


Before you go through this module, it is important that you note the text
arrangement. Understanding the text arrangement will help you to organise your
study of this course in a more objective and effective way. Generally, the text
arrangement for each topic is as follows:

Learning Outcomes: This section refers to what you should achieve after you
have completely covered a topic. As you go through each topic, you should
frequently refer to these learning outcomes. By doing this, you can continuously
gauge your understanding of the topic.

Self-Check: This component of the module is inserted at strategic locations


throughout the module. It may be inserted after one sub-section or a few sub-
sections. It usually comes in the form of a question. When you come across this
component, try to reflect on what you have already learnt thus far. By attempting
to answer the question, you should be able to gauge how well you have
understood the sub-section(s). Most of the time, the answers to the questions can
be found directly from the module itself.

Activity: Like Self-Check, the Activity component is also placed at various


locations or junctures throughout the module. This component may require you to
solve questions, explore short case studies, or conduct an observation or research.
It may even require you to evaluate a given scenario. When you come across an
Activity, you should try to reflect on what you have gathered from the module and
apply it to real situations. You should, at the same time, engage yourself in higher
order thinking where you might be required to analyse, synthesise and evaluate
instead of only having to recall and define.

Summary: You will find this component at the end of each topic. This component
helps you to recap the whole topic. By going through the summary, you should
be able to gauge your knowledge retention level. Should you find points in the
summary that you do not fully understand, it would be a good idea for you to
revisit the details in the module.

Key Terms: This component can be found at the end of each topic. You should go
through this component to remind yourself of important terms or jargon used
throughout the module. Should you find terms here that you are not able to
explain, you should look for the terms in the module.

References: The References section is where a list of relevant and useful


textbooks, journals, articles, electronic contents or sources can be found. The list
can appear in a few locations such as in the Course Guide (at the References

Copyright © Open University Malaysia (OUM)


x  COURSE GUIDE

section), at the end of every topic or at the back of the module. You are
encouraged to read or refer to the suggested sources to obtain the additional
information needed and to enhance your overall understanding of the course.

PRIOR KNOWLEDGE
A basic knowledge and skills in problem solving and C syntax that you would
have learned from CBCP2101 are very useful to be used for this module. Learners
will continue to practise common programming control and techniques by
applying the knowledge and skills.

ASSESSMENT METHOD
Please refer to myINSPIRE.

REFERENCE
Marini Abu Bakar, Norleyza Jailani & Sufian Idris. (2000). Bahasa Pengaturcaraan
C. Kuala Lumpur: Prentice Hall.

TAN SRI DR ABDULLAH SANUSI (TSDAS)


DIGITAL LIBRARY
The TSDAS Digital Library has a wide range of print and online resources for the
use of its learners. This comprehensive digital library, which is accessible
through the OUM portal, provides access to more than 30 online databases
comprising e-journals, e-theses, e-books and more. Examples of databases
available are EBSCOhost, ProQuest, SpringerLink, Books24x7, InfoSci Books,
Emerald Management Plus and Ebrary Electronic Books. As an OUM learner,
you are encouraged to make full use of the resources available through this
library.

Copyright © Open University Malaysia (OUM)


T op i c  Selection
1 Control
Structure
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Write C syntax for if selection, if/else selection, multiple
if/else selection and nested if selection structures;
2. Compare between the if and switch statements based on the
problem given; and
3. Differentiate between the if and switch statements.

 INTRODUCTION
In Topic 2 of CDCP2101, you have learnt how to solve problems using the
sequence, selection and repetition control structures. C language has a few
selection structures that control the flow of the program which is if, switch
and break.

1.1 if STATEMENT
The if statement is used to represent the selection structure. The selection
structure allows us to choose and execute only one of the many choices available
based on a certain condition. Selection structure is divided into three main types,
which are if selection, if-else selection and nested if selection.

Copyright © Open University Malaysia (OUM)


2  TOPIC 1 SELECTION CONTROL STRUCTURE

1.1.1 if Selection Structure


Syntax for the if selection structure is written as:

if(expression)
statement;

The if statement above will only be executed when the value of the expression is
true. If the statement is false, the statement will not be executed. Expression can
only be made up of relational or logical expressions that would have the value of
true or false.

Example 1.1: Displaying a positive value.

/* Program that will display only when a positive value


number is entered. */
#include <stdio.h>
void main()
{
int x;
printf(“Input a number: “);
scanf(“%d”, &x);
if (x > 0)
printf(“%d is a positive number\n”,x);
}
Output:

Input a number: 8
8 is a positive number

The statements above have been executed because the value of the expression is
true. If the value is false, then there would not be any message displayed on the
screen.

Example 1.2: Determining the number of days in a leap year.

/* Program will determine the number of days in a year if


the year is a leap year. */

#include <stdio.h>
#define LEAPYEAR 2000
void main()
{
int days = 365;

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE  3

int year;
printf(“Input year: “);
scanf(“%d”, &year);
if (year == LEAPYEAR)
days += 1;
printf(“Number of days this year is %d”, days);
}

Output:

Input year: 1994


Number of days this year is 366

In Example 1.2 above, the if statement determines the number of days in a year.
If the year is a leap year, then it will add one extra day to the number of days for
that year. Notice however, if statement has one statement only, which is days
+=1;. The printf() after the if statement will be executed, whether the if
statement is true or false.

ACTIVITY 1.1
Write a C program that will display the value of square root for an
integer number.

1.1.2 if-else Selection Structure


Syntax for the if-else selection structure is written as:

if(expression)
statement-1;
else
statement-2;

If the value of the expression is true then statement-1 will be executed.


However, if the value of the expression is false then statement-2 will be
executed. Statement-1 and statement-2 can also be made up of compound
statements (surrounded by { and }).

Example 1.3: Display a message whether the value entered is positive or


negative.

/* Program that will display a message if the value entered


is positive or negative. */

Copyright © Open University Malaysia (OUM)


4  TOPIC 1 SELECTION CONTROL STRUCTURE

#include <stdio.h>
void main()
{
int num;
printf(“Input an integer number: “);
scanf(“%d”, &num);
if (nom > 0)
printf(“%d is a positive number.\n”, num);
else
printf(“%d is a negative number.\n”, num);
}

Output:

Input an integer number: 3


3 is a positive number.

In Example 1.3, the if expression tests the input entered, and the expression
returns true. As 3 > 0 is true, the first statement is displayed, „3 is a positive
number‰.

Example 1.4: Comparing two integer numbers to get the smaller of the two.

/* Program that will compare two integer numbers and display


the value of the smallest input. */
#include <stdio.h>
void main()
{
int num1, num2;
printf(“Input two integer numbers: “);
scanf(“%d %d”, &num1, &num2);

if (num1 < num2)


printf(“%d is less than %d\n”, num1, num2);
else
printf(“%d is less than %d\n”, num2, num1);
}

Output:

Input two integer numbers: 17 8


8 is less than 17

In Example 1.4, the comparison of two integer numbers input is made. The
program will evaluate the value of the expression num1 < num2 as false.
Therefore, the second statement will be printed, „8 is less than 17‰.
Copyright © Open University Malaysia (OUM)
TOPIC 1 SELECTION CONTROL STRUCTURE  5

ACTIVITY 1.2

Write a C program to determine if a student passes the examination (A


student passes the examination if the score obtained is more or
equivalent to 50).

1.1.3 Nested if Selection Structure


Syntax for the nested if selection structure is given as:

if(expression-1)
statement-1;
else if(expression-2)
statement-2;
else
statement-3;

Statement-1 will be executed when the value of expression-1 is true. Statement-2


will be executed when expression-1 is false and expression-2 is true. Statement-3
will be executed when both expression-1 and expression-2 are false.

The nested if statement can be described as an if statement embedded in


another if statement, (shown as a box in the syntax above).

Example 1.5: Display a message whether the value entered is positive or negative
or zero.

/* Program that will display a message if the value entered


is positive or negative or zero */

#include <stdio.h>
void main()
{

int num;
printf(“Input an integer number: “);
scanf(“%d”, &num);
if (num > 0)
printf(“%d is a positive number.\n”, num);
else if (nom < 0)
printf(“%d is a negative number.\n”, num);
else
printf(“%d is zero.\n”, num);

Copyright © Open University Malaysia (OUM)


6  TOPIC 1 SELECTION CONTROL STRUCTURE

}
Output:

Input an integer number: 0


0 is zero.

In Example 1.3, the condition is checked for more than zero to be positive, but
zero or less than zero is displayed as negative values, which is a problem.

As there are three possible outcomes, a nested if is to be used, as given in


Example 1.5, where the condition is checked for more than zero and less than
zero. You do not need to have a condition to check for the zero as it is the third
possible outcome at the last else statement.

ACTIVITY 1.3

Write a C program that will show different messages according to the


value of the waterÊs temperature:

Water Temperature Message


10 oC and below Cold
11 oC to 25 oC Tepid
26 oC and above Hot

1.2 SWITCH AND BREAK STATEMENT


The if-else-if statement is used to select one of the many choices depending
on the value of the expression tested. It is actually easier to use the switch-
case-break statement. The switch and break statements are used to select
only one choice from many choices that exist.

This statement is very useful when the choice is dependent on the value for one
variable or simple expression. The value for the expression can only be of type
int and char, but not of type float. Consider the syntax for the statements
switch and break:

switch (expression) {
case expression-1 :
statement-1;
break;

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE  7

case expression-2:
statement-2;
break;
:
case expression-m :
statement-m;
break;
default :
statement-n;
break;
}

The expression at the switch statement will be evaluated and matched to


expression-1 until expression-m at the case. If it matches, the case statement
will be executed and will be followed by the break statement.

The break statement will bring the program control out of the switch
statement without executing the next case statement. If the break statement is
not given, then the next statement will be executed, regardless the case value
matches or not.

If the expression cannot be matched, and the default statement is available,


then statement-n will be executed. If the default statement does not exist, control
will exit the switch statement.

Example 1.6: Displaying text for a digit.

/* Program that will display text for a digit(0 – 9). */

#include <stdio.h>
void main()
{
int digit;
printf(“Input a digit: “);
scanf(“%d”, &digit);
switch (digit)
{
case 1: printf(“One”);
break;
case 2: printf(“Two”);
break;
case 3: printf(“Three”);
break;
case 4: printf(“Four”);
break;
Copyright © Open University Malaysia (OUM)
8  TOPIC 1 SELECTION CONTROL STRUCTURE

case 5: printf(“Five”);
break;
case 6: printf(“Six”);
break;
case 7: printf(“Seven”);
break;
case 8: printf(“Eight”);
break;
case 9: printf(“Nine”);
break;
default : printf(“Not a digit”);
}
}

Output:

Input a digit: 5
Five

ACTIVITY 1.4
Write a C program that will display the name of a colour when the
first letter of the colour is input.

1.3 DIFFERENCES BETWEEN IF AND SWITCH


STATEMENTS
The switch statement can be said to be an alternative to the nested if-else
statement, where the if-else expressions are then tested at each of the case’s
variable value.

The differences between these two control statements are given in the following
Table 1.1:

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE  9

Table 1.1: Differences between Nested if-else and switch Statements

if Statement switch Statement


if-else can use more than one variable switch can only use one variable to do the
to do the comparison in the expression comparison in the expression
The value of the expression is either true or The value of the expression is numeric
false (data type int or char)
Can use the relational and logical operators Cannot use relational and logical operators
in the expression in the expression
After the expression is evaluated, based on After the expression is evaluated, based on
true or false, the statements are executed the value of the expression, the case
statements are matched
Uses reserved words like if and else Uses reserved words like switch, case,
break and default.

ACTIVITY 1.5

Discuss these questions:

(a) What would happen if the if statement does not have an else?

(b) Explain the if-else statement syntax given below:

if (expression-1)
if (expression-2)
statement-1;
else
statement-2;

(c) What is the use of the reserved keyword break? What would
happen if the break statement is not given in the switch-
case control statement?

The following programs (Program 1.1, Program 1.2 and Program 1.3) are meant
for Self-Check 1.1. Kindly refer to the respective section to continue your
practices.

Copyright © Open University Malaysia (OUM)


10  TOPIC 1 SELECTION CONTROL STRUCTURE

Program 1.1
/* if-else program. Prints a certain message according
to the body weight index */
#include <stdio.h>
void main() {
float weight, height, bodyWeightIndex;
printf(“Enter your weight (kg): ”);
scanf(“%f”, &weight);

printf(“Enter your height (m): ”);


scanf(“%f”, &height);
bodyWeightIndex = weight / (height * height);
printf(“Your body weight index is %.2f\n”,
bodyWeightIndex);
if (bodyWeightIndex >= 25.0)
printf(“Your body weight is more than ideal
weight.\n Try reducing.\n”);
else
printf(“Congratulations! Your body weight is
normal.\n”);
}

Program 1.2
/* if-else program. P r i n t s a c e r t a i n
message according to the body weight
i n d e x */
#include <stdio.h>
void main() {
float weight, height, bodyWeightIndex;
printf(“Enter your weight (kg): ”);
scanf(“%f”, &weight);
printf(“Enter your height (m): ”);
scanf(“%f”, &height);
bodyWeightIndex = weight / (height * height);

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE  11

printf(“Your body weight index is %.2f\n”,


bodyWeightIndex);
if (bodyWeightIndex >= 30.0)
printf(“You’re obese! Do more exercise and
less food.\n”);
else if (bodyWeightIndex >= 25.0)
printf(“Your body weight is more than ideal
weight.\n Try reducing.\n”);
else
printf(“Congratulations! Your body weight is
normal.\n”);
}

Program 1.3
/* Prints character categories that is input using
logical expression */
#include <stdio.h>
void main() {
char chr;
scanf(“%c”, &chr);
if ((chr >= ‘a’ ) && (chr <= ‘z’))
printf(“Lower case letter\n”);
else if ((chr >= ‘A’) && (chr <= ‘Z’))
printf(“Capital Letter\n”);
else if ((chr >= ‘0’) && (chr <= ‘9’))
printf(“Digit\n”);
else
printf(“Special Character\n”);
}

Copyright © Open University Malaysia (OUM)


12  TOPIC 1 SELECTION CONTROL STRUCTURE

SELF-CHECK 1.1
1. What is the value of bodyWeightIndex and output message
displayed for each of the cases below?

Weight Height (m) BodyWeightIndex Output Message


(kg)
80.0 1.5
60.0 1.5
55.0 1.5

(a) Given the data above, edit, compile and execute Program
1.1. Fill in the information.
(b) Modify Program 1.1 to 1.2. Test the data above and fill in
the information.
(c) Edit, compile and execute Program 1.3.

SELF-CHECK 1.2

1. What is the output of the following program segments:

(a) int code;


code = 2;
if (code = 1)
printf(“Man\n”);
else
printf(“Woman\n”);

(b) int i;
i = 14;
if (i % 2 == 0)
printf(“Even Number\n”);
else
printf(“Odd Number\n”);

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE  13

(c) float weight;


weight = 55.5;
if (weight <= 50.0)
printf(“Good\n”);
else
printf(“Exercise\n”);

(d) int marks;


marks = 84;
if (marks >= 85)
printf(“Excellent\n”);
else
printf(“Work Harder\n”);

2. Given the program segment below,

float i, j;
scanf(“%f”, &i);
if (i > 3.0)
if (i < 12.0)
j = i / 100 * 5;
else
j = 10 / i * 2.5;
else
j = 5.5 * i / 2;
printf(“%f”, j);

What is the output if the input value is:


(a) 5.0 (d) 15.0
(b) 3.0 (e) 12.0
(c) 2.5 (f) 11.5

Copyright © Open University Malaysia (OUM)


14  TOPIC 1 SELECTION CONTROL STRUCTURE

SELF-CHECK 1.3

By stating the Analysis, Data Requirements, Design and


Implementation, solve the following problem:

You are instructed by your lecturer to write a program to calculate


assignment marks for this course. Marks awarded will take into
account timely submission or late submission. Students who submit
their assignments late will be fined by having their marks deducted.
The program needs the user to input marks and marks correction
factor. The correction factor value is 0 if the assignment is on time. On
the other hand, the correction factor value for late submission is
between 0.0 and 1.0. Value 0.20 means that 20% or marks will be
deducted. The program has to display the latest marks. Below are
examples of input/output:

Input marks > 71


Input correction factor (0 if not late) > 0.20
New marks= 56.80

Input marks > 83


Input correction factor (0 if not late) > 0
New marks= 83.00

Try Self-Check 1.4 to reinforce your understanding.

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE  15

SELF-CHECK 1.4

1. You do not need to write a program for this problem. Instead, you
need to solve how to calculate the charges for using water for a
particular month that is provided by the Water Utility Company.
Charges are calculated based on these information:
 Outstanding payment amount;
 Previous meter reading; and
 Current meter reading.

Payment rates are given as:

0 ă 15 m3 : RM0.42 every m3,


15.1 ă 40 m3 : RM0.65 every m3,
40.1 m3 and above : RM1.05 every m3

With minimum payment of RM5.00


(a) State the input and output of this problem.
(b) State the formula involved.
(c) Give the detailed algorithm for this problem.

2. Write a program that would calculate the marks needed for the
final examination by a student to enable him/her achieve a
particular grade in a course. Your program should have
input/output interaction as shown below:

Input grade > B


Input minimum average marks needed to reach
grade > 79.5
Input your current average marks > 74.6
Input percentage contributed by final examination >
25
==========
You need to get at least 94.20 marks in the final
examination to get a grade B. In the example
above, the final examination marks contribute to
25% of the overall marks.

Copyright © Open University Malaysia (OUM)


16  TOPIC 1 SELECTION CONTROL STRUCTURE

Ć You have looked at the C syntax for the selection control. There are three
forms of the if statement ă if, if-else and nested if-else.

Ć You have also learnt how to use the switch and break statements.

Ć The differences between these control structures are also given.

break Logical expression


case Nested if
Control Relational expression
Default Selection
else Structure
if switch

Copyright © Open University Malaysia (OUM)


T op i c  Repetition
2
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Implement C programs using repetition structure such as for, while
and do-while statements;
2. Differentiate between for, while and do-while statements;
3. Use continue and break statements as a jump instruction; and
4. Write nested loops depending on the problem given.

 INTRODUCTION
In the previous topic, you were introduced to the algorithm of a repetition
structure where a few statements can be repeated until a condition is satisfied. In
C, repetition structure can be represented by while, do-while and for
structure.

2.1 while STATEMENT


The while statement is used to perform repetition on a few statements when the
expression is true.

Syntax for the while statement:

initialisation;
while(expression)
{
statement;

Copyright © Open University Malaysia (OUM)


18  TOPIC 2 REPETITION

counter;
}

Figure 2.1 describes briefly the while statement.

Figure 2.1: The while statement

Expression can be made up of a relational or a logical expression that either has


the value true or false. The statement, likewise can be written as a single
statement or a compound statement which are enclosed by { and }. The
initialisation always has a variable and its value will be tested in the expression.
Update the counter to ensure that the expression value becomes false eventually
so that the while statement can end.

The while statement is executed in this sequence:


1. Do the initialisation;
2. Test the expression;
3. If the expression is true, then do the statements (including the counter).
Repeat step 2; and
4. Alternatively, if the expression is false, the while statement ends.

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION  19

Let us now take a look at an example of using the while statement.

Example 2.1: Displaying numbers from 1 to 10.

/* Program that displays numbers from 1 to 10*/

#include <stdio.h>
void main()
{
int x = 1;
while (x <= 10)
{
printf(“%d\t”, x);
x++;
}
}

Output :
1 2 3 4 5 6 7 8 9 10

In Example 2.1 above, the expression x <= 10, is true at the beginning. After
displaying 1 on the screen, x has been updated by 1, by the x++ statement.
Because the expression in the while expression,(2 <= 10) is still true,
therefore, 2 is also printed on the screen. These steps will be repeated until x
value is added 1 to be 11. The expression is now false, and the while statement
will end.

In Example 2.2, we will see how an input value is used in the while expression.

Example 2.2: Adding all numbers from 1 to n.

/* Program adds all numbers from 1 to n which is input by


user */

#include <stdio.h>
void main()
{
int num, x = 1, total = 0;

printf(“Input number : “);


scanf(“%d”, &num);
while (x <= num)
{
total += x;
x++;
}
Copyright © Open University Malaysia (OUM)
20  TOPIC 2 REPETITION

printf(“Total of numbers from 1 to %d is %d.\n”, num,


total);
}

Output:

Input number: 10
Total of numbers from 1 to 10 is 55.

ACTIVITY 2.1

1. Write a program that will display even numbers from 2 to 20.


2. Write a program that will input positive numbers, which ends
when 0 is entered.

ACTIVITY 2.2
Discuss why the input is done twice in the program you have written
in Activity 2.1(b).

SELF-CHECK 2.1

1. Complete the segment code below so that the output generated is


as follows:
3 6 9 12 15 18 21 24 27 30
i = 1;
while (_________) {
printf(______________);
___________;
}

2. Write the output generated by the program code below:


int i;
i = 9;
while (i > 0) {
printf(“%d\n”, i);
i -= 2;
}

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION  21

2.2 do-while STATEMENT


This statement is similar to the while statement, because it too has initialisation,
expression, statements and counter.

Syntax for do-while statement:

initialisation;
do
{
statement;
counter;
} while (expression);

Similar to the while statement, expression can be made up of a relational or a


logical expression that has the value true or false. The statement, likewise can be
written as a single statement or a compound statement which are enclosed by {
and }.

The initialisation always has a variable and its value will be tested at the end.
Update the counter to ensure that the expression value becomes false eventually
so that the do-while statement can end.

Figure 2.2 describes briefly the do-while loop execution.

Figure 2.2: The do-while statement

The do-while statement is executed in this sequence:


1. Do the initialisation;
2. Do the statement and the counter;
3. Test the expression;
4. If the expression is true, then repeat steps 2 to 4; and
5. Alternatively, if the expression is false, the do-while statement ends.
Copyright © Open University Malaysia (OUM)
22  TOPIC 2 REPETITION

Let us now take a look at an example of using the do-while statement.

Example 2.3: Displaying numbers 1 to 10.

/* Program to display numbers from 1 to 10 */

#include <stdio.h>
void main()
{
int x = 1;

do
{
printf(“%d\t”, x);
x++;
} while (x <= 10) ;
}

Output :
1 2 3 4 5 6 7 8 9 10

You would have noticed that this program is similar to the one in Example 2.1.
To solve the problem of displaying numbers from 1 to 10, you can use any
repetition structure, while or do-while. It is actually a choice of preference.

Next, you will see how to stop a loop (repetition) by using an input from the
user, in Example 2.4.

Example 2.4: Adding all positive numbers being input until 0 is entered.

/* Program that will add all the positive numbers entered,


until 0 is entered. */
#include <stdio.h>
void main()
{
int num, total = 0;
do
{
printf(“Input a positive number to add, 0 to stop: “);
scanf(“%d”, &num);
total += num;
Copyright © Open University Malaysia (OUM)
TOPIC 2 REPETITION  23

} while (num != 0);


printf(“Total of positive numbers entered : %d”, total);
}

Output:
Input a positive number to add, 0 to stop: 1
Input a positive number to add, 0 to stop: 2
Input a positive number to add, 0 to stop: 3
Input a positive number to add, 0 to stop: 4
Input a positive number to add, 0 to stop: 5
Input a positive number to add, 0 to stop: 0
Total of positive numbers entered : 15

ACTIVITY 2.3

1. What is the minimum number of times a while loop will be


executed? What about do-while loop?

2. What does the program below do?


#include <stdio.h>
void main()
{
int i, total = 0;
do {
scanf(“%d”, &i);
if( i < 0)
i = -i;
total += i;
} while (i != 0);
printf(“Total is : %d”, total);
}

Copyright © Open University Malaysia (OUM)


24  TOPIC 2 REPETITION

SELF-CHECK 2.2

Write a code segment that uses a while loop which would execute
similarly to the execution of the do-while loop below.

do {
scanf(“%d”, &data);
} while (data != -1);

2.3 FOR STATEMENT


The for statement is to write loops in an easy format, but the number of loops
are to be known at the time of writing the program.

Syntax for a for statement:

for (initialisation; expression; counter )


{
statement;
}

Figure 2.3 describes briefly the for statement.

Figure 2.3: The for statement


Copyright © Open University Malaysia (OUM)
TOPIC 2 REPETITION  25

The for statement is executed in this sequence:


1. Do the initialisation;
2. Test the expression;
3. If the expression is true, do the statement and repeat steps 2 and 3.;
4. Alternatively, if the expression is false, the for statement ends; and
5. Update the counter.

You will now see the program that displays the numbers 1 to 10, but using the
for statement instead.

Example 2.5: Displaying numbers 1 to 10.

/* Program that displays numbers 1 to 10 */

#include <stdio.h>
void main()
{
int x;
for (x = 1; x <= 10; x++)
printf(“%d\t”, x);
}

Output :
1 2 3 4 5 6 7 8 9 10

You will notice that in example 2.1, 2.3 and 2.5, the output is the same, only those
different loops were used: while, do-while and for. All three loops have
similarities: initialisation, expression and counter. Which one of these loops
would you use and why?

Three important aspects of writing correct loops are:

(a) Initialisation ă without the initial value, the expression cannot be tested,
and therefore the statement is not executed.

(b) Expression ă if the expression is written wrongly, where the expression is


always true (does not end) or always false (does not start).

(c) Counter ă most often forgotten, as in the while and do-while loops, it is
part of the compound statements. If the counter is not done, the program
might not end, as the expression might be true, based on the initial value.

According to C syntax, the for statement body has to be one statement. What
Copyright © Open University Malaysia (OUM)
26  TOPIC 2 REPETITION

happens if a group of statements needs to be repeatedly executed? The way is to


combine the statements into a compound statement. The compound statement is
formed by surrounding the statements with the symbols { and }.

Consider Program 2.1 that will read 10 numbers and then output the total and
average.

Program 2.1

/* Input 10 numbers and then output the total and


average */

#include <stdio.h>
void main () {
int x;
int number;
int total;
float average
Compound statement
total = 0;
for (x = 0; x < 10; x++)

{
printf (“Enter an integer value”)
scanf(“%d”, &number);
total = total + number;
}

average = (float) total/10;


printf(“Total: %d\n”,total);
printf(“Average: %.2f\n”, average);
}

ACTIVITY 2.4

Write a C program that can display the output below using for, do-
while or while loop:

*****
***
*

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION  27

SELF-CHECK 2.3

1. What is the output generated by the following loop?

for (x=10; x > 0; x—)


printf(“%d\t”, x);

2. What is the output generated by the following loop?

for (dig=0; dig <= 20; dig = dig+2)


printf(“%d\t”, dig);

3. Write the segment code again below by changing the for loop
with the while loop.

for (c=’A’; c <= ‘Z’; c++)


printf(“%c\t”, c);

2.3.1 The Relationship between for and while


Statements
If we compare the flow of the for statement execution with the while statement
execution, we can see the equality between them. Still, a for loop can be
changed into a while loop that is similar to it and vice versa. We will see now
how to change a for loop into a while loop.

Recall that the for general form is:

for (initialisation; test; update)


Statement;

We can use the segment code below as a template to write a while loop which is
comparable to the for loop.

initialisation;
while (test) {
statement;
update;
}

Copyright © Open University Malaysia (OUM)


28  TOPIC 2 REPETITION

ACTIVITY 2.5

Sketch the execution flow for the while loop code template above.
Compare that to the flow chart in Figure 2.2.

2.4 CONTROLLING LOOPS


As we understand it, a non-zero represents the true value whereas a zero
represents a false value. This can allow us to control the repetition of the
execution of the body in a loop statement.

Consider the code segment below:

printf("Input a number larger than 0:");


scanf("%d", &num);
x = num - 1;
total = 0;
1
while (x != 0) {
total += x;
x--;
}

Looping of the while statement in the code segment is controlled by the


condition (x != 0). In other words, the repetition of the statement body will
continue as long as the condition is true, that is as long as the value x has not
reached zero. Based on how C represents the value true and false, we can rewrite
the while statement in the segment code above as below:

2
while (x) {

total += x;
x--;
}

Statement while 2 is comparable to statement while 1 since both will end when
the value of x reaches zero. Sometimes the test component of a while
statement is false at the beginning of the statementÊs execution. In this case, the
body of the loop will not be executed at all.
Copyright © Open University Malaysia (OUM)
TOPIC 2 REPETITION  29

2.4.1 Endless Loop


When we write a repetition statement, the most important thing that we look
into is its stopping condition. We need to ensure that the execution of the
statement will eventually end. Observe the following code segment:

printf(“Input a number: ”);


scanf(“%d”, &num);
x = 0;
while (x != num)
x++;
printf(“Value of i is %d\n”, i);

In that code segment, an integer number will be input and assigned to the
variable num. Variable x is initialised to the value 0. The while statement will
increase variable x by 1 repeatedly until the value of the variable is the same as
the value of num.

The code segment above looks reasonable. Still, what will happen if a negative
value is input? We will see that the execution of the while statement will not
end. The test component for the statement is always true since the value of
variable x will not be the same as num. If this condition happens, we would say
that an endless loop has been created.

In Example 2.6, a program that shows an endless loop is given. Please execute
this program with care, ending all other applications before running this
program.

Example 2.6: Endless Looping with for statement

/*Program that does not have an initialization, expression


and counter. NOTE: THIS PROGRAM DOES NOT END – MANUALLY
CLOSE THE APPLICATION */

#include <stdio.h>
void main()
{
for ( ; ; )
printf(“This statement is never displayed”);
}

Program in Example 2.6 shows that a for loop can be written without the
initialisation, expression and counter, but with the correct syntax (semicolons ;) to
Copyright © Open University Malaysia (OUM)
30  TOPIC 2 REPETITION

divide the different parts. The program above can be executed, without any
syntax errors, but the statement is always true and therefore does not end.

ACTIVITY 2.6

Try to rewrite the program above using the for repetition control
structure.

2.4.2 while Loop Controlled by Condition


The while loops in the examples before are called loops determined by
condition. These loops will continue its repetition until a certain condition is met.
Program 2.2 is another example that uses loop determined by condition. The task
of this program is to input a number of data, count the even and odd numbers
and at the end output a summary.

Program 2.2
/* Input the number of data followed by the data itself.
Then count the number of even and odd numbers for input
data.*/

#include <stdio.h>
void main() {
int count, x, num, countEven, countOdd;
x = countEven = countOdd = 0;

printf(“Number of data:”);
scanf(“%d”,&count);

while(x<count){
printf(“Enter positive integer:”);
scanf(“%d”,&num);
if(num%2==0)
countEven++; Do these
else repeatedly: Read
countOdd++; the data and update
x++; the number of odd
} and even numbers

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION  31

printf(“Number of even numbers:\t%d\n”,countEven);


printf(“Number of odd numbers:\t%d\n”,countOdd);

Calculated output

ACTIVITY 2.7

Think of the output for Program 2.2 if the input given is as follows:
Number of data: 5
Number of positive integer: 3 2 1 4 7

2.4.3 while Loop Controlled by Sentry


Consider Program 2.2 again. This program needs to know how many data is to
be input because that is the number of data being input. Still, there might be
situations where the number of data being input cannot be determined earlier.

Therefore,

A loop controlled by sentry is a loop that will repeat according to a value


that is called the sentry value.

(a) Sentry value is the value that is out of the boundary of valid data.
(b) Loops like these are suitable to be used in situations where the number of
repetitions cannot be determined.

To help in your understanding, do the following exercises.

Copyright © Open University Malaysia (OUM)


32  TOPIC 2 REPETITION

SELF-CHECK 2.4

Consider the program below:


scanf(“%d”, &data);
while (i != -1) {
printf(“%d “, data/5);
scanf(“%d”, &data);
}

1. What is the sentry data used in the code segment above?

2. What is the output generated by the code segment above if the


input data is 5, 10, 15, 20, -1?

2.5 CONTINUE STATEMENT


Other than the expression component, there are two other statements available in
C that are used to control the repetition structure of while, do-while and for,
which are continue and break statement.

continue statement is used when the statement immediately after in the loop is
not to be executed, and the program control will return to the while, do-while
and for statement.

Example 2.7: Displaying even numbers.

/* Program that will display even numbers only */


#include <stdio.h>
void main()
{
int x;
for (x = 0; x <= 9; x++) {
if (x % 2 != 0)
continue;
else
printf(“%d even number\n”, x);
printf(“Prints even numbers only! \n”);
}
}

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION  33

Output:
0 even number
Prints even numbers only !
2 even number
Prints even numbers only !
4 even number
Prints even numbers only !
6 even number
Prints even numbers only !
8 even number
Prints even numbers only !

In Example 2.7 earlier, the for statement is repeated 10 times, from 0 to 9. Only if
the numbers are even ( x % 2 == 0 to test for even numbers), the first
printf() statement is executed. The second printf() statement is printed
every time the even numbers are printed, but not for when the numbers are odd
(as the continue statement controls the flow of execution to the for expression).

2.6 BREAK STATEMENT


The break statement, on the other hand, is used when exiting the execution of
the loop. It will force the expression to be false before its time. Therefore, break
statement can be used when using while, do-while and for statements and
the program needs to end based on some value that does not evaluate the
expression.

As an example, numbers starting from 1 will be added to the number before it


until the total value exceeds 100. How many repetitions are necessary before the
total becomes 100? Consider Example 2.8 to solve this problem.

Example 2.8: Totalling numbers from 1 till total is more than 100.

/* Program that will total numbers starting from 1, till its


total reaches 100 or more. */

#include <stdio.h>
void main()
{
int n, total=0;
for (n = 1; n <=25; n++)
{
total = total + n;
if (total >= 100)
break;
}
Copyright © Open University Malaysia (OUM)
34  TOPIC 2 REPETITION

printf(“Total value = %d\n”, total);


printf(“n value = %d\n”, n);
}

Output:
Total value = 105
n value = 14

In Example 2.8, the break statement has caused the for statement to end before it
repeated 25 times as stated. It is because of the total has reached more than 100.

ACTIVITY 2.8

Write C programs that will:


(a) Input an integer value and if its value is 5, it will display a
message „The number 5 is input‰. This program will end when
the number 5 is entered. Which of the repetition structures are
suitable for this problem?
(b) Input five integer numbers, and using the while statement,
determine the largest number.
(c) Input a lower case letter and display the equivalent upper case
letter, until the user enters!

Ć You have been introduced to the three repetition constructs ă while, do-
while and for statements.

Ć The initialisation, expression and counter which are important for all
repetition constructs are explained.

Ć You have also seen the break and continue statements are used together
with the repetition constructs and how they can control the loopsÊ execution.

Ć Controlling loops can be done either through controlled condition or


controlled by sentry value. Endless loop must be avoided.

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION  35

break Logical
continue Relational
counter Repetition
do-while Statement
for while

Copyright © Open University Malaysia (OUM)


Topic  Functions
3
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Define functions and its components;
2. Write function prototype, function call and function definition;
3. Write C programs that invoke functions; and
4. Describe the use of library functions in a program.

 INTRODUCTION
C is a procedural language. It has functional features that enable us to structure
our programs better. So far, the program examples given are easy and small. In
fact, all program statements can be put into one function which is the main()
function. This structure is not suitable for large programs because it makes the
programs hard to read and understand. Proper code arrangement is needed so
that it can clarify logical structure and flow of program execution. This will make
sure programs are easier to read, understand and maintained.

This topic will explain these functional features. We will learn:


(a) What are functions; and
(b) How we define our own functions.

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS  37

3.1 WHAT ARE FUNCTIONS?


Functions are a segment of a program by itself that does a specific task. All C
programs have at least one function, which is the main function. A program can
have many different functions but a function cannot be contained in another
function.

There are three important components in a function:


(a) Function declaration
(b) Function prototype
(c) Function calls

All of these components will be discussed in detail in this topic.

Figure 3.1: Functions in programs illustration

In Figure 3.1 above, the main function will be executed first. At the statement call
functionA, the whole of functionA will be executed. After ending functionA,
control is transferred back to the main function. The next statement is call
function B, where the whole function B is executed. At the end of function
B, control is back to the function main and ends.

Copyright © Open University Malaysia (OUM)


38  TOPIC 3 FUNCTIONS

3.2 FUNCTION DEFINITION


Functions can be defined as having a head and a body. Let us look at the function
syntax:

returned_data_type function_name (parameter_list) Head


{
function_body Body
}

The function head is made up of three main parts: returned data type, function
name and parameter list. All three parts are important to determine the identity of
the function, and other functions cannot have the same function head.

(a) Returned Data Type


There are four returned data type data: char, int, float and double.
There is a void return type as well, when there is no data to be sent back to
the calling function, and char[] which is the character array return type, is
used when a character array is to be returned from the function.

(b) Function Name


Naming a function is similar to naming a variable. Each function will have its
own unique name, given by the programmer (except for predefined function
names).

(c) Parameter List


This list is made up of variable declaration of all the values to be inserted into
the function.

The function body is made up of statements that you have learnt in the topics
before this, like declaring variables, input and output statements, selection and
repetition. The function body must be enclosed in { and }. The last statement in a
function should be the return statement (not necessary if returned data type is
void). There should only be one return statement per function.

Next, we will see some examples on how to write functions. Notice however, that
some of the examples are only showing functions and not the whole program
code. You cannot run these programs as they are. You should also include the pre-
processor files (#include <stdio.h>) and the main function.

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS  39

Example 3.1: A simple function.

void display (void)


{
printf(“Hi\n”);
}

In the above example, the display function does not have a returned data type
value and neither does it have any parameters. Therefore the word void is written
in its place. If nothing is written in the returned data type, it is of type int by
default.

Example 3.2: Function definition with a returned data type and a parameter list.

int addition (int x, int y)


{
int total = 0;
total = x + y;
return total;
}

In Example 3.2, the returned data type is int, which means that the data is
returned from the function is of type integer. The name of the function is
addition and the parameter list has the declaration of two variables, x and y of
type integer. (Note: every variable must be defined separately in the parameter
list). The function body declares a variable called total, which will be assigned
the sum of x and y. The variable total value will be returned through the
return statement written on the last line of the function body.

Next, we will see a complete program using function prototypes, functions


definitions and function calls.

Example 3.3: A complete program showing the use of functions in C program.

#include <stdio.h>
void display_message (void); // function prototype

void main (void)


{
printf(“In function main\n”);
display_message(); // function call
printf(“Return to function main\n”);
}

Copyright © Open University Malaysia (OUM)


40  TOPIC 3 FUNCTIONS

void display_message(void) // function definition


{
printf(“In function display_message\n”);
}

Output:

In function main
In function display_message
Return to function main

Let us look at some of the important sections of the program code in Example 3.3.
First, there is the function prototype, which will declare the name and returned
data type as well as any parameter types of the function. Next, is the function call.
Function call is where the function name is used and the control of the program is
transferred to the function. Lastly, the function definition which we have recently
seen. All of these sections will be explained in detail in the next section.

ACTIVITY 3.1

Write a C program that will add two floating point numbers in a


function called addition and the total is returned and displayed from
the main function.

ACTIVITY 3.2

1. Can the function definition start with the name of the function
(without first writing the returned data type)?

2. What would happen if the return statement is not written on the


last line of the function?

3.3 FUNCTION PROTOTYPE


C programs can be written without a function prototype, but the function must
be defined by the programmer, before the main function (before the function
calls are written). As most programmers prefer to write programs by adding
more functions downward (after the main function), the function prototype is
necessary. The function prototype is normally written before the main function.

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS  41

The main reason the function prototype is written is to proved information of the
type of return value (if any), and the number and type of parameters. The
definition of function prototype is the same with the function head, and is ended
with the semicolon(;). The function prototype given below is also accepted, as the
name of the variables in the parameter list can be ignored.

void addition (int, int);

One of the advantages of using a function prototype is that the programmer can
easily read and identify all the functions that are used in the program.

Example 3.4: Function prototype usage.

#include <stdio.h>
void square (int x); // function prototype

void main(void)
{
int num = 5;
square (num); // function call
}

void square (int x) // function definition


{
printf(“Square of %d is %d”, x , x * x);
}
Output:
Square of 5 is 25

In Example 3.4 above, the function prototype: void square (int x); is
checked when the function call: square (num); is made. Because of the
returned data type, function name and parameter list (an integer type variable) is
the same as the function prototype, there is no error.

In Example 3.5, shows how an error in the function prototype leads to the
program not able to run efficiently.

Example 3.5: How an error in the function prototype leads to the program not
able to run efficiently.

#include <stdio.h>
int print_message (int num);

void main(void)
{
Copyright © Open University Malaysia (OUM)
42  TOPIC 3 FUNCTIONS

int number = 10;


print_message (number);
}

void print_message (int num)


{
printf(“Data that is received is : %d”, num);
}

No output.

In Example 3.5 above, the compilation error happens when the statement
print_message (number); is compiled. This is because there isnÊt any
function prototype found with the void returned data type (the function
prototype has an integer returned data type). To avoid having errors like this,
ensure that the function prototype written above the main function and the
function definition: returned data type, function name and parameter list match.

ACTIVITY 3.3

Correct the errors in the program below, so that no syntax error is


reported.

#include <stdio.h>
void main (void) {
int x;
printf (“Input a value: “);
scanf(“%d”, &x);
printf(“Absolute value: %d\n”, absoluteValue(x));
}

void absoluteValue( int x) {


if (x < 0)
return –x;
else
return x;
}

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS  43

3.4 FUNCTION CALLS


To execute a function, we need to call the function. Calling a function means
transferring the control of the program to the beginning of the function. Once the
function has been executed, the control will be transferred back to the statement
after the function call.

If there is data to be sent to the function, use the parameters after the name of the
function to be called.

Example 3.6: Samples of function calls with parameters.

calculateSum(input1, input2);

square(num1, num2);

If there is data to be returned to the function, assign the returning value to a


variable which is of the same type as the returned data type declared for the
function called.

Example 3.7: How the values returning from the function are assigned.

int result;

result = add(3, 6);

Therefore, functions can be of three types:


(a) Functions without returned data type and without parameters;
(b) Functions without returned data type but with parameters; and
(c) Functions with returned data type and with parameters.

Function calls are determined by the type of the function. In the next examples,
explanations will be given on each type of function.

3.4.1 Functions without Returned Data Type and


without Parameters
Functions like these are to display error messages or explanation on a
programming case. The function call is written as:

function_name;
Copyright © Open University Malaysia (OUM)
44  TOPIC 3 FUNCTIONS

Even though there is no value sent to the function, there are still brackets () after
the function_name. It is also not assigned to any variable.

Example 3.8: Function without returned data type and without parameter.

#include <stdio.h>
void display (void);

void main(void)
{
display(); // function call
}
void display(void)
{
printf(“Welcome to the world of C Programming\n”);
}

Next is an example of a function declaration without parameters.

void draw_sides4(void) {
int row, columns;
for (row=0; row < 4; row++) {
for (column=0; column < 5; column++)
printf(“*”);
printf(“\n”);
}
}

Notice however the keyword void after the name of the function. This states
that the function is declared without any parameters.

Consider the program below that calls the function above:

void main(void) {
printf(“This is a square\n”);
draw_sides4();/*calling a function without
a parameter*/
printf(“Good Luck!”);
}

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS  45

Figure 3.2: Calling a function without parameters

This program generates the following output:

This is a rectangle
*****
*****
*****
*****
Good Luck!

3.4.2 Functions without Returned Data Type but with


Parameters
There are functions that need data from the calling function to do a particular
task. The data is sent to the function through the parameters that are written in
the brackets () after the function name. The function call will be written as:

function_name(parameter list);

The parameter list can be made up of constants, variables or expressions. Since


there is no value to be returned, the function call does not need to be assigned to
any variable.

Copyright © Open University Malaysia (OUM)


46  TOPIC 3 FUNCTIONS

Example 3.9: Multiplication function.

#include <stdio.h>
void multiplication (int, int); // function prototype

void main(void)
{

multiplication(2,3); // function call


}

void multiplication(int x, int y)


{
int value;
value = x * y;
printf(“Multiplication: %d x %d = %d”, x, y, value);
}

In Example 3.9, the multiplication function requires two integer parameters. In


the function call, multiplication(2,3); the values 2 and 3 are provided in the
parameter list to be sent to the multiplication function. As the output is displayed
within the multiplication functions, there is no need to return the value to the
calling function.

Figure 3.3 shows another example of how the function can be utilised with
parameters.

Figure 3.3: Calling Functions with Parameters


Copyright © Open University Malaysia (OUM)
TOPIC 3 FUNCTIONS  47

3.4.3 Functions with Returned Data Type and with


Parameters
Most of the functions are in this form. When data is entered into the function,
there is a value to be returned to the calling function after ending this function.
Even though the size of the parameter is not limited, we can insert many function
of many types into a function. There can only be one value returned from a
function, written in the return statement.

Function calls syntax is written as:

variable = function_name(parameter list);

The variable must be the same type as the returned data type that was written in
the called function head.

Let us now take a look at a function, Example 3.10, that shows how the function
maximum is called and the maximum value is returned to the main function.

Example 3.10: Getting the maximum value of two numbers.

#include <stdio.h>
int maximum (int, int);

void main(void)
{
int x, int y;

printf(“Input two integer numbers:”);


scanf(“%d %d”, &x, &y);
printf(“Larger value is: %d\n”, maximum (x,y));
}

int maximum(int x, int y)


{
int max;
if (x < y)
max = y;
else
max = x;

return max;
}

Copyright © Open University Malaysia (OUM)


48  TOPIC 3 FUNCTIONS

Notice that the variable x and y are declared as integer in the main function and
also in the function head of maximum function. This phenomena is called local
variables, where the variables are declared and used in a particular function, and
are not known outside the boundary of the function. You may name the variables
in different functions differently, or choose the same name, as their values are
kept in separate memory cells.

ACTIVITY 3.4
Write a C program that will use the function named positive that
receives one data of type integer, and returns the absolute value of it
to the main function where it is displayed.

3.5 LIBRARY FUNCTIONS OF C


Program code reuse is one of the methods often practiced by programmers when
developing any software. Through this method, the programmerÊs productivity
can be increased. By using program code reuse that has been written and tested
for errors before, programmers can avoid writing the same program code again.

C Language provides library functions that have many types of functions already
defined and can be used again by programmers. For example, sqrt() function
to calculate square root is available in the mathematics standard library. The next
example contains examples of reusing this sqrt() function.

#include <stdio.h>
#include <math.h> // math preprocessor file

void main(void)
{
double num, amount;
printf(“Enter number: “);
scanf(“%f”, &num);
amount = sqrt (num); // C standard function
printf(“Square Root of %lf: %lf”, num, amount);
}

Output:

Enter number: 16.0


Square Root of 16.0: 4.0

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS  49

Let us look at the sqrt() function calls in the program code above that causes
the execution of the function code. In the call, the value of the argument num is
passed from the calling function to be used in the calculation.

For example, let us say the number being input is 16.0. Therefore the variable
amount calls the sqrt() function to calculate the square root of that number.
After the function code is executed, the control of the program will move back to
the calling program. The result of the calculation will be returned and assigned to
the amount variable. The program ends by outputting the result of the
calculation using the printf() function.

Notice however that the program above contains the pre-processor directives
#include<math.h>. This instruction will cause the header file math.h to be
included with the program code before compilation. The header file is needed
because it contains useful information on the functions that are available in the
mathematics standard library including the function sqrt() that will be reused
in the program code above.

ACTIVITY 3.5

Write a C program that will:


(a) Get an integer number from a function called numberinput. The
programme will exit when a 0 is entered.
(b) Use a function named NumberToText that will receive an
integer number from 1 to 10 only and display it in Text.

ACTIVITY 3.6

1. Write two standard function names that you normally use.

2. What are some advantages of using standard C functions?

Copyright © Open University Malaysia (OUM)


50  TOPIC 3 FUNCTIONS

SELF-CHECK 3.1

1. Consider the following function:


float calcPay(int j, int total) {
float g;
if (j <= 40)
g = 4.5 * j;
else
g = (j - 40) * 5.5 + 4.5 * 40;
if (j > 100)
g += (j-100) * 3.0;
return g;
}

What is the value returned by the function for the calls below:
(a) calcPay(35, 120)
(b) calcPay(50, 100)

2. Write the function definition for the function


displayRectangle() that will display a rectangle on the
screen. This function has two parameters which are the width
and height of the rectangle that will be displayed by it. As an
example, calling displayRectangle(6,4)will display the
following output:

******
******
******
******

3. Write a function definition for printNumber() that receives


two integer numbers M and N as its parameters. This function
will print all numbers between M and N, including the two
numbers. If M is smaller than N, the function will print the
numbers in ascending order. Alternatively, if M is larger than N,
the numbers will be printed in descending order.
For example, if M and N are 7 and 3 respectively, then the
output is:
7 6 5 4 3

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS  51

Ć In this topic, we have learnt all about functions which are small programs
that can do a specific task.

Ć We have seen how to define and call functions. There are some functions that
require parameters when called. The parameters are input to the function.

Ć At the end, we have seen the C standard function that can be used after
adding the appropriate header files that contains the function in our
program.

Ć Two types of variables that have different scopes are local and global.

Ć A variableÊs scope determines the area where the variable can be reached.

Definition Parameter list


Function Prototype
Library function Recursion

Copyright © Open University Malaysia (OUM)


Topic  Files
4
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Write C programs which have file manipulation; and
2. Input data from file and channel output to a file.

 INTRODUCTION
Data that is used in the programming examples in the topics before is only
temporary. After the program has ended, the data will be lost. Therefore, ways to
keep data permanently has to be known. In this topic, you will learn about files
used to store data.

4.1 FILE SUPPORT IN C PROGRAMS


C language provides many standard functions for file input output operations.
With this support, we can write C programs to read data from files. Program
data can be kept in data files that can be used repetitively. In addition, we can
write programs that channel output to files.

There are two methods of accessing data that is stored in files, which is
sequential or random access. These access methods determine how data is read,
written, modified and deleted by the program.

When a data is accessed sequentially, it will be read in the order it is written. To


read a sequential file is like playing a cassette tape; we need to play it in order to
ensure the songs are on the tape. Accessing a file randomly is like playing a CD;
you can directly access and play the songs in any order.

Copyright © Open University Malaysia (OUM)


TOPIC 4 FILES  53

Files in C language are categorised into two types: binary file or text file. Binary
files can keep data in smaller sizes but text files are easier to use.

4.1.1 Binary File


Normally, it was known as a file that is not formatted, and keeps data in blocks
that has contiguous bytes. There is a special standard library file, to process
binary files. Binary files will not be discussed further in this topic or used in any
of the example.

4.1.2 Text File


Text files are sequence of characters that can be created using notepad.exe or any
other text editor that you normally use. The file extension is normally .txt or .dat.

4.2 FILE OPERATIONS


Only sequential file access will be discussed in this topic. Usually, there are three
operations that can be done to a sequential access file, which are create file,
reading , writing data and closing a file.
(a) Creating a file ă fopen();
(b) Reading a file ă fscanf();
(c) Writing to a file ă fprintf(); and
(d) Closing a file ă fclose().

4.2.1 fopen()
Before any operation can be carried out on a file, it must be opened first. In C,
when opening any file, we must send file name and access mode (either we want
to read, write or add data to a file). The relevant function used is fopen().
Format to invoke (call) it is as below:

fopen(file_name, access_mode)

The file_name is the name of the file to be opened, whereas access_mode is the
mode used to access the file and will be explained in detail later. The fopen()
function returns a pointer that will point to the file opened. This pointer is used
later in the operations that are carried out on the file. Usually, the pointer will be
kept in a variable type FILE *. Look at the code segment:
Copyright © Open University Malaysia (OUM)
54  TOPIC 4 FILES

FILE *fptr;
Fptr = fopen(“datafile”’ “r”);

fptr is a variable that is declared to keep the file pointer. After the calling of
fopen()function ends, the pointer pointing to the file „datafile‰ will be returned
by the function. The pointer will then be assigned to fptr.

Access mode of any file determines the operations that can be done on that file.
Table 4.1 shows the access modes that are specified in the fopen()function calls.

Table 4.1: Access Modes

Access Modes Explanation


„r‰ File is opened for read only
„w‰ File is opened for writing only (start from the beginning of file)
„a‰ File is opened for writing only (start from the end of file)
„r+‰ File is opened for updating (read and write)
„w+‰ File is opened for updating (create, read and write)
„a+‰ File is opened for updating (read the whole file or writing at the
end of file.)

The code segment below shows the usage of fopen() function to open the file
input and file output. File input is opened for reading only whereas file output is
opened for writing only.

FILE *fptr1, *fptr2;


fptr1 = fopen(“input”, “r”);
fptr2 = fopen(“output”, “w”);

Sometimes the file that is required to be opened cannot be opened using the
fopen() function. For example, we want to open a file to be read, but the file
does not really exist. In this situation, the fopen() function will return a null
pointer (represented by the value NULL) if it fails to open the file in the required
mode.

It is important that we can trace the event so that the errors that cause the file
operation to return a null pointer can be avoided. The code segment below
shows how to trace the return of null pointer by fopen().

fptr = fopen(“inputfile”, “r”);


if (fptr == NULL) {
printf(“File cannot be opened\n”);
Copyright © Open University Malaysia (OUM)
TOPIC 4 FILES  55

exit(1); /* end program when file fails to open */


}

The if statement in the code segment tests whether the opening of inputfile is
successful or fails by testing if fptr is equivalent to NULL or not. If fptr is
NULL, it means that the file failed to be opened. If this happens an error message
will be displayed followed by calling of the exit()function. The exit()
function is a library function to stop execution of a program. To use it, we must
use the header file stdlib.h together with the program by entering the pre-
processor command at the beginning of the program.

#include <stdlib.h>

ACTIVITY 4.1

1. Write a code segment to open an existing file, named student.txt,


for reading and writing.
2. What are the statements that need to be inserted into a program to
test if the file to be opened exists in the system or not?

4.2.2 fclose()
When we have finished operating on a file, the file needs to be closed. The
fclose() function is a function to close a file.

To call to the function to close a file is pointed to by a file pointer fptr as shown
below:

fclose(fptr);

The following program shows an example calling both the fopen() and
fclose() functions to open and close the file.

#include <stdio.h>
#include <stdlib.h>

void main (void)


{
FILE *fptr;
fptr = fopen(“datafile”, “r”);/*open file to read*/
if (fptr == NULL) {
printf(“File datafile cannot be opened\n”);
Copyright © Open University Malaysia (OUM)
56  TOPIC 4 FILES

exit(1);
}
:
:
fclose(fptr); /* file closed */
}

4.2.3 fprintf()
We can use the fprintf() function to print all types of data from a file. The
syntax to call the function is as follows:

int fprintf(fptr, output_format [, values_list])

Calls to the fprintf() function is nearly the same as calling the printf()
function. The difference with printf() is that it has an additional parameter; the
first parameter is a file pointer to some output file.

An example of using fprintf() function is shown in Example 4.1. This program


prints to an output file the values to the power of two for all numbers between 1
and 100.

Example 4.1: How to use fprintf() function.

/* Prints to the power of two numbers 1 - 100 to output file */


#include <stdio.h>
#include <stdlib.h>
void main(void)
{
FILE *fptr;
int x, power2;

fptr = fopen(“output”, “w”);


if (fptr == NULL)
{
printf(“Cannot open output file\n”);
exit(1);
}

for(x = 1; x <= 100; x++)


{
power2 = x * x; /*written to output file*/
fprintf(fptr, “%d\n”, power2);
}
Copyright © Open University Malaysia (OUM)
TOPIC 4 FILES  57

fclose(fptr);
}

Output in the file named ‘output’:


1
4
9
16
25
36
49
64
81
100

ACTIVITY 4.2

Write a program that will input three integer numbers. Calculate the
average of these numbers. Write to a file named „average.dat‰, these
three numbers and the average. Execute your program several times,
so that the data in the average.dat file is written to every time you run
your program.

4.2.4 fscanf()
The fscanf() function can be used to read many types of data from a file. The
syntax to use the function is as follows:

fscanf(fptr, format_input [, address_list]);

We will see how the fscanf() function resembles the scanf() function; the
difference is in the fscanf() first parameter which is a file pointer to some input
file.

Example 4.2 below reads data from file data1 and displays the data on the screen.
The data that is contained in the file is the matric number as well as the grade for
a group of students.

Copyright © Open University Malaysia (OUM)


58  TOPIC 4 FILES

Example 4.2: Read data from file and displays on the screen.

/* Read data from file and display it on the screen */

#include <stdio.h>
#include <stdlib.h>

void main (void)


{
FILE *fptr;
int x, total, matricno;
char gr;

fptr = fopen(“data1”, “r”);


if (fptr == NULL)
{
printf(“File data1 cannot be opened\n”);
exit(1);
}
fscanf(fptr, “%d”, &total);
for (x = 0; x < total; x++) Reading from
{ data file
fscanf(fptr, “%d %c”, &matricno,&gr);
printf(“Matric Number: %d\tGrade: %c\n”, matricno, gr);
}
fclose(fptr);
}

After the file data1 has been successfully opened, the program will read the first
data in the file which is the total number of students. Based on the number of
students, the program will loop to read the matric number and the grade for each
student. An example of the file data1 that is appropriate to the program is given
below:

File: data1
10
1101 C
1102 E
1202 A
1203 B
1302 B
1305 C
1306 D
1401 C
1402 B
1500 C
Copyright © Open University Malaysia (OUM)
TOPIC 4 FILES  59

The first line in file data1 has the total number of students, which is 10. Each line
after that has data for each student, which is the matric number, followed by the
grade. The output generated by the program for the data file is given below:

Matric Number: 1101 Grade: C


Matric Number: 1102 Grade: E
Matric Number: 1202 Grade: A
Matric Number: 1203 Grade: B
Matric Number: 1302 Grade: B
Matric Number: 1305 Grade: C
Matric Number: 1306 Grade: D
Matric Number: 1401 Grade: C
Matric Number: 1402 Grade: B
Matric Number: 1500 Grade: C

If the fscanf() function reaches the end of the file while reading, it will return
an EOF value. This value can be used as a sentinel value while reading data from
a file.

ACTIVITY 4.3

Answer the questions below based on the program segment given:


#include <stdio.h>
void main()
{
FILE *pt1, *pt2;
int a; float b; char c;
pt1 = fopen(„sample.old‰, „r‰);
pt2 = fopen(„sample.new‰, „w‰);
... // your answer starts here
fclose(pt1);
fclose(pt2);
}

1. Read the values for a, b and c from the file sample.old.


2. Request for an input from the user.
3. Write the new values for a, b and c into the file sample.new.

Copyright © Open University Malaysia (OUM)


60  TOPIC 4 FILES

ACTIVITY 4.4
Write a C program that will read lowercaseletter.txt file and write to a
new file uppercase.txt after changing each character in the file
lowercaseletter to capital letters.

SELF-CHECK 4.1

1. Assume that the program below is kept in a file atur1.c. Write the
output that will be produced by the program if the file that is
opened is the program file itself.

#include <stdio.h>
void main(void)
FILE *fptr;
char aks;
fptr = fopen(“atur1.c”, “r”)
if (fptr == NULL) {
printf(“Error opening atur1.c\n”)
exit(1);
}
while (1) {
aks = getc(fptr)
if (aks == EOF
break;
if (‘a’ <= aks && aks <= ‘z’
aks = ‘A’+(aks - ‘a’);
printf(“%c”, aks)
}
fclose(fptr)
}

2. Consider the program code below:


#include <stdio.h>
#include <stdlib.h>
void main(void)
FILE *fptr;
int length, height, num, i;
fptr = fopen(“input”, “r”);
if (fptr == NULL) {
printf(“Numbers File cannot be opened.”)
exit(1);

Copyright © Open University Malaysia (OUM)


TOPIC 4 FILES  61

}
fscanf(fptr, “%d”, &bil);
for (i=0; i < num; i++)
display(i,num);
fclose(fptr)
}
void display(int length, int height) {
int i, j
for (i=0; i < height; i++) {
for (j=0; j < height; j++
printf(“*”);
printf(“\n”);
}
}

Write the output that will be generated if the contents of input file
is as this: 3

3. Write a program that would read every positive integer number


from a file named number and then outputs the average on the
screen.

4. Modify the program in (3) so that the average output is to a file


named output.

Ć In this topic, you have learnt how to do file input and output in C. In
particular, we have learnt how to open and close files, read data from files as
well as writing to files.

Ć We have seen the usage of some library functions that are relevant which are
fopen(), fclose(), fprintf(), and fscanf().

Copyright © Open University Malaysia (OUM)


62  TOPIC 4 FILES

fclose() NULL
fopen() Pointer
fprintf()
Random
fscanf()
Sequential

Copyright © Open University Malaysia (OUM)


APPENDIX

Copyright © Open University Malaysia (OUM)


64  APPENDIX

Copyright © Open University Malaysia (OUM)


APPENDIX  65

Appendix

Integrated Development Environment (IDE) for C Language


Integrated Development Environment (IDE) is a software application with
comprehensive facilities for computer programmers and software developers
where the compiler, editor and debugger are combined together as one solution.
IDE helps to simplify the process of your programming works. You do not have
to rely on separate tools anymore and working in the Windows environment.

Nowadays, there are lots of IDEs for C programming available either as:
(a) Freeware;
(b) Open source software; or
(c) Commercial software.

The following are examples of IDEs for C programming:


(a) Eclipse C or C++ Development Toolkit (CDT);
(b) Bloodshed Dev-C++ (by Bloodsheed);
(c) Code::Blocks;
(d) NetBeans IDE;
(e) Microsoft Visual Studio Express;
(f) CodeLite;
(g) Borland C++; and
(h) Turbo C.

You may be wondering why the list contains C++. Can they run C language?
Yes! These IDEs are built to run both C and C++ languages. You just need to
know the correct way to save it before you compile and run your respective C
programs.

For this course, we are going to use Orwell Dev-C++ (by Orwell). Actually, this
IDE is a modified version from Bloodshed Dev-C++. Take a look at the following
steps on how to download, install and use Orwell Dev-C++.

(a) How to Download Orwell Dev-C++


You can download the latest version of OrwellÊs Dev-C++ from his blog at
http://orwelldevcpp.blogspot.com. Scroll down of the blog site and find
the Download section to see the options (refer to Figure 1). Choose
Copyright © Open University Malaysia (OUM)
66  APPENDIX

according your hardware specification. Basically, for modern computers


with Windows 8, you can download the 64-bit version. For the old machine,
you can download the 32-bit version. In Windows, you can check your
system properties from Control Panel > System and Security > System.
Look at the system type whether it is 32-bit or 64-bit.

Figure 1: Download section of Orwell Dev-C++


Source: http://orwelldevcpp.blogspot.com

(b) How to Install Orwell Dev-C++


After you finish downloading, you may install the software by following
the instructions given. By default, you just need to click the „Next‰ button
until it is finish and complete the full installation.

(c) How to use Orwell Dev-C++


Once installed, the application can be accessed from Windows menu. Click
and open the application to see the following interface (refer to Figure 2).

Copyright © Open University Malaysia (OUM)


APPENDIX  67

Figure 2: Interface of Orwell Dev-C++

Before you start writing a C program, click on the new file icon 1 and

choose the Source File 2 (refer to Figure 3).

Figure 3: Source file

Once the New Source File is loaded on the screen, choose menu File > Save
As⁄ as shown in Figure 4.

Copyright © Open University Malaysia (OUM)


68  APPENDIX

Figure 4: Save as

In the Save As dialogue box, make sure of the following (refer to Figure
A.5):

(i) 3 : Choose appropriate folder in your computer;

(ii) 4 : Click and choose C source files (*.c) option; and

(iii) 5 : Write the name of the file.

Copyright © Open University Malaysia (OUM)


APPENDIX  69

Figure 5: In the Save As dialogue box, a name is given to the file

When you save the file, the tab of the respective file will be renamed as

shown in the interface 6 in Figure 6. You may start writing your first C

program here 7 (refer to Figure 6). You are advised to write this main

block every time you start writing C program. By practicing this method,
you will not miss any codes especially the opening and closing braces.

Copyright © Open University Malaysia (OUM)


70  APPENDIX

Figure 6: Rename file and where to write the first C program

After you finish writing the codes, press the Compile button 8 (refer to

Figure 7) or press F9 on your keyboard to compile it.

Figure 7: Compile button

You need to see the bottom part of the Windows, whether you get any

errors or the program is compiled successfully 9 (refer to Figure 8). If

there is any error, double click on each error listed to see the respective line

Copyright © Open University Malaysia (OUM)


APPENDIX  71

of code that contains the error. Find solutions to fix it. If there is no error,
the compilation is indicated as successful.

Figure 8: Check if there is any error

10
If the program is successfully compiled, press the Run button or

11
press F10 to run and get the output of the program as shown in

Figure 9.

Figure 9: Run and get the output of the program

Copyright © Open University Malaysia (OUM)


72  APPENDIX

IDE in Linux
If you are working on the Linux platform, you can use Geany as an application to
write, compile and run C program. How to get and install it? In this tutorial, we
use Ubuntu as the most popular and easiest Linux distribution. For your
information, any Linux platforms come with pre-installed C compiler called
GNU Compiler Collection (GCC), so you do not have to worry about C compiler
anymore. Geany is an editor to be used to write C codes, but it has an ability to
compile and run C program because of the integration with GCC.

To get Geany, you can open the Ubuntu Software Center and search for Geany
(refer to Figure 10). Later, you can press the Install button and let the system
install it for you. Additional plugin called g++ also need to be installed. You just
need to search „g++‰, find and install it through the Ubuntu Software Centre.

Figure 10: Ubuntu software center


Source: www.ubuntu.com

After the installation is completed, press the Window button on the keyboard
and type „Geany‰. Click on the icon to fire up Geany (refer to Figure 11).

Copyright © Open University Malaysia (OUM)


APPENDIX  73

Figure 11: Click the icon Geany to activate it

Before you start writing codes in Geany, we need to do a little change in the
Preference menu. Kindly go to Edit > Preference menu and set the output of the
program must be shown in gnome-terminal. You just need to replace the value
inside the dialog box with „gnome-terminal‰ (refer to Figure 12).

Figure 12: Replace the value inside the dialog box with „gnome-terminal‰

Copyright © Open University Malaysia (OUM)


74  APPENDIX

Once completed, you can proceed with your programming codes as follows
(refer to Figure 13):
(a) To begin the C program, click on File > Save As⁄;
(b) Select a folder to save the file;
(c) Write the file name together with the extension of .c (for example,
HelloWorld.c); and
(d) Press the Save button.

Figure 13: Steps to start your programming codes

Then, write your program in the editor as shown in Figure 14.

After completing the codes, you can do the following necessary steps in order to
accomplish your programming tasks:

5
(a) To compile program: Press this button (refer to Figure 14);

6
(b) To run program: Press this button (refer to Figure 14); and

Copyright © Open University Malaysia (OUM)


APPENDIX  75

Figure 14: Write your program, compile and run in the editor

(c) The output displayed is shown in Figure 15.

Figure 15: Output of the program

Copyright © Open University Malaysia (OUM)


76  APPENDIX

Okay, you are done with IDE, not for Windows platform only, but also for Linux
platform. Enjoy your learning and always remember ă programming is fun!!

Copyright © Open University Malaysia (OUM)


MODULE FEEDBACK
MAKLUM BALAS MODUL

If you have any comment or feedback, you are welcome to:

1. E-mail your comment or feedback to modulefeedback@oum.edu.my

OR

2. Fill in the Print Module online evaluation form available on myINSPIRE.

Thank you.

Centre for Instructional Design and Technology


(Pusat Reka Bentuk Pengajaran dan Teknologi )
Tel No.: 03-27732578
Fax No.: 03-26978702

Copyright © Open University Malaysia (OUM)


Copyright © Open University Malaysia (OUM)

You might also like