You are on page 1of 123

Faculty of Science and Technology

CBCP2202
Computer Programming II

Copyright © Open University Malaysia (OUM)


CBCP2202
COMPUTER
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, CBCP2202


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 Statements 6
1.3 Differences Between if and switch Statements 8
1.4 Case Study 14
1.4.1 Problem Statement 14
1.4.2 Analysis 15
1.4.3 Data Requirements 16
1.4.4 Design 17
1.4.5 Implementation 19
Summary 22
Key Terms 22

Topic 2 Repetition 23
2.1 while Statement 23
2.2 do-while Statement 27
2.3 for Statement 30
2.3.1 The Relationship between for and while 34
Statements
2.4 Controlling Loops 35
2.4.1 Endless Loop 36
2.4.2 while Loop Controlled by Condition 37
2.4.3 while Loop Controlled by Sentry 39
2.5 continue Statement 40
2.6 break Statement 41
2.7 Nested Loops 42
2.7.1 Tracing Nested Loops 42
2.8 Case Study 44
2.8.1 Problem 44
2.8.2 Analysis 45
2.8.3 Design 45
Summary 49
Key Terms 50

Copyright © Open University Malaysia (OUM)


iv  TABLE OF CONTENTS

Topic 3 Functions 51
3.1 What are Functions? 52
3.2 Function Definition 53
3.3 Function Prototype 56
3.4 Function Calls 58
3.4.1 Functions without Returned Data Type and 59
without Parameters
3.4.2 Functions without Returned Data Type but 61
with Parameters
3.4.3 Functions with Returned Data Type and with 62
Parameters
3.5 Library Functions of C 64
3.6 Variable Scope 67
3.7 Recursion 75
3.8 Functions and Top Down Design 79
Summary 82
Key Terms 83

Topic 4 Files 84
4.1 File Support in C Programs 84
4.1.1 Binary File 85
4.1.2 Text File 85
4.2 File Operations 85
4.2.1 fopen() 85
4.2.2 fclose() 87
4.2.3 fprintf() 88
4.2.4 fscanf() 89
4.2.5 getc() 92
4.2.6 putc() 93
Summary 96
Key Terms 96

Appendix 97

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
CBCP2202 Computer Programming II is an advanced course and a continuation
of CBCP2101 Computer 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 Bachelor 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
section), at the end of every topic or at the back of the module. You are

Copyright © Open University Malaysia (OUM)


x  COURSE GUIDE

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


Topic X 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.

X INTRODUCTION
In Topic 2 of CBCP2101, 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 X 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;
int year;

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE W 3

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

Copyright © Open University Malaysia (OUM)


4 X TOPIC 1 SELECTION CONTROL STRUCTURE

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. */
#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:

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE W 5

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

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, 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: “);

Copyright © Open University Malaysia (OUM)


6 X TOPIC 1 SELECTION CONTROL STRUCTURE

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


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

1.2 SWITCH AND BREAK STATEMENTS


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

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE W 7

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

Copyright © Open University Malaysia (OUM)


8 X TOPIC 1 SELECTION CONTROL STRUCTURE

break;
case 2: printf(“Two”);
break;
case 3: printf(“Three”);
break;
case 4: printf(“Four”);
break;
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 W 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 X 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 W 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 X 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 W 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

1.4 CASE STUDY


Computer programs are not only used to perform boring tasks. You can also
have fun by writing computer game programs. Now that you have learnt the
basic syntax for C language, this topic will demonstrate a computer game case.
This example will show how to solve problems in stages using methods
discussed in Topic 1. Then we will write programs using the C syntax for the
selection structure.

Copyright © Open University Malaysia (OUM)


14 X TOPIC 1 SELECTION CONTROL STRUCTURE

1.4.1 Problem Statement


Have you ever played computer games before? In this topic, you will learn how
to write an easy computer game program. You would have probably played this
game when you were younger. It is called „paper, rock and scissors‰. Two
players usually play the game. Every player uses their hand to represent one of
the three objects. Holding out their palms at a horizontal level represents
„paper‰, making a fist is a „rock‰ and putting up two fingers is „scissors‰.
Players will sit facing each other and count „one, two, three!‰ At the count of
three, both players will show their choice of object. If their choices are the same,
then the result is a tie. If not, the result will be based on:
• Paper hides rock (Paper wins)
• Rock breaks scissors (Rock wins)
• Scissors cuts paper (Scissors wins)

Figure 1.1: Symbols used for computer games

1.4.2 Analysis
To simulate this game, we will write a program that will allow a user (player 1) to
play with a computer (player 2). Both players can choose an integer 0, 1 or 2 that
will each represent paper, rock and scissors.

Table 1.2: Number Representation

Representation Number

Paper 0
Rock 1
Scissors 2

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE W 15

To enable the computer to choose a number at random between 0 and 2, we need


to use the rand() function. This function returns a random integer number that
can have a value between 0 and RAND_MAX, usually 32767. This value depends
on the computer system where the program is executed. By using only the
rand() function, we might get a large number. To ensure that the number is
between 0 and 2, we need to use the following formula:

Random number = rand() % 3

As an example, let us say rand() returns 1694. The expression value (rand()
% 3) is 2. To ensure the rand() function creates a different number every time
the program is executed, we would use the following function call:

srand(time(NULL));

The time (NULL) function returns seconds calculation that has been lapsed since
1 January 1970 (UNIX systems date of birth). By passing this integer second
calculation (it will surely be different each time the time(NULL) function is called)
to the srand()function, will determine where the rand() function starts. Thus, the
value returned by the rand()function will always be different. Both the
rand()and srand() function prototypes is in the file stdlib.h whereas the
time()function prototype is in the time.h file. As a result, we need to insert the
preprocessor instruction #include <stdlib.h> and #include <time.h> in
the program. It is easier to decide the winner if we build the table below:

Copyright © Open University Malaysia (OUM)


16 X TOPIC 1 SELECTION CONTROL STRUCTURE

Table 1.3: Determining the Winner

P Computer
l
0 1 2
a Legend:
0 T P C T = Tie
y
1 C T P P = Player wins
e C = Computer wins
r 2 P C T

T shows a tie result that will be obtained when the choices of the Player and the
Computer are the same. P shows the combination of choices by the Player and the
Computer that ends with the Player winning. T shows the combination of choices
by the Player and the Computer that ends with the Computer winning. Therefore,
we have seven conditions to show the game results message that is to be printed.

1.4.3 Data Requirements


As usual, we need to identify the input and output. In this example, the input
and output are as follows:

Input

int player; /* player-1’s choice (user) */

Output

Player and computer’s choices


Results – “Tie”, “You (user) have won”, or “You lose”

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE W 17

1.4.4 Design

Initial Algorithm

Our initial algorithm is as follows:

1. Start.
2. Display introductory message and instruction.
3. Input player choice as integer value.
4. Generate computer choice as integer value.
5. Do comparison to display player and computer choice in
text form.
6. Do comparison to determine the winner based on the player
and the computer choices and display the result.
7. End.

Steps 1, 2, 3 and 7 are simple and do not need any details. On the other hand,
steps 4, 5, and 6 need more details. Let us see the detailed steps as follows:

(a) Detailed Step 4


4. Generate computer choice as integer value.
4.1 Call srand(time(NULL)) function to ensure the number
generated is always different.
4.2 Computer = rand() % 3
(b) Detailed Step 5
5. Do a comparison to display player and computer choice in text form.
5.1 Display title “YOUR CHOICE COMPUTER RESULT”.
5.2 IF (player == 0) start_if_1
5.2.1 Display “PAPER”.
end_if_1
if_else if (player == 1) start_if_2
5.2.2 Display “ROCK”.
end_if_2
if_else if (player == 2) start_if_3
5.2.3 Display “SCISSORS”.
end_if_3
5.3 if(computer == 0) start_if_1
5.3.1 Display “PAPER”.

Copyright © Open University Malaysia (OUM)


18 X TOPIC 1 SELECTION CONTROL STRUCTURE

end_if_1
if_else if (computer == 1) start_if_2
5.3.2 Display “ROCK”.
end_if_2
if_else if (computer == 2) start_if_3
5.3.3 Display “SCISSORS”.
end_if_3

(c) Detailed Step 6


To do this detail, we can refer to Table 10.1.
6. Do a comparison to determine the winner based on the player and
computer choices.
6.1 if (player == computer) start_if_1
6.1.1 Display “TIE”.

end_if_1
if_else if ( ((player == 0) && (computer ==
1))|| ((player == 1) && (computer == 2)) ||(player
== 2) && (computer == 0))) start_if_2
6.1.2 Display “YOU WIN!”.
end_if_2
if_else if ( ((computer == 0) && (player ==
1)) || ((computer == 1) && (player ==
2))||((computer == 2) && (player == 0)))
start_if_3

6.1.3 Display “YOU LOSE!”.


end_if_3

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE W 19

1.4.5 Implementation

Program 1.4
/* Paper, Rock and Scissors Game Program */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main(){
int player, computer;
printf(“\n%s\n”, “***PAPER, ROCK, SCISSORS***\n In this
game you are given three choices:\n”);
printf(“Input your choice: “);
scanf(“%d”, &player);
srand(time(NULL));
computer = rand() % 3;
printf(“\n%15s %15s %15s\n”, “YOUR CHOICE”, “COMPUTER”,
“RESULT”);
printf(“%15s %15s %15s\n”, “===========”, “=========”,
=========”);
switch (player){
case 0: printf(“%15s “, “PAPER”);
break;
case 1: printf(“%15s “, “ROCK”);
break;
case 2: printf(“%15s “, “SCISSORS”);
break;
}
switch (computer){
case 0: printf(“%15s “, “PAPER”);
break;
case 1: printf(“%15s “, “ROCK”);
break;
case 2: printf(“%15s “, “SCISSORS”);
break;
}
if (player == computer)
printf(“%15s\n”, “DRAW”);
else if ( ((player == 0) && (computer == 1)) ||
((player == 1) && (computer == 2)) ||
((player == 2) && (computer == 0)) )
printf(“%15s\n”, “YOU WIN!”);

Copyright © Open University Malaysia (OUM)


20 X TOPIC 1 SELECTION CONTROL STRUCTURE

else if ( ((computer == 0) && (player == 1)) ||


((computer == 1) && (player == 2)) ||
((computer == 2) && (player == 0)) )
printf(“%15s\n”, “YOU LOSE!”);
}

The program interacts as follows:

***PAPER, ROCK, SCISSORS***


In this game you are given three choices:
0 is paper
1 is rock
2 is scissors.

Input your choice: 2

YOUR CHOICE COMPUTER RESULT


=============== =============== ==============
SCISSORS ROCK YOU LOSE!

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

Copyright © Open University Malaysia (OUM)


TOPIC 1 SELECTION CONTROL STRUCTURE W 21

Try Self-Check 1.4 to reinforce your understanding.

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)


22 X 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)


Topic X 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.

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

Copyright © Open University Malaysia (OUM)


24 X TOPIC 2 REPETITION

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.

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

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION W 25

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. As 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++;
}
printf(“Total of numbers from 1 to %d is %d.\n”, num,
total);
}
Copyright © Open University Malaysia (OUM)
26 X TOPIC 2 REPETITION

Output:

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

ACTIVITY 2.1
(a) Write a program that will display even numbers from 2 to 20.
(b) 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 W 27

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)


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

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION W 29

total += num;
} 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

(a) What is the minimum number of times a while loop will be


executed? What about do-while loop?
(b) 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)


30 X 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.

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION W 31

Figure 2.3: The for statement

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.

Copyright © Open University Malaysia (OUM)


32 X TOPIC 2 REPETITION

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 examples 2.1, 2.3 and 2.5, the outputs are the same, only
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
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.

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION W 33

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 belowusing for,
do-while or while loop:
*****
***
*

Copyright © Open University Malaysia (OUM)


34 X TOPIC 2 REPETITION

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)


TOPIC 2 REPETITION W 35

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

Copyright © Open University Malaysia (OUM)


36 X TOPIC 2 REPETITION

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.

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.

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION W 37

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

Copyright © Open University Malaysia (OUM)


38 X TOPIC 2 REPETITION

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

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

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION W 39

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.

(i) Sentry value is the value that is out of the boundary of valid data.
(ii) 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.

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?

Copyright © Open University Malaysia (OUM)


40 X TOPIC 2 REPETITION

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

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

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

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION W 41

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

Copyright © Open University Malaysia (OUM)


42 X TOPIC 2 REPETITION

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!

2.7 NESTED LOOPS


Nested loops refer to the looping statement where the body has a looping
statement. As an example, a for statement can have a body with a while loop.
In the following section, we will see the execution flow of a nested loop as well as
an example of its usage.

2.7.1 Tracing Nested Loops


Consider the code segment below:

for (i = 0; i < 2; i++) { A


for (j = 0; j < 5; j++) {
printf("%d, %d\t", i, j);
} B
printf(“\n”);
}

Notice that the code segment has two for statements that are marked as A and
B. Statement B is part of the statement that is in the body of statement A. From
the heading of statement A, we know that the statement execution is done twice.
The same as statement B, the body will repeat five times.

As looping statement B is nested in looping statement A, statement B will loop


five times for every loop of A.

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION W 43

The output generated is as follows:

0,0 0,1 0,2 0,3 0,4


1,0 1,1 1,2 1,3 1,4

Example 2.9: Calculating the average of a set of data.


Let us say we wish to write a program that is able to calculate the average of a
few integer numbers. For each set of numbers, the program will input its data,
calculate the average and then output the calculated value. Program 2.3 shows
how this can be done using the nested loops.

Program 2.3

/* Calculating average for every input line */


#include <stdio.h>
void main() {
int numSet, numData, tot, x, y, data;
float p;
printf("How many data sets? "); A Repeat for
scanf("%d", &numSet); every data set
for (x = 1; x <= numSet; x++) {
printf("How many data in set %d? ", )
scanf("%d", & numData);
tot = 0;
B
for (y = 1; y <= numData; y++) {
printf("Input data %d: ", y); Read each
scanf("%d", &data); data for
tot += data; current set
} data and
update
p = (float) tot / numData;
totals
printf("Set average %d = %.2f\n", x, p);
}
}

There are two for statements that are involved and are marked A and B.
Statement A will repeat its execution of body for every number set that needs
processing. For every repetition, the following items will be executed for every
number set:
(i) Input how many numbers will be input for that set.

Copyright © Open University Malaysia (OUM)


44 X TOPIC 2 REPETITION

(ii) Input every number in that set and at the same time update its totals.
(iii) Calculate the average for that set.
(iv) Output the average for that set.

Execution of step (ii) would surely need looping because for every set, the
numbers would be input one at a time.

SELF-CHECK 2.5

1. What is the output generated by the code segment below if the


data input is 5?

scanf(“%d”, &data);
for (row=1; row <= data; row++) {
for (col=1; col <= row; col++)
printf(“%d”, col);
printf(“\n”));
}

2. Write a program that will display a rectangle whose width and


height are inputted by the user. Below is an example of the
program execution.

Enter rectangle width: 6


Enter rectangle height: 5
******
******
******
******
******

2.8 CASE STUDY


Let us now go through this case study.

2.8.1 Problem
Many programs need input from users. Examples of programs that we have seen
so far will display a message when some data have been inputted. This message
will give the users an indication about the type or choice of input needed by the
program.

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION W 45

One technique of interaction between a program and its user is using the menu.
The menu is a list of items that can be selected by the user. Once the menu is
displayed, the program will wait for the user to input his or her choice. After the
user has chosen the item, the program will continue processing based on that
item.

In this section, we will develop a program that will do these conversions:


• Convert time from minutes to hours;
• Convert distance from feet to metres; and
• Convert temperature from Fahrenheit to Celsius.

The program will display a menu to get the type of conversion required. Once
that is done, it will ask the user for the input to be converted, do the calculation
and then display the result. After that, the program will display the menu again
and the process will continue until the user decides to stop the program.

2.8.2 Analysis
The following formula is used to do the conversions:

1 hour = 60 minutes
1 foot = 0.3048 metres
1 Celsius = (5/9) * (Fahrenheit ă 32)

2.8.3 Design
The menu to be displayed by the program is based on the selection listed in Table
14.1:

Table 2.1: Menu

Choice Code Conversion Type


1 Minutes to hours
2 Feet to metres
3 Fahrenheit to Celsius
0 Program ends

Copyright © Open University Malaysia (OUM)


46 X TOPIC 2 REPETITION

Users choose the type of conversion by entering the corresponding code. If the
user enters a 0, the program ends. If the user enters any value other than the code
numbers in Table 2.1 above, it will be ignored. The program will re-display the
menu and the user has to choose again.

An explanation on the algorithms that will be implemented is given in Table 2.2.


These variables will be used in the algorithm.

Table 2.2: Variables

Variable Explanation
Choice Users choice from the menu
Minutes Value of minutes input by the user
Hours Keeps the converted value from minutes to hours
Feet Value of feet input by the user
Metres Keeps the converted value from feet to metres
Fahrenheit Value of Fahrenheit input by the user
Celsius Keeps converted value from Fahrenheit to Celsius

The following is a beginning algorithm for our solution:

1. Start
2. Do
2.1 Choose conversion type
2.2 IF (1 <= choice and choice <= 3) Start_IF
a. Do the conversion and display the result
End_IF
End_DO (choice != 4)
3. End

Notice how the second step involves a loop to repeat Steps 2.1 and 2.2 until the
user chooses to stop the program when the choice value is 4.

Copyright © Open University Malaysia (OUM)


TOPIC 2 REPETITION W 47

(a) Refining Step 2.1


In Step 2.1, the program will display the menu selection and continues to
wait for the user to enter his or her choice.

2.1.1 Display menu


2.1.2 Input choice from user

(b) Refining Step 2.2


Step 2.2 involves calculation that will do the conversion and then display
the results. The calculation that is carried out depends on the type of
conversion specified by the user in Step 2.1.2.

2.2a.1 If (choice == 1) start if


a. Do time conversion
b. Display hours and minutes
end if
2.2a.2 If else if (choice == 2) start if
a. Do distance conversion
b. Display feet and metres
end if
2.2a.3 If else if (choice == 3) start if
a. Do temperature conversion
b. Display Fahrenheit and Celsius
end if

(c) Refining Step 2.2a. 1a


Step 2.2a. 1a involves calculation to convert time. The calculation is carried
out after the program receives input from the user.

2.2a.1a. (i) input minutes


(ii) calculate hours

(d) Refining Step 2.2a. 2a


Step 2.2a. 2a involves calculation for distance conversion. The calculation is
carried out after the program receives input from the user.

2.2a.2a. (i) input feet


(ii) calculate metres

Copyright © Open University Malaysia (OUM)


48 X TOPIC 2 REPETITION

(e) Refining Step 2.2a. 3a


Step 2.2a. 3a involves calculation for temperature conversion. The
calculation is carried out after the program receives input from the user.

2.2a.3a. (i) input fahrenheit


(ii) calculate celsius

2.8.4 Implementation
Program 2.4 below is an example of a program to implement the design above.

Program 2.4

/* Program to convert time, distance and temperature */


#include <stdio.h>

void main(void) {
int choice;
int min; /* minutes */
float hr; /* hours */
float ft; /* feet */
float mtr; /* metres */
float fahr; /* fahrenheit */
float celc; /* celsius */

do {
/* display menu */
printf(“\n\t\tCONVERTER\n”);
printf(“\t\t==================\n”);
printf(“\t1. Time: minutes to hours\n”); printf(“\t2.
Distance: feet to metres\n”);
printf(“\t3.Temperature: Fahrenheit to Celsius\n”);
printf(“\t4. Program End\n”);
printf(“\tYour Choice: “);
scanf(“%d”, &choice);
if (1 <= choice && choice <= 3) {
switch (choice) {
case 1 :
printf(“Time in minutes: “);
scanf(“%d”, &min);
hr = (float) min / 60;
printf(“%d minutes = %.2f hours\n”,min,hr);
break;
case 2 :
Copyright © Open University Malaysia (OUM)
TOPIC 2 REPETITION W 49

printf(“Distance in feet: “);


scanf(“%f”, &ft);
mtr = ft * 0.3048
printf(“%.2f feet=%.4f metres\n”,ft,mtr);
break;

case 3 :
printf(“Temperature in Fahrenheit: “);
scanf(“%f”, &fahr);
celc = (5.0/9.0) * (fahr - 32);
printf(“%.2f Fahr = %.2f Celcius\n”,fahr, celc);
break;
}
}
} while (choice != 4);
}

SELF-CHECK 2.6
Modify Program 2.4 so that an error message would be displayed if
the user does not enter the correct code during menu selection.

• 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.
(a) Controlling loops can be done either through controlled condition or
controlled by sentry value. Endless loop must be avoided.
(b) Nested loops are useful in generating loop statement within another
loop statement.

Copyright © Open University Malaysia (OUM)


50 X TOPIC 2 REPETITION

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

Copyright © Open University Malaysia (OUM)


Topic X 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.

X 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:


• What are functions; and
• How we define our own functions.

Copyright © Open University Malaysia (OUM)


52 X TOPIC 3 FUNCTIONS

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:


1. Function declaration
2. Function prototype
3. 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 called
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)


TOPIC 3 FUNCTIONS W 53

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)


54 X TOPIC 3 FUNCTIONS

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)


TOPIC 3 FUNCTIONS W 55

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?

Copyright © Open University Malaysia (OUM)


56 X TOPIC 3 FUNCTIONS

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.

The main reason the function prototype is written is to prove 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.

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 57

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

Copyright © Open University Malaysia (OUM)


58 X TOPIC 3 FUNCTIONS

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

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.

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 59

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;

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

Copyright © Open University Malaysia (OUM)


60 X TOPIC 3 FUNCTIONS

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

Figure 3.2: Calling a function without parameters

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 61

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.

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

Copyright © Open University Malaysia (OUM)


62 X TOPIC 3 FUNCTIONS

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

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.

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 63

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

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.

Copyright © Open University Malaysia (OUM)


64 X TOPIC 3 FUNCTIONS

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

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

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 65

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)


66 X 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 W 67

3.6 VARIABLE SCOPE


Every variable in a program is associated with a scope. Variable scope refers to an
area where the program can reach it. There are two categories of variables:

Table 3.1: Local Variable Scope and Global Variable Scope

Category Local Variable Global Variable


Scope Inside the function body Outside the function body
Life Expectancy Throughout function Throughout program
execution execution
Reach Only in the function The entire program
Usage Encouraged Not encouraged (difficult
to control)

Look at the program below. Variable x and y defined in the main() function is a
local variable. This means that it can only be reached directly through that
function. This variable cannot be reached directly in the function f1().

Figure 3.4a: Variable x and y as a local variable

Copyright © Open University Malaysia (OUM)


68 X TOPIC 3 FUNCTIONS

Figure 3.4b: Variables x and y as global variables

The next program declares both variables x and y as global variables. Thus, it can
be reached in any of the functions in the program.
#include <stdio.h>
int x, y; /* pembolehubah sejagat */
void f1(void) {
printf(“x = %d y = %d\n”, x, y);
}
void main(void) {
printf(“Include two numbers: “);
scanf(“%d%d”, &x, &y);
f1();
}

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 69

Now, observe the next program:

Program 3.1

#include <stdio.h>
void calcSquare(float a, float b) {
/*a and b are calSquare()’s local variables*/
b = a * a;
}
void main(void) {
float x, y; /*main() function’s local variables */
x = 3;
y = 20;
calcSquare(x,y);
printf(“%1.1f square is %2.1f\n”, x, y);
}

Notice that x and y are local variables for the function main(), whereas a and b
are local variables in the calcSquare() function. When the program starts to
execute, the main()function becomes active and the local variables x and y are
created. Figure 3.5 below shows the state of the variables before calling the
calcSquare() function.

Figure 3.5: State of local variables in main() before the calcSquare()


function is called

When the function calcSquare() is called, the memory space for variables a
and b is created. After that, the values x and y are sent to the function with the
respective values copied into parameters a and b. The program control is later
transferred to the calcSquare() function. Memory space that is created when
the function is called is shown in Figure 3.6.

Copyright © Open University Malaysia (OUM)


70 X TOPIC 3 FUNCTIONS

Figure 3.6: Memory states when the calcSquare() function is called

Let us look at the box above that represents the memory area for the entire
program. The box labelled as main shows the memory area for the function
main(). The memory of local variables for the function x and y are created from
this memory area.

Two small boxes labelled x and y represent memory for both the variables. Just
like the main() function, a labelled box represents memory space for the
calcSquare() function. Two small boxes labelled a and b in the box represent
memory area for local variables which are parameters a and b. Notice that the
values of a and b each represent values x and y. This is because of parameter
passing that happens when the function calcSquare() is called.

Next, the statement in the calcSquare() function body is executed that makes
the value of the expression a * a is assigned to b. The result, value of b is now
9, as shown in Figure 3.7.

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 71

Figure 3.7: Memory area after the execution of calcSquare() function

After the calcSquare() function is executed, the program control is returned


to the calling function which is the main() function. With the end of the
calcSquare() function call, it means the end of the local variables life, which is
a and b. After returning, the statement that will be executed next is the one to
output the a and b variable values. The output that is generated is as follows:

3.0 Squared is 20.0

The program output above shows that the execution of the program is not what
we had hoped. From the output, we found that the value of b did not change
after the call to calcSquare(). Even when the calcSquare() function does
the square calculation and keeps the value in b, the result of the calculation is not
assigned to y when returning from the function. This is why the value of y is still
the same before the call to the function.

We are allowed to name a local variable in a function as the same name as


another variable in another function. This is because the local variables can only
be reached by the function that has declared it; therefore, there is no confusion
when the name is used to reach a variable in a function. As an example, consider
the area variable in the following program:

Copyright © Open University Malaysia (OUM)


72 X TOPIC 3 FUNCTIONS

#include <stdio.h>
double calcSquareArea(double width, double height)
double area; /*local variable */
area = width * height;
return area;
}
double calcCircleArea(double radius) {
double area; /*local variable */
area = 22.0/7 * radius * radius;
return area;
}
void main(void) {
double radius, l, t, area; /*local variables*/
printf(“Enter width and height: “);
scanf(“%f%f”, &l, &t);
area = calcSquareAread(l, t);
printf(“Square Area: %lf”, area);
printf(“Enter radius: “);
scanf(“%f”, &radius)
area = calcCircleArea(radius);
printf(“Circle Area: %lf”, area);
}

Notice that the name area was used to name three local variables, that were
declared in the main() function, calcSquareArea() and calcCircleArea().
Similarly with the radius, it is used to name a variable in the main() function
and another variable in the calcCircleArea().

In the program code above, every reference to the variable is matched to the
variable declaration. As an example, consider the statement area = 22.0/7 *
radius * radius; in the calcCircleArea() function. Radius referred to in
the statement is to the local variable radius in the function and not the variable
radius in the main()function.

C does not allow us to declare more than one local variable with the same name.
Nevertheless, we can declare a local variable that has the same name as a global
variable.

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 73

Consider the program below:

#include <stdio.h>
int x, y; /* x and y are global variables */
void f1() {
int x;
x = 0; /* local variables */
y = 0;
}
void main(void) {
x = 10;
y = 15;
f1();
printf(“x = %d y = %d\n”, x, y);
}

In this program, two global variables are declared as x and y. Function f1()
also declares a local variable by the name x. The arrow at the statement x = 0;
in function f1() shows that the reference to x in the statement is referring to the
local variable x and not the global variable x.

With that, the value of the global variable x does not change when the function
f1() is called in the main() function. On the other hand, f1()function has
changed the local variable y to 0. The output generated by the program is as
follows:

x = 10 y = 0

ACTIVITY 3.7

Use the tracing method as in Program 14.1. What would happen in


this last example, when the value x does not change but value y does?

Copyright © Open University Malaysia (OUM)


74 X TOPIC 3 FUNCTIONS

SELF-CHECK 3.2

Write the output that is generated by the program below:

#include <stdio.h>
int A(int x) {
printf(“Value received by A(): %d\n”, x);
x = x*x;
printf(“Value returned by A(): %d\n”, x);
return x;
}
void main(void) {
int x;
x = 10;
printf(“Value of x in main() before sent to
A(): %d\n”, x);
A(x);
printf(“Value of x in main() after returning from
A():
%d\n”, x);
}

ACTIVITY 3.8

Most of the examples shown previously did not touch on function


prototype. Can you differentiate functions without prototypes and
functions with prototypes and their advantages?

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 75

3.7 RECURSION
If n is a round number, then the value of its factorial written as n! is determined
by the following formula:

1, if n = 0
n! =
n*(n-1)*...*2*1, if n > 0

The formula to calculate the factorial value for n (if n > 0) is as follows:

n! = n * (n-1) * (n-2) * ... * 1

Notice that (n-1)*(n-2)*...*1 is the value for the factorial (n-1). In other words,

n! = n * (n-1) * (n-2) * ... * 1


= n * (n-1)!

The diagram below shows the calculation of the value for factorial 4 based on the
observation above. To calculate the value of factorial 4, we would need to get the
value of factorial 3. Likewise, to calculate the value for factorial 3, we would
need to get the value of factorial 2. This continues until the value of factorial 0 is
needed to calculate factorial 1. Case 0! is a special case because the formula
above cannot be used for value of n which is equivalent to 0. For this case, the
factorial value of 0 is defined as 1.

4! = 4 * 3!
= 4 * (3 * 2!)
= 4 * (3 * (2 * 1!))
= 4 * (3 * (2 * (1 * 0!)))
= 4 * (3 * (2 * (1 * 1)))
= 4 * (3 * (2 * 1))
= 4 * (3 * 2)
= 4 * 6
= 24

Based on the above, the formula to calculate the value of a factorial for a round
number n is shown below:

Copyright © Open University Malaysia (OUM)


76 X TOPIC 3 FUNCTIONS

1, if n = 0
n! =
n*(n-1)!, if n > 0

We can write a function to calculate the value of a factorial based on this formula.
Notice the function factorial() code on the next page:

int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n-1);
}

The function definition above is an example of a recursive function because the


body of the function has a function call to itself (look at the else statement in the
code above). When we call the function to calculate the value of factorial for n
which is more than 0, it will make a series of calls to itself. This is shown in
Figure 3.8 which shows the execution of factorial(4).

Figure 3.8: Tracing of factorial (4) execution

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 77

The following Program 3.2 inputs a number between 0 and 15 and continuously
calls the function factorial() to calculate its factorial value for that number
recursively.

Program 3.2
/* Counting factorial value of n recursively */
#include <stdio.h>
void main(void) {
int n;
long int factorial(int);
printf(“Enter value n “);
scanf(“%d”, &n);
if ((n < 0) || (n > 15))
printf(“n is outside range\n”)
else
printf(“%d! = %ld\n”, n, factorial(n));
}
long int factorial(int n) {
if (n == 0)
return 1; /* stopping condition */
else
return (n * factorial(n-1));/* recursion */
}

Two things must be taken into consideration when we write recursive function
definition; both are regarding the stopping of the function. The first is there
should be a condition to stop the function. Once the condition is satisfied, the
function should not call itself. This is because as long as the function calls itself,
the execution will not end. This situation is called endless recursion. This is
shown by the following function definition:

void forever(void) {
printf(“I will not end\n”);
forever();
}

Refer to the recursive function factorial() that we saw earlier. The condition to
stop is when the value of its parameter is zero, which is n = = 0 . When this condition
is met, the function will immediately return the value 1 to its caller. The Figure 3.9
below shows the role of the condition in the execution of factorial(4).

Copyright © Open University Malaysia (OUM)


78 X TOPIC 3 FUNCTIONS

Figure 3.9: Role of condition in the execution of factorial (4)

The second is to ensure that for every call towards the recursive function, the
condition to stop has to be fulfilled at last. Consider the function printLines()
definition below:

void printLines(int i) {
if (i <= 0)
return;
else {
printf(“*”);
printLines(i-1);
}
}

This function will display recursively one line of ‘*’ whose length is determined
by its parameter. For example, if we call printLines(10), ten ‘*’ characters
will be displayed on one line.

Consider the else part which contains the call to itself. The parameter that is
passed is i-1. This means that every time the function calls itself, the parameter
passed will decrease by 1. This is so that the final call will be printLines(0)
and this will ensure that the stopping condition is fulfilled. Notice that the
stopping condition for the function is i <= 0 and not i == 0. This is to ensure
that the function will end even when the parameter received is a negative value.

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 79

ACTIVITY 3.9

What is the advantage of using recursive concept? Why is it


important?

SELF-CHECK 3.3

Write the output generated by the following program:

#include <stdio.h>
long int prod(int lgt) {
if (lgt <= 0)
return (long int) -1;
else if (lgt == 1)
return (long int) 1;
else
return 10*prod(lgt-1) + 1;
}
void main(void) {
printf(“prod(-2): %ld\n”, prod(-2));
printf(“prod(0): %ld\n”, prod(0));
printf(“prod(1): %ld\n”, prod(1));
printf(“prod(8): %ld\n”, prod(8));
}

3.8 FUNCTIONS AND TOP DOWN DESIGN


In solving complex problems, a good programmer will overcome the complex
tasks by breaking the problem into sub-problems. If the programmer cannot solve
any sub-problem at a certain level, a new sub-problem will be introduced to the
lower level. This will continue until a level where every sub-problem involved
can be solved individually. This design is called the top-down design.

As an example, consider the problem of drawing certain shapes to the screen.


Figure 3.10 shows a drawing of a stick-woman.

Copyright © Open University Malaysia (OUM)


80 X TOPIC 3 FUNCTIONS

Figure 3.10: Drawing of a stick-woman

Notice that the stick-woman is made up of an oval, a triangle and two lines
joined at an angle. Therefore, the problem of drawing a stick-woman can be
broken into three sub-problems.

Beginning Algorithm:
1. Draw Oval
2. Draw Triangle
3. Draw Two Lines Joined at an Angle

Let us say sub-problems 1 and 3 can be solved directly. To solve sub-problem 2,


we see the triangle as two lines joined at an angle but with a horizontal line.
Therefore, we break sub-problem 2 into two sub-problems at the next level as
shown below:

Refining Step 2:
2. Draw Triangle
2.1. Draw Two Lines Joined at an Angle
2.2. Draw Horizontal Line

At this level, any sub-problem introduced can be solved easily. We can build a
structure chart like the one shown in Figure 3.11 that shows the original problem
and sub-problems and the relationship between them.

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 81

Figure 3.11: Structure chart showing steps for drawing stick-woman

Functions have an important role in implementing the design above in a C


program. For every sub-problem in the structure chart above, we will write a
function definition to solve it. An example of the program that implements the
design above is given in Program 3.3. Meanwhile, Figure 3.12 shows the
functions defined in the program for every sub-problem given.

Program 3.3

/* Drawing Stick-Woman */
#include <stdio.h>

void draw_oval(void);
void draw_joinedLine(void)
void draw_horizontalLine(void);
void draw_triangle(void)
void main(void) {
draw_oval();
draw_triangle();
draw_joinedLine ();
}

void draw_oval(void) {
printf(“ ** \n”);
printf(“ * * \n”);
printf(“ * * \n”);
}

void draw_triangle(void) {
draw_joinedLine();

Copyright © Open University Malaysia (OUM)


82 X TOPIC 3 FUNCTIONS

draw_horizontalLine();
}
void draw_joinedLine(void) {
printf(“ /\\\n”);
printf(“ / \\\n”);
printf(“/ \\\n”);
}

void draw_horizontalLine(void) {
printf(“———\n”);
}

Figure 3.12: Combination of sub-problem with functions

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

Copyright © Open University Malaysia (OUM)


TOPIC 3 FUNCTIONS W 83

Definition Parameter List


Function Prototype
Library Function Recursion

Copyright © Open University Malaysia (OUM)


Topic X 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.

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

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.
Copyright © Open University Malaysia (OUM)
TOPIC 4 FILES W 85

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 and 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:

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

Copyright © Open University Malaysia (OUM)


86 X TOPIC 4 FILES

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”);
exit(1); /* end program when file fails to open */
}

Copyright © Open University Malaysia (OUM)


TOPIC 4 FILES W 87

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”);
exit(1);

Copyright © Open University Malaysia (OUM)


88 X TOPIC 4 FILES

}
:
:
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 W 89

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)


90 X 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 W 91

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)


92 X 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.

4.2.5 getc()
The getc()function can be used to read a character from a file. The prototype of
this function is as follows:

getc(FILE *ptr);

The ptr is a pointer that the file will read. The getc()function would return the
character that was read from the file. If the function returns an EOF value, this
means the end of the file has been reached.

Program 4.1 aims to show the contents of a file to the screen. It uses the getc()
function to read the next character from the file and the putchar() function is
to display the character on the screen. This process continues until the getc()
function reaches the end of the file.

Program 4.1

/* Read a text file and display the contents on the


screen */

#include <stdio.h>
#include <stdlib.h>
void main (void) {
FILE *fptr;
char nfile[20]
char letter;

printf(“File Name: “);


gets(nfile);
fptr = fopen(nfile, “r”)
if (fptr == NULL) {

printf(“File %s cannot be opened\n”, nfile);


exit(1);

Copyright © Open University Malaysia (OUM)


TOPIC 4 FILES W 93

}
do {
letter = getc(fptr);
if (letter == EOF)
break;
putchar(letter);
} while (1);
fclose(fptr);
}

4.2.6 putc()
We can use the putc() function to print a character to a file. Below is the
prototype for this function:

putc(int aks, FILE *ptr)

aks is a character that will be the output; whereas ptr is a pointer to the output file.

Program 4.2 below uses the putc()function to copy the contents of an input file
to another output file.

Program 4.2

/* Copy contents of one input file to another output


file */

#include <stdio.h>
#include <stdlib.h>
void main (void) {
FILE *f_input, *f_output
char input_name[20];
char output_name[20];
char letter;
printf(“Enter input file name: “);
gets(input_name);
f_input = fopen(input_name, “r”);
if (f_input == NULL) {
printf(“Error in opening file %s\n”,
input_name);
exit(1);

Copyright © Open University Malaysia (OUM)


94 X TOPIC 4 FILES

}
printf(“Enter output file name: “);
gets(output_name);
f_output = fopen(output_name, “w”);
if (f_output == NULL) {
printf(“Error to open file %s\n”,
output_name);
exit(1);
}
printf(“\nCopying File %s to file %s\n”,

input_name, output_name);

while ((letter = getc(f_input)) != EOF)


putc(letter, f_output);
fclose(f_input);
fclose(f_output);
}

ACTIVITY 4.5
So far, you have learnt a few instructions in this topic. Can you state the
use of each instruction listed below?

Instruction Usage
1. fopen()
2. fclose()
3. fprintf()
4. fscanf()
5. getc
6. putc

Copyright © Open University Malaysia (OUM)


TOPIC 4 FILES W 95

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);
}
fscanf(fptr, “%d”, &bil);
for (i=0; i < num; i++)
display(i,num);
fclose(fptr)
}

Copyright © Open University Malaysia (OUM)


96 X TOPIC 4 FILES

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

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

Copyright © Open University Malaysia (OUM)


APPENDIX

Copyright © Open University Malaysia (OUM)


98 X APPENDIX

Copyright © Open University Malaysia (OUM)


APPENDIX W 99

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

Choose this option to


download the 32-bit version

Choose this
option to
download
the 64-bit
version

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 W 101

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)


102 X 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 W 103

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)


104 X APPENDIX

6
7

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 W 105

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.

10

11

Figure 9: Run and get the output of the program

Copyright © Open University Malaysia (OUM)


106 X 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 W 107

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

Replace value here with


„gnome-terminal‰

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

Copyright © Open University Malaysia (OUM)


108 X 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.

1
3

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 W 109

5 6

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)


110 X 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