You are on page 1of 145

Faculty of Science and Technology

CBCP2101
Computer Programming I

Copyright © Open University Malaysia (OUM)


CBCP2101
COMPUTER
PROGRAMMING I
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: Dr Nantha Kumar Subramaniam


Yuzery Yusoff
Open University Malaysia

Kalaivani K. Radakrishnan

Developed by: Centre for Instructional Design and Technology


Open University Malaysia

First Edition, April 2014 (rs)


Copyright © Open University Malaysia (OUM), April 2014, CBCP2101
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 ix-xiii

Topic 1 Introduction to Programming 1


1.1 Introduction and Definitions 2
1.2 Program Development Process 2
1.2.1 Problem-solving Phase 3
1.2.2 Implementation Phase 5
Summary 6
Key Terms 6

Topic 2 Algorithm 7
2.1 Algorithms Representation 8
2.1.1 Flow Chart Representation 8
2.1.2 Pseudo-code Representation 10
2.2 Algorithm Development Method 11
2.2.1 Identify Input and Output of Problems 12
2.2.2 Identifying Sub-problems 14
2.2.3 Solving Sub-problems 14
2.3 Selection Structure 16
2.3.1 Single Selection 16
2.3.2 Dual Selection 20
2.3.3 Multi-selection 25
2.4 Repetition Structure 29
2.4.1 Counter Controlled Loop 30
2.4.2 Condition Controlled Loop 34
2.4.3 Sentry Controlled Loop 37
2.4.4 Structuring 39
2.5 Case Study 1 41
2.6 Case Study 2 43
Summary 49
Key Terms 50

Copyright © Open University Malaysia (OUM)


iv TABLE OF CONTENTS

Topic 3 Programming Language 51


3.1 Programming Language Types 52
3.1.1 Machine Language 52
3.1.2 Assembly Language 52
3.1.3 High-level Language 52
3.2 C Language 54
3.3 C Programming Environment 54
3.4 Sample C Program 57
Summary 59
Key Terms 60

Topic 4 Data Types and Variables 61


4.1 Cell Sizes and Qualifiers 62
4.2 Integer Data Type (int) 62
4.3 Character Data (char) 62
4.4 Real Data Type 63
4.5 Variable Naming 64
4.5.1 Rules to Name a Variable 65
4.5.2 C Reserved Words and Standard Identifiers 66
4.6 Variable Types 67
4.7 Variable Declarations 68
4.8 Variable Assignment 69
Summary 71
Key Terms 71
References 72

Topic 5 Constants 73
5.1 Integer Constant 73
5.2 Real Constants 74
5.3 Character Constant 76
5.4 String Constant 77
5.5 Symbolic Constant 78
Summary 80
Key Terms 80

Topic 6 Input and Output 81


6.1 printf() Function 82
6.1.1 Printing Strings 82
6.1.2 Printing Values 84
6.2 scanf() Function 88
6.2.1 Variable Input 88
Summary 91
Key Terms 91

Copyright © Open University Malaysia (OUM)


TABLE OF CONTENTS v

Topic 7 Operators and Expressions 92


7.1 Basic Arithmetic Operators 92
7.2 Arithmetic Expressions 96
7.2.1 Precedence Level 97
7.2.2 Writing Arithmetic Expressions in C 98
7.3 Assignment Statement (=) 99
7.3.1 Expression Assignment Statement 99
7.3.2 Multiple Expression Assignment Statement 100
7.3.3 Compound Assignment Statement 102
7.4 Relational Operator 104
7.5 Logical Operator 105
7.6 Increment And Decrement Operators 107
7.7 Cast Operator 109
7.8 Conditional Operator 110
Summary 113
Key Terms 113

Appendix 115

Copyright © Open University Malaysia (OUM)


!
vi TABLE OF CONTENTS

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
CBCP2101 Computer Programming I is one of the courses offered by Faculty of
Information Technology and Multimedia Communication at Open University
Malaysia (OUM). This course is worth 1 credit hour and should be covered over
eight to 15 weeks.

COURSE AUDIENCE
This course is offered to all learners taking the Bachelor of Information
Technology programme. This course is crucial for them to understand the initial
phases of programming, including problem analysis, data requirements, and
designing algorithms. Learners are expected to gain knowledge, enhance their
skills and experiences in problem-solving and familiarise themselves with syntax
and commands of programming codes, while writing simple programs.

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 ensure that you have the right course materials, understand
the course requirements, as well as know 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 one-credit hour course, you are expected to spend 40
study hours. Table 1 gives an estimation of how the 40 study hours could be
accumulated.

Copyright © Open University Malaysia (OUM)


x COURSE GUIDE

Table 1: Estimation of Time Accumulation of Study Hours

Study
Study Activities
Hours
Understanding course content and initial discussions 1
Read three units and complete exercises given at a rate of 20 hours per unit 20
Attend 5 tutorial sessions at a rate of 2 hours per session 8
Access to Websites 4
Complete one assignment at a rate of 15 hours per assignment 3
Revision 4
TOTAL STUDY HOURS 40

COURSE OUTCOMES
By the end of this course, you should be able to:

1.! Analyse programming problems and determine the requirements needed to


solve the problems; and

2.! Design algorithms to be used in the implementation phase of programming.

COURSE SYNOPSIS
This course is divided into seven topics. The synopsis for each topic is presented
below:

Topic 1 explains the concepts of program and programming and how


programming can be done in certain phases, for example: the problem-solving
phase and implementation phase.

Topic 2 covers the topic of algorithms, where learners will be required to


understand how to represent algorithms in correct ways. They will also be
exposed to the right technique in creating algorithms for sequence, selection and
repetition structures of programming.

Topic 3 introduces learners to three levels of programming and to C language. By


the end of the topic, learners should be able to understand the development
environment for C language and construct their first C program.

Copyright © Open University Malaysia (OUM)


COURSE GUIDE xi

Topic 4 explains the concept of data types and variables, in programming.

Topic 5 describes several constant values for programming, such as integer, real,
character and string.

Topic 6 discusses the concept and practices of input and output in programming.

Topic 7 explains the usage of operators and expressions in programming.

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.

Copyright © Open University Malaysia (OUM)


xii COURSE GUIDE

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
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 of the subject matter is not required for learners who follow
this module. However, programming knowledge and skills will be an advantage.

ASSESSMENT METHOD
Please refer to myINSPIRE.

REFERENCES
Marini Abu Bakar, Norleyza Jailani & Sufian Idris. (2002). Pengaturcaraan C.
Kuala Lumpur: Prentice Hall.

Copyright © Open University Malaysia (OUM)


COURSE GUIDE xiii

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)


!
xiv COURSE GUIDE

Copyright © Open University Malaysia (OUM)


Topic Introduction to
1 Programming

LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Define computer program and programming; and
2. List the six steps involved in the program development process.

INTRODUCTION
Since its introduction, computers have helped tremendously to make everyday
human tasks easier. With the help of a computer, we can pay bills, perform
banking transactions and even shop from home. Businesses depend on
computers for seamless operations. More and more students are also learning
with computers at schools. Imagine a life without computers!

Apart from computers themselves, of equal importance is computer


programming. Programming is a list of instructions followed by a computer.
Without it, a computer will not be able to function. Programming languages
allow us to write these programs and therefore, communicate with the computer.

This topic will discuss programming concepts and the processes involved in
developing a program.

ACTIVITY 1.1

Before we proceed further, state what you know about programming.

Copyright © Open University Malaysia (OUM)


2 TOPIC 1 INTRODUCTION TO PROGRAMMING

1.1 INTRODUCTION AND DEFINITIONS


As we know, human behaviour and thoughts are always based on a logical
sequence. These behaviours and thoughts happen automatically without us
realising them. Let us take a look at one of our daily actions. To turn on the tap,
the following sequence is needed:

(a) Lift hand to hold the tap head; then


(b) Rotate the tap head anti clock-wise (from right to left).

Being aware of the sequence of things is important in human life. The sequence is
achieved through a process called programming. In our daily routine, we often
have to do the same tasks repeatedly. This may make us feel bored or to lose
interest, resulting in the task not being completed properly or completed with
errors. Programs prevent human beings from having to do repetitive tasks.

In the language of programming language, programming is defined as planning,


scheduling and/or performing a task/event. It configures a computer to perform
a particular task or various tasks that is/are required.

Computer programming is a process to plan a set of sequential instructions


to be run by a computer.

Whereas,

A computer program, is a sequential instruction which determines the steps


to be taken by a computer.

1.2 PROGRAM DEVELOPMENT PROCESS


To simplify program development, we can divide the programming process into
two phases:

(a) The problem-solving phase; and


(b) The implementation phase.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO PROGRAMMING 3

Each of these phases is divided into several parts. Refer to Figure 1.1 to learn
about the relationship between these two phases.

Figure 1.1: Programming process

Now, let us look at the two phases in detail.

1.2.1 Problem-solving Phase


There are three steps that must be taken to solve any problem, which are:

(a) To perform a problem analysis;


(b) Get a general algorithm design; and
(c) Walkthrough the algorithm.

We will discuss in detail how these three steps are carried out.

Copyright © Open University Malaysia (OUM)


4 TOPIC 1 INTRODUCTION TO PROGRAMMING

(a) Analysis
Analysis is the process of understanding and defining a problem. At this
stage, a programmer should try to state the problem clearly and
understand what needs to be done to solve the problem. We may need to
know additional detailed information from the people who have identified
the problem.

During analysis, ensure that you understand and define the problem
accurately.

(b) General Design (Algorithm)


Algorithm is a set of logical sequential steps used to solve a problem.

The process of creating an algorithm is called the problem-solving design


process. Normally, writing an algorithm is the most challenging part in the
problem-solving process.

Most computer algorithms have at least three sub-problems, as stated


below:
(i) Data collection;
(ii) Process calculations; and
(iii) Output results.

Once the sub-problem is identified, we can solve each sub-problem, one at


a time.

(c) Walkthrough
Walkthrough is one of the steps in algorithm design that is often forgotten.

To walkthrough an algorithm, we must perform each step of the algorithm


just as it would be done by the computer, to see if the algorithm really does
solve the problem. This process is called tracing the algorithm. To perform
this step, we must create an input sample for the algorithm and check it
step by step. This is the time to find errors and to correct them.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO PROGRAMMING 5

1.2.2 Implementation Phase


The implementation phase also consists of three steps which are:

Detailed problem-solving in the form of program code;

Carrying out tests on the program code; and

Maintaining the program code.

(a) Detailed Design (Program Code)


The algorithm implementation process involves writing a program code.
We need to interpret each algorithm step into one or more statements in
programming language.

(b) Testing
Testing a program code is the process of running a program and checking it
for errors. This is to ensure the program does what it is intended to do.
Normally, testing is carried out by running the program code repeatedly
using a set of different data, to ensure it functions properly for every
situation. Large input size that cannot be tested manually has to be tested
now. If an error is found, the program needs to be modified until it
produces the right output or answer.

(c) Maintenance
Maintaining and updating a program code involves tasks in modifying the
program code, to eliminate errors that were not found before, and to
update it according to current changes in the organisationÊs rules and
policies.

Usually, maintenance work is carried out every five years and the
programmer who developed the program might have left the organisation
by then. Therefore, it is important for a programmer to write programs that
are easy to read, understand and maintain. Thus, we must adhere to
programming styles that are accepted by the programming society.

We have so far discussed all the processes involved in the problem-solving


phase as well as the implementation phase. If there are still points you find
unclear, you may wish to go through the text again.

To check your understanding, answer the following questions.

Copyright © Open University Malaysia (OUM)


6 TOPIC 1 INTRODUCTION TO PROGRAMMING

SELF-CHECK 1.1

1. What is a program?

2. At which phase is the algorithm created?

3. At which phase is the written algorithm translated into a


computer program?

4. The programming process is divided into two. State the processes


that are involved in each.

Computer programming is a process to plan a set of sequential instructions


to be run by a computer.

A computer program is a sequential instruction which determines the steps


to be taken by a computer.

To simplify program development, we can divide the programming process


into two phases: the problem-solving phase and the implementation phase.

There are three steps that must be taken to solve any problem, which are: to
perform a problem analysis, get a general algorithm design and
walkthrough the algorithm.

The implementation phase also consists of three steps which are: detailed
problem-solving in the form of program code, carrying out tests on the
program code and maintaining the program code.

Algorithm Computer programming


Computer program Walkthrough

Copyright © Open University Malaysia (OUM)


Topic Algorithm
2
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Solve problems by using two algorithm representative techniques;
2. Test the algorithm execution process with step-by-step detailing; and
3. Build an algorithm.

INTRODUCTION
Topic 1 introduced two main phases in developing a program. One of which was
the problem-solving phase, which involves the use of algorithms. In this topic,
we will focus entirely on algorithms, from the aspect of representation up to its
implementation. (From a historical point of view, it was the famous
mathematician Alkhwarizmi (Algorithm) who first introduced the concept of
algorithms.)

In programming, algorithm is a very important process.

Algorithm is a step-by-step problem-solving method in a limited time.

This means that the steps will lead to an end or stop. At every step, the
subsequent action should uniquely be determined by the instructions and data
obtained at that time.

Copyright © Open University Malaysia (OUM)


8 TOPIC 2 ALGORITHM

2.1 ALGORITHMS REPRESENTATION


Algorithms can be conceptual or abstract. Therefore, we need a way to represent
it so that it can be presented to humans and computers. There are two algorithm
representations that will be discussed here, which are the flow chart
representation and the pseudo-code representation.

2.1.1 Flow Chart Representation


Let us have a look at the first algorithm representation, the flow chart. Activities
in the algorithm representation are represented by geometry nodes. Each node
represents a different activity. These nodes will be connected to one another
using arrows that demonstrate the flow or a sequential activity. Below are some
symbols that are used in a flow chart representation.

Figure 2.1: Symbols in a flow chart representation

In order to represent algorithms by using flow charts, we can use the following
as a guide:

(a) Identify the symbol used, according to its function.


(b) Get the right formula.
(c) Make sure that appropriate data is used.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 9

(d) Test the flow chart by tracing each symbol, comparing it with the expected
output.

Based on the guide given above, let us examine the flow chart on starting a car
engine, as shown in Figure 2.2.

Figure 2.2: Flow chart on the process of starting a car engine

ACTIVITY 2.1

Sketch a flow chart for the process of going for a tutorial session.

Copyright © Open University Malaysia (OUM)


10 TOPIC 2 ALGORITHM

2.1.2 Pseudo-code Representation


Pseudo-code is another technique of representing algorithms.

Pseudo-code or false codes are instructions that mimic the program code
(actual program instructions).

Whilst flow charts use diagrams, pseudo-codes are written using phrases or
words. To represent algorithms by using pseudo-codes, we need to follow the
rules of writing pseudo-codes as follows:

(a) Every step in an algorithm should not have more than two actions.

(b) Steps in an algorithm are executed in sequence.

(c) The word End or Stop is used to show that the process has ended.

(d) The action that is allowed includes declaring variable names to identify the
set of variables that have a corresponding data type. Types of data might be
in the form of integer, real, character or others.

(e) To give an initial value to a variable (if applicable).

(f) To use arithmetic symbols to state the addition, subtraction, multiplication


and division operations, as well as brackets to show operation priority.

(g) A <--- B represents assigning the value of variable B to A.

(h) The relational operators below are used to state the relationship between
two values:
(i) < Less than
(ii) <= Less than or equals to
(iii) > More than
(iv) >= More than or equals to
(v) ! = Not equal
(vi) == Equal

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 11

(i) The use of sentences is allowed, if it states the meaning accurately.

(j) Read/Input/Get shows the data given to the algorithm as input.

(k) Print/Report/Write/Output/Display shows the result obtained by the


algorithm.

Example 2.1
Change lb unit to kg.

The pseudo-code is:


1.0 Start.
2.0 Read lb_weight
3.0 kg_weight = lb_weight * 2.5
4.0 Print kg_weight
5.0 End

To test your understanding of the concept, work on the following activity:

SELF-CHECK 2.1

1. Write a pseudo-code to calculate your total savings, after getting a


dividend of 12%.

2. You have been introduced to two techniques of algorithm


representation. Which do you think is more effective? Why?

2.2 ALGORITHM DEVELOPMENT METHOD


In order to build an algorithm, we need to first develop our skills through lots of
practice. There are several general strategies in the process of problem-solving
that can help us build algorithms. The divide and conquer method is one of the
most useful approaches. By using this method, the original problem can be
broken into several sub-problems (divide). Each sub-problem can then be solved
(conquered).

Copyright © Open University Malaysia (OUM)


12 TOPIC 2 ALGORITHM

Below is a guide that we can follow when building algorithms:

(a) Identify the input and output of a problem.

(b) Identify and list the sub-problems. Each problem must be solved, in order
to get the results needed.
(c) For every sub-problem, identify and list the steps that must be taken to
solve it.

Next, we will see how each step is executed.

2.2.1 Identify Input and Output of Problems


To solve a problem, we must first understand it. We would need to identify the
input and output of the problem. The process of problem-solving is usually made
up of three levels, which are: to get input, to do processing on the input and to
display the output or the results obtained. This process is shown in Figure 2.3.

Figure 2.3: Problem-solving process

Input is all the information that is relevant or needed, to execute a process.


Usually the information of the input is inserted in the problem statement given.

Output is the result that is needed. The format of how the output is to be
displayed, has also to be identified, during the construction of the algorithm. One
of the most common format used for displaying output information are tables.
Below is the input and output that have been identified in some problems.

Example 2.2
Determine whether a given year is a leap year or not.

Input: A year
Output: Message „Leap Year‰ or „Not Leap Year‰

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 13

Example 2.3
Calculate the average marks for the course TM 20200.

Input: Marks of every student


Output: Average marks

Example 2.4
Given the buying and selling price of an item, determine whether the
company made a profit, broke even or made a loss.

Input: (i) Buying price (in ringgit)


(ii) Selling price (in ringgit)

Output: Message „Profit‰ or „Break Even‰ or „Loss‰

When the input and output are known, we will need to build a list of formulae
that will relate one to the other. Based on Example 2.4, the general formula
obtained is:

Difference = Selling price Buying price


If Difference > 0, Output = „Profit‰
If Difference = 0, Output = „Break Even‰
If Difference < 0, Output = „Loss‰

Notice that we have been introduced to a variable, which is „Difference‰. It is


used to identify the relationship between the input and output. In some cases, a
few assumptions have to be made to form a relationship. The problem modelling
process, which is used by identifying variables and the relationships between
them, is called abstraction.

To test your understanding of input and output, answer the following question.

SELF-CHECK 2.2

Write a formula for Example 2.3.

Before proceeding further, take a short break, as the next section will need your
full attention.

Copyright © Open University Malaysia (OUM)


14 TOPIC 2 ALGORITHM

2.2.2 Identifying Sub-problems


Often, the problems that we get are not problems that can be solved easily. To
solve complex problems, we have to break them into smaller sub-problems first.
Each sub-problem then has to be solved, to get the results needed. Notice how
this process is done by looking at the next example.

Example 2.5
Given the name of a student, calculate the number of ÂaÊs in the name.

Solution:
The name of a student can be made up of more than one word. To count the
number of ÂaÊs in it, we need to get each letter and compare them. We need to
have a variable to act as a counter, to track the number of ÂaÊs that exist. The
letter ÂaÊ can exist in upper case or lower case. For example, in the name
„Najwa Amani‰ there are four ÂaÊs.

Initial Algorithm (Main Steps)


1. Start.
2. Input studentÊs name: studName.
3. Count the number of ÂaÊs in studName.
4. Report result.
5. End.

Step 2 and 4 can be done easily. However step 3 requires refinement. Step 3 looks
like a sub-problem that is easily solved, but if it is to be solved using a computer;
we will need to have detailed steps on how this will be done. Notice how the
refinement is done, by using the guide given next.

2.2.3 Solving Sub-problems


For every sub-problem, we need to identify and list the steps that can be taken to
solve it. This method is called refining step-by-step.

(a) Refining Step-by-step Method


We have identified five main steps in sub-topic 2.2.2. Step 3 however, needs
a detailed explanation. Refer to Figure 2.4 for an explanation of this
method.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 15

Figure 2.4: Step-by-step refinement concept

Now that you understand the refinement concept, here is the complete
explanation on algorithm, re-written for Example 2.5.

1. Start.
2. Input studentÊs name: studName.
3. Count the number of ÂaÊs in studName.
3.1 Set n = 1 and totalA = 0
3.2 Until there are characters to be read, execute the following steps.
After which, continue to step 4.
3.2.1 Read n-character
3.2.2 If n-character is the same as ÂAÊ or ÂaÊ, add 1 to totalA.
3.2.3 Increase n by 1.
4 Report „Number of ÂaÊs is totalA‰.
5. End.

Copyright © Open University Malaysia (OUM)


16 TOPIC 2 ALGORITHM

In this easy example, the number of levels refined is only up to two levels. One of
the main steps which is step 3, is refined to be step 3.1 and 3.2. Then 3.2 is further
refined into steps 3.2.1, 3.2.2 and 3.2.3. For more complex problems, the level of
refinement may increase, with each step being detailed and executable. Below are
a few guidelines in summarising the solution:

(a) At every level of refinement, the sub-problem must be understood


properly. Input/Output analysis must be done for every sub-problem, just
as it is done for the entire problem as a whole.

(b) Sub-problems that have similar processes must be looked at together. This
will prevent overlapping and arrangements can be made for modules or
sub-problems to provide an overall solution.

(c) All sub-problems can be represented in the same way. Therefore, when all
the solutions to sub-problems are combined to create the original problem,
the result from the combination is easier to understand.

2.3 SELECTION STRUCTURE


Selection structure is a structure design that gives a few choices during
execution. The choices made are dependent on the conditions that are given.
There are three types of general selection structures, which are:

(a) Single Selection;


(b) Dual Selection; and
(c) Multi-selection.

2.3.1 Single Selection


Single selection involves testing one condition only. The choice that is given
depends on whether the condition is met or not met. Below is the syntax for the
single selection algorithm.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 17

step a
If <Condition true>
Start_If
step 1
step 2
:
step k
End_If
Step k+1

If the condition is met, step 1 till step k will be executed. Then, step k + 1 is
executed. Alternatively, if the condition is not met, step k + 1 will be executed
without executing step 1 to step k.

Step 1 to step k is also known as the start_if and end_if block. Here we will see
that step k+1 will always be executed whether the condition is met or not met.
Step a which is put before the start_if and end_if block will always be executed
because the testing of the condition is after step a.

Note: Notice the indentations for steps in the block start_if end_if are indented
a little bit. This is to show that the steps are dependent on the results that are
obtained from the testing of the condition that is done.

Syntax that is given above can be pictured as a flow chart, as shown in Figure 2.5:

Figure 2.5: Single selection structure flow chart

Copyright © Open University Malaysia (OUM)


18 TOPIC 2 ALGORITHM

Let us now have a look at Example 2.6.

Example 2.6
Determine if the customers deserve to get a discount of RM10.00 from the
total payment charged. Customers will be categorised as deserving if the
total payment is RM60.00.

The algorithm is:


1.0 Start.
2.0 Input total_payment value
3.0 If (total_payment > 60)
4.0 Start_If
4.1 Minus 10 from the total_payment
5.0 End_If
6.0 Report actual total_payment
7.0 End

Note: Words that are written in italics like total_payment are variable names that
are recommended. Variables are words that can receive any type of value. You
are also free to use any other name as a variable. But it is good if the variable
name can reflect the task. As given above, total_payment refers to the total
payment that is charged to the customer.

Let us now trace the algorithm. Let us say the total_payment is RM80.00. Testing
done in step 3.0 is true because 80 > 60. Therefore, the control of the program will
enter the start_if-end_if block. This means that the total_payment will see a
deduction of 10. Then, the control of the program will exit from the block and
execute step 6.0. Therefore, the value of total_payment reported is RM70.00.

ACTIVITY 2.2

What if the total payment is RM48.00? Use the algorithm in Example 2.6
as a reference.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 19

The flow chart is:

Figure 2.6: Flow chart for Example 2.6, single selection structure

Now let us look at the second example.

Example 2.7
Determine the requirement of a student to sit for the examination based on
the number of lab sessions attended. The percentage of attendance at the lab
must be 80%. If it is less than that value, the student is categorised as not
qualified.

The algorithm is given as:


1.0 Start.
2.0 Set value no_of_labs = 10
3.0 Input value total_attended
4.0 Percentage_attended (total_attended / no_of_labs ) * 100
5.0 If ( Percentage_attended >= 80)
6.0 Start_If
6.1 Requirement „Qualified‰
7.0 End_If
8.0 Report Requirement
9.0 End

Copyright © Open University Malaysia (OUM)


20 TOPIC 2 ALGORITHM

Try to consider the algorithm above. Assume total_attended input is 8. Therefore


in step 4.0, percentage_attended will be 80 because of (8/10)*100. Testing step 5.0
is also executed, and the result is true that is percentage_attended >= 80. The
program control will enter the start_if-end_if block. After coming out of the
block, the required value is reported as „Qualified‰. Trace for total_attended at
the value of 7.

ACTIVITY 2.3

Draw a flow chart of the pseudo-code in Example 2.7.

SELF-CHECK 2.3

Re-write similar statements as those in step 4.1 in Example 2.6.

2.3.2 Dual Selection


The dual selection structure involves testing for two conditions. Choices that are
given are the same as single selection, that is, whether the condition is met or not
met. The difference is, if the condition is not met, there are some steps to be
executed. To understand it further, let us look at the general algorithm below:

If <true condition>
Start
step 1
step 2
:
step k
End_If
If_Not
Start
step k+1
step k+2
:
step n
End_If_Not
step n+1

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 21

The If < true condition > steps in, the start_if - end_if block will be executed.
Then, step n+1 will be executed ignoring the steps in the start_if_not - end_if_not
block.

However if the condition is not true or not met, the start_if_not - end_if_not
would be executed without executing the steps in the start_if - end_if. Step n+1
will still be executed whether the condition is met or not. This case is the same as
in the single selection.

A general form of a flow chart for the dual selection is shown in Figure 2.7 below.

Figure 2.7: Dual selection structure flow chart

Let us take a look at the example for a dual selection structure below:

Copyright © Open University Malaysia (OUM)


22 TOPIC 2 ALGORITHM

Example 2.8
Determine the payment that will be charged to a customer for parking their
car in a car park. The payment rate charges are, if total time parked is 2
hours or less, the payment charged is RM2.00; but if the total time parked is
more than 2 hours, then RM6.00 is charged.

The Algorithm is given as:


1.0 Start.
2.0 Input in_time
3.0 Input out_time
4.0 Total_time out_time in_time
5.0 If (Total_time< 2)
6.0 Start
6.1 Set total_payment = 2
7.0 End_If
8.0 If_Not
9.0 Start
9.1 Set total_payment = 6
10.0 End_If_Not
11.0 Report results of total_payment
12.0 End

Assume:
in_time = 9.00
out_time = 13.00
total_time = 13.00-9.00 = 4

Testing at step 5.0 will be false because 4 is larger than 2. This will cause the
control of the program to execute the start_if_not - end_if_not block. At the last
step, total_payment will be reported as 6. See Figure 2.8 for the example above.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 23

Figure 2.8: Flow chart for Example 2.8: Dual selection structure

ACTIVITY 2.4

Now, can you try to solve the problem by using in_time 8.00 and out_time
17.00? Use Example 2.8 as a reference.

Copyright © Open University Malaysia (OUM)


24 TOPIC 2 ALGORITHM

Another example of the dual selection instruction is shown here.

Example 2.9
Determine the payment that is charged to the customers who parked their
cars in the parking lot. The payment rates charged are RM2.00 for the first
hour and RM1.00 for each subsequent hour.

The algorithm is given as:


1.0 Start.
2.0 Input in_time
3.0 Input out_time
4.0 Total_time = out_time in_time
5.0 If (total_time<= 1)
6.0 Start_If
6.1 Set total_payment = 2
7.0 End_If
8.0 If_Not
9.0 Start
9.1 Set total_time = total_time -1
9.2 Set payment = total_time * 1
9.3 Set total_payment = payment + 2
10.0 End_If_Not
11.0 Report results of total_payment
12.0 End

In the algorithm above, if total_time > 1, and let us say the total_time is 2, then,
the start_if-end_if block (step 6.0 to 7.0) will not be executed. However, the
start_if_not-end_if_not block (step 9.0 to 10.0) will be executed.

In step 9.1, total_time will be 1 because 2 minus 1 is 1. Total_time is reduced by 1


because the payment for the first hour is different from the subsequent hours.

In step 9.2, payment will also be 1 because total_time is multiplied by 1 and is 1,


hence in the second hour and so on, the payment is 1 for every hour.

In step 9.3, total_time now becomes 3; because 1 plus 2 is 3. Here the value 2 is
for the payment rate for the first hour. You need to remember that the payment
for the first hour is different from the subsequent hours. Total payment reported
in step 11.0 is 3.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 25

ACTIVITY 2.5

Now try with the previous data which has the in_time 9:30 and out_time
4.30. Use the algorithm given in Example 2.9 as a reference.

SELF-CHECK 2.4

The pseudo-code in Example 2.9 above can be re-written using the


single-selection structure. Write the new pseudo-code.

2.3.3 Multi-selection
This is the last selection structure. In multi-selection we are allowed to choose
only one statement block from a number of blocks that exist. The number of
statement blocks depends on the number of conditions. If there are n conditions,
then there are n+1 statement blocks, because we have a last statement block that
is not tied to any of the conditions. In the general form below, the statement
blocks are from step q till r.

If <true condition1>
Start
step 1
step 2

step k
End_If1
If_Not
If<true condition2>
Start
step k+1
step k+2

step m
End_If2


If_Not
If<true condition h>

Copyright © Open University Malaysia (OUM)


26 TOPIC 2 ALGORITHM

Start
step n + 1
step n + 2

step p
End_Ifh
If_Not
step q
step q+1

step r
End_If_Not

Figure 2.9 shows the flow chart for the general structure of multi-selection.

Figure 2.9: Multi-selection structure flow chart


Copyright © Open University Malaysia (OUM)
TOPIC 2 ALGORITHM 27

Let us consider the examples given.

Example 2.10
Input an integer number and determine whether that number is negative,
positive or zero. Print the results.

The algorithm for the example given above is:


1.0 Start.
2.0 Read integer N
3.0 If (N < 0)
4.0 Start.
4.1 Print „N is negative‰
5.0 End_If1
6.0 If_Not
7.0 If (N > 0)
8.0 Start.
8.1 Print „N is positive‰
9.0 End_If2
10.0 If_Not
11.0 Start.
11.1 Print „N is zero‰
12.0 End_If_Not
13.0 End

Let us trace the example above. Suppose that the value of N is 7. Testing at step
3.0 will be false because 7 is larger than 0. Step 4.0 till step 5.0 are ignored. When
testing at step 7.0 is executed, the result is true. Therefore, it will print „N is
positive‰.

ACTIVITY 2.6

Trace the value of 10 based on the algorithm above. What is the printed
result?

Copyright © Open University Malaysia (OUM)


28 TOPIC 2 ALGORITHM

Example 2.11
Input bus passengerÊs age to determine the price of the tickets. If the age of
the passenger is 55 and above or between 6 to 12 years, then the ticket price is
50% of the normal ticket price. If the passengerÊs age is between 12 and 18
years, then the ticket price is only 75% of the normal ticket price. It is free for
passengers less than 6 years old.

From the question given, we can conclude that there are five groups of
passengers, as shown in Table 2.1 below:

Table 2.1: Summary of Example 2.11

Passenger Groups Ticket Price


Aged less than 6 (Age < 6) Free
Aged between 6 and 12 50% of the normal ticket price
( 6 <= Age <12 )
Aged between 12 and 18 75% of the normal ticket price
( 12 <= Age <18 )
Aged between 18 and 55 Normal ticket price
( 18 <= Age <55 )
Aged more than 55 50% of normal ticket price
( Age >= 55 )

Figure 2.10 is a flow chart that shows a multi-selection structure. Trace Figure
2.10 and compare it with the conditions stated in Example 2.11. The flow chart is
as follows:

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 29

Figure 2.10: Flow chart Example 2.11, multi-selection structure

2.4 REPETITION STRUCTURE


Repetition Structure is a structure where one block of statements is executed
repeatedly. This repetition concept has already been used in the algorithm
examples earlier by using English words such as until, repeat and others. In a
more formal algorithm, the concept of repetition is stated in a structure called a
loop. There are three main types of loops as shown in Figure 2.11.

Figure 2.11: Types of loops

Copyright © Open University Malaysia (OUM)


30 TOPIC 2 ALGORITHM

2.4.1 Counter Controlled Loop


The counter controlled loop is managed by a loop controller variable or
otherwise known as a counter. The counter holds a value that represents a count.
This counter can be divided into three components:

(a) Initial value for counter;


(b) Condition to repeat the loop; and
(c) Updating the counter value.

For a loop controlling counter, the three components are put in special places,
such as:

for (counter=initial_value; test counter; update counter)

start_for
step 1
step 2
Loop Body
step n
End_for

At the beginning of the execution, the counter will be assigned an initial_value.


Then the condition for repetition is tested. For an incrementing loop, the value of
the counter will always increase until the condition is false. Therefore normally,
the condition for repetition is the counter value which is always lesser than, or
the same as, the last value that wants to be achieved.

If the counter value is still less than the last value, the step in the start_for-
end_for block, which is steps 1 till n will be executed. This block is also known as
the loop body.

After the last step in the loop is executed, the value of the counter is updated
according to the increment that is stated. Notice however that the increment is
not necessarily done by adding 1 to the counter. The increment can be 2 or 3 and
so on. After the counter has been updated, the test is done again and the
execution of the loop body repeats until the condition that is set on the counter is
no longer fulfilled.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 31

The loop ends and the control will get out of the loop. The step after the end_for
will be executed. Figure 2.12 shows the general flow chart for the counter
controlled loop.

Figure 2.12: Flow chart for counter controlled loop

There are two types of counter controlled loops:

(a) Loop with increasing counter; and


(b) Loop with decreasing counter.

Let us look at each of these counters.

(a) Loop with Increasing Counter Control


The loop with increasing counter control is the commonly found loop.
Usually the initial_value is a smaller value than the last value. The update
is made on the value by increasing the value of initial_value until the value
is the same as the end value and the test becomes false. Look at Example
2.12.

Copyright © Open University Malaysia (OUM)


32 TOPIC 2 ALGORITHM

Example 2.12

The algorithm is given as:


1.0 Start.
2.0 Set total = 0.
3.0 for (i = 1; i < 10; increase i by 2)
4.0 start_for
4.1 total total + i
5.0 end_for
6.0 Report total value.
7.0 End

In Example 2.12, the start_for - end_for block will be executed five times.
Therefore, we need to trace the algorithm above while looking at Table 2.2.

Table 2.2: Tracing Incrementing Loop

i i < 10 Total
0
1 True 1 (0+1)
3 (1+2) True 4 (1+3)
5 (3+2) True 9 (4+5)
7 (5+2) True 16 (9+7)
9 (7+2) True 25 (16+9)
11 (9+2) False 25

The loop will stop when the counter i is more than 10, that is, when the
value i is 11. At this stage, the value of total will be 25.

(b) Loop with Decreasing Counter Control


Loop with decreasing counter control, is generally the same as the loop
with increasing counter control. The differences are:

(i) The counter starts at a larger value and will decrease to a smaller
value according to the decrement rate stated.

(ii) The condition for repetition is > or >= with the last value.

(iii) The initial_value must be a large number.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 33

You need to remember that the initial_value must be a large value. After
the last step is executed, the value of the counter will be decreased
according to the rate specified. Just as in the increasing counter control
loop, the rate is not necessarily 1. Look at Example 2.13:

Example 2.13

The algorithm is:


1.0 Start.
2.0 Set total = 0
3.0 For (i = 9; i >= 1; i decrement 2) start_for
3.1 total total + i
4.0 End_for
5.0 Report total
6.0 End

Notice that in step 3.0, the initial_value is a large number that will be
decreased by 2 to its initial_value. Next, we look at Table 2.3 to trace the
loop:

Table 2.3: Tracing Decreasing

i>=1 Total
0
9 True 9 (0+9)
7 (9-2) True 16 (9+7)
5 (7-2) True 21 (16+5)
3 (5-2) True 24 (21+3)
1 (3-2) True 25 (24+1)
-1 (1-2) False 25

The loop will stop when the condition is not fulfilled, that is when the
value of i is -1. At that instant, the total is 25. The end result of total in the
example with the increasing counter and the total in the example with the
decreasing counter is the same.

Copyright © Open University Malaysia (OUM)


34 TOPIC 2 ALGORITHM

ACTIVITY 2.7

What is the effect if i decrement 2 is replaced by i plus 2 in the Example


2.13 algorithm in step 3.0? Why does that happen?

2.4.2 Condition Controlled Loop


Loops like these are controlled by true conditions. There are two types of general
loops controlled by conditions, which are:

Loops with conditions tested first; and

Loops with conditions tested later.

(a) Loop with Condition Tested First


Where the condition is tested first, and if it is true, the step in
start_until_end_until (step 1 until step n) will be executed. After the last
step in the block is executed, usually updates are done and the condition is
tested again.

True Repetition statements in the loop body


Until condition
False Out of loop and execute step after end_until

The general form of a condition loop tested first is as follows:

Figure 2.13: General Form and Flow Chart of Loop Structure with condition tested first

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 35

Let us now look at Example 2.14.

Example 2.14

Consider the example:


1.0 Start.
2.0 Set total and counter to 0
3.0 Until counter < 5
4.0 Start.
4.1 counter counter + 1
4.2 total total + counter
5.0 End
6.0 Report total value
7.0 End

In Example 2.14, the block start_until-end_until will be executed five times


until the condition counter < 5 is false and the value of counter is 5. The last
value of total is 15. Consider the tracing of the loop below:

Table 2.4: Tracing of Loop with Condition Control

Counter < 5 Loop Counter Total


0 0
True (0<5) 1 1 (0+1) 1 (0+1)
True (1<5) 2 2 (1+1) 3 (1+2)
True (2<5) 3 3 (2+1) 6 (3+3)
True (3<5) 4 4 (3+1) 10 (6+4)
True (4<5) 5 5 (4+1) 15 (10+5)
False (5<5) 5 15

(b) Condition Tested Later


For this loop, the steps in the loop will be executed first and the condition
will be tested later, that is when the statement until is reached. This means
the steps in start end loop will be executed at least once. The following
Figure 2.14 shows the flow chart for the condition controlled loop with the
condition tested later.

Copyright © Open University Malaysia (OUM)


36 TOPIC 2 ALGORITHM

Figure 2.14: General form and flow chart of loop structure with condition tested later

Example 2.15

Consider the example for loops of this type:


1.0 Start.
2.0 Set total and counter to 0.
3.0 Start.
3.1 counter counter + 1.
3.2 total total + i.
4.0 End.
5.0 Until (counter less than 5).
6.0 Report total value
7.0 End.

In Example 2.15, the end result of total is the same as the loop before this,
which is 15. Notice in the tracing below, the number of tests for the
condition in the condition controlled loop for this form is one less than the
condition in the condition controlled loop in the form before this.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 37

Table 2.5: Tracing of Loop with Condition Control Tested Later

Counter < 5 Loop Counter Total


0 0
1 1 (0+1) 1 (0+1)
True (1<5) 2 2 (1+1) 3 (1+2)
True (2<5) 3 3 (2+1) 6 (3+3)
True (3<5) 4 4 (3+1) 10 (6+4)
True (4<5) 5 5 (4+1) 15 (10+5)
False (5<5) 5 15

2.4.3 Sentry Controlled Loop


Loops of this type are actually subset loops controlled by condition. Sentry value
is a signal to stop the loop. Loops like these are also called uncertain loops
because the number of loop executions are not known before the execution starts.
The sentry value chosen must not be an input data that is valid. Consider the
sentry controlled loop in Example 2.16.

Example 2.16
Read one set of studentsÊ marks where if the marks are negative then the
input ends. Calculate the average marks.

Algorithm 2.16 (A):


1.0 Start
2.0 Set i to 1 and Total to 0
3.0 Read first mark, mi
4.0 Until mi > = 0
5.0 Start
5.1 Total total + mi
5.2 i i +1
5.3 Read i-th mark, mi
6.0 End
7.0 Average Total/(i - 1)
8.0 Print Average
9.0 End

Copyright © Open University Malaysia (OUM)


38 TOPIC 2 ALGORITHM

In example 2.16, a negative mark input will end the loop because the test
condition (step 4.0) becomes false. In the example above, the number 999 can be a
sentry value because the maximum mark is 100. To make the number 999 as a
sentry value, step 4.0 in the algorithm has to be changed to Until mi = 999, that is,
when the mark mi is 999, then the statement becomes false and automatically
exits the loop.

ACTIVITY 2.8

For the algorithm in Example 2.16, what if the negative value is a valid
data?

Sentry value can also be of a type character. We can change the example above
and use the character „t‰ as a sentry value. Consider the changes made in
algorithm 2.16(B) below.

Algorithm 2.16 (B):


1.0 Start
2.0 Set i to 1 and Total to 0
3.0 Set continue as ÂyÊ
4.0 Until continue == ÂyÊ
5.0 Start
5.1 Read i-th mark, mi
5.2 Total Total + mi
5.3 i i + 1
5.4 input ÂyÊ to continue the operation or ÂnÊ to stop the operation
6.0 End
7.0 Average Total/(i - 1)
8.0 Print Average
9.0 End

You have now learnt three types of control structures. Take a short break before
moving on to the next section.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 39

2.4.4 Structuring
This method is used to solve problems by designing structure charts. The
benefits of using the structure chart are as follows:

(a) Able to identify the number of modules or sub-problems that are created
by breaking up the problem;

(b) Able to give input that is needed by a module or sub-problem that can be
shown in the chart; and

(c) Able to determine the output that is obtained from one module that can be
used in other modules.

As an example, consider the problem statement given below:

(a) Problem
Solve the problem of calculating the gross pay and net pay for workers that
is made up of basic pay and overtime pay. The normal working hours are
40 hours. The rate for working overtime is twice the normal rate. If the
workerÊs pay exceeds RM500 per week, a tax of RM50 is deducted.

(b) Analysis
To calculate the pay, the information needed are the hours worked and the
hourly rate. The net pay of a worker can be obtained by deducting tax from
the pay if the pay exceeds RM500.

(c) Data Requirements


Permanent Information (Constant):

Taxable_Pay = 500.00
Tax = 50.00
Maximum_Hours = 40.0
Overtime_Rate = 2.0

Input:
Hours_Worked (float type)
Hourly_Rate (float type)

Output:
Gross_Pay (float type)
Net_Pay (float type)

Copyright © Open University Malaysia (OUM)


40 TOPIC 2 ALGORITHM

Relevant Formula:
Normal_Pay = Work_Hours x Hourly_Rate
Overtime_Pay = Overtime_Hours x Overtime_Rate x Hourly_Rate
Gross_Pay = Normal_Pay + Overtime_Pay
Net_Pay = Gross_Pay - Tax

(d) Design
Initial Algorithm:

1.0 Start
2.0 Read Hours_Worked and Hourly_Rate.
3.0 Calculate Gross_Pay.
4.0 Calculate Net_Pay.
5.0 Print Gross_Pay and Net_Pay.
6.0 End

The following Figure 2.15 shows a structure chart of the problem.

Figure 2.15: Structure Chart to find net pay problem

Step 3.0 and step 4.0 can be refined. Normally, our operation uses
refinement to get the calculated gross pay and net pay.

(e) Step 3 Refinement:

3.1 IF (Hours_Worked <= Maximum_Hours)


3.1.1 Gross_Pay = Hours_Worked x Hourly_Rate
3.2 End_IF
3.3 IF_Not
3.3.1 Gross_Pay = (Maximum_Hours x Hourly_Rate) +
3.3.2 (Hours_Worked Maximum_Hours) x Overtime_Rate x
Hourly_Rate)
3.4 End_IF_Not

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 41

(f) Step 4 Refinement:

4.1 IF (Gross_Pay > Taxable_Pay)


4.1.1 Net_Pay = Gross_Pay - Tax
4.2 IF_Not
4.2.1 Net_Pay = Gross_Pay
4.3 End_IF_Not

2.5 CASE STUDY 1


PROBLEM
You are required to do surveying jobs and deal with maps that give distances in
either km or miles. However, you prefer to use metric measurements. When you
have to deal with values in miles, you will need to convert them. So, it will be
great if you can have a conversion program to convert the measurement from
miles to km. Let us first analyse this problem.

ANALYSIS
The first step in solving a problem is to determine what you are asked to do. Are
you supposed to convert measurement from km to miles, or vice versa? The
problem states clearly that you need to convert miles to km. Therefore, the
problem input is distance in miles and the problem output is distance in km.
Then, you will need to know the relationship between miles and km. Based on
the metric table, one mile is equal to 1.609km.

Write down on a piece of paper, the following data requirements:

(a) Problem Input:


miles /* the distance in miles */

(b) Problem Output:


kms /* the distance in km */

(c) Relevant Formula:


1 mile = 1.609km

Copyright © Open University Malaysia (OUM)


42 TOPIC 2 ALGORITHM

DESIGN
Next step, formulate an algorithm to represent this problem. Think logically of
the three major steps in a proper sequence.

Algorithm

1. Get the distance in miles.

2. Convert the distance to km.

3. Display the distance in km.

Now you will need to decide if this algorithm can be refined further. Step 1
(getting data) and step 3 (displaying value) are basic steps and cannot be refined
anymore. Step 2 however, can be refined with additional detail. You can add the
information as step 2.1, indented under step 2.

Algorithm with Refinements


1. Get the distance in miles.
2. Convert the distance to km.
2.1. The distance in km is 1.609 times the distance in miles.
3. Display the distance in km.

The above steps are known as pseudo-code. You might be interested in drawing
a flowchart to represent the same algorithm. Take a look at the following
flowchart to get an idea of designing algorithms for programming tasks.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 43

Figure 2.16: Flow chart of the conversion program

After finishing with this algorithm, you may want to do a desk checking before
proceeding with its implementation. How is that done? Let us say, step 1 gets a
distance of 10.0 miles and step 2.1 should convert the measurement to 1.609 X
10.0. You should then get 16.09 km as the result to be displayed in step 3.
Remember these values as you are going to use them in the implementation
phase later on.

2.6 CASE STUDY 2


PROBLEM
Many programs require input from users. Based on this input, the program will
then display an appropriate message. This message will give the users an
indication about the type or choice of input needed by the program.

Copyright © Open University Malaysia (OUM)


44 TOPIC 2 ALGORITHM

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 is able to perform these


conversions:

(a) Convert time from minutes to hours;


(b) Convert distance from feet to metres; and
(c) 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.

ANALYSIS
The following formula is used to do the conversions:

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

DESIGN
The menu to be displayed by the program is based on the selection listed in Table
2.6:
Table 2.6: Menu

Choice Code Conversion Type


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

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
above, it will be ignored. This means, the program will re-display the menu and
the user has to choose again.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 45

Table 2.7. shows all the variables to be used in the pseudo-code.

Table 2.7: 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 the initial pseudo-code for our problem:

1.0 Start
2.0 Do
2.1 Display the menu
2.2 Input the choice from the user
2.2.1 IF (1 <= choice and choice <= 3)
Start_IF
Do the conversion and display the result
End_IF
3.0 Until (choice NOT 0)
4.0 End

Step 2.2.1 involves calculation that will perform the conversion and then display
the results. The calculation that is carried out depends on the type of choice
specified by the user in Step 2.2. Thus, Step 2.2.1 needs to be refined further, to
reflect the userÊs choice. The following is the refined and complete pseudo-code
after refining Step 2.2.1 above:

Copyright © Open University Malaysia (OUM)


46 TOPIC 2 ALGORITHM

1.0 Start
2.0 Do
2.1 Display the menu
2.2 Input the choice from the user
2.2.1a IF (choice==1)
Start_IF
Input minutes from the user
Calculate hours
Display hours and minutes
End_IF
2.2.1b IF (choice==2)
Start_IF
Refined
Input feet from the user
steps
Calculate metres
Display feet and metres
End_IF
2.2.1c IF (choice==3)
Start_IF
Input fahrenheit from the user
Calculate celsius
Display fahrenheit and celsius
End_IF
3.0 Until (choice NOT 0)
4.0 End

The flow chart for the above pseudo-code is given below in Figure 2.17:

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 47

Figure 2.17: Flow chart for the pseudo-code

Copyright © Open University Malaysia (OUM)


48 TOPIC 2 ALGORITHM

SELF-CHECK 2.5

1. Based on the problem given below, construct a flow chart:

(a) By inputting an integer number, generate a multiplication-


table (1 to 12) for that number. As an example, if the number
input is 4, then display the 4 times table; and

(b) Input the values of length and width for a residential area in
feet measurement. Also enter the values of length and width
for the building of a house in feet measurement. Assume the
difference of a grassy area between them. Calculate the time
needed to cut grass at the rate of 2 square feet per second.

2. Based on the problem given below, construct a pseudo-code.

(a) Given the radius, determine the area and circumference of a


circle.

(b) You have been asked to input your name and then print it
five times.

(c) Construct a flow chart to determine your weight category.


The category determination is based on Body Mass Index
(BMI). BMI is the ratio of height in metres to body weight
in kilos. The formula is given as:

Weight category is as follows:

CATEGORY BMI
Underweight less than 18.5
Normal 18.5 24.9
Overweight class 1 25.0 29.9
Obesity class 2a 30.0 34.9
Obesity class 2b 35.0 39.9
Obesity class 3 40.0 and above

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM 49

(d) Create a pseudo-code for this problem. Accept two integer values as
input, for example, 3 and 7. Print all the integer numbers between
them, including those two numbers. If the first number is smaller
than the second number, then print the numbers in ascending order.
If otherwise, print the numbers in descending order.

For example:
Input: 3 7
Output: 3 4 5 6 7

Input: 7 3
Output: 7 6 5 4 3

Algorithm is a step-by-step problem-solving method in a limited time.

Activities in the algorithm representation are represented by geometry


nodes. Each node represents different activities. These nodes will be joined
using arrows that show the flow or a sequential activity.

Pseudo-code or false codes are instructions that mimic the program code
(actual program instructions).

Input is all the information that is relevant and needed to execute a process.

Output is the result that is needed.

Selection structure is a structure design that gives a few choices during


execution.

Single selection involves testing one condition only. The choice given
depends on whether the condition is met or not.

The dual selection structure involves testing for two conditions. Choices that
are given are the same as single-selection, that is, whether the condition is
met or not.

Copyright © Open University Malaysia (OUM)


50 TOPIC 2 ALGORITHM

In multi-selection we are allowed to choose only one statement block from a


number of blocks that exist. The number of statement blocks depends on the
number of conditions.

Repetition Structure is a structure where one block of statements is executed


repeatedly.

Algorithm Semantic
Flow chart Syntax
Pseudo-code

Copyright © Open University Malaysia (OUM)


Topic Programming
3 Language

LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Differentiate the three different types of programming languages, by
levels;
2. Explain briefly on the history of C language development; and
3. Describe the six phases that are involved in developing a program in
C environment.

INTRODUCTION
In Topics 1 and 2, we looked at the basics of program development. We will now
continue exploring programming language in more detail.

To command a computer to do a task, instructions must be written in the


computerÊs native language, which is machine language. If you have not heard
about machine language before, then this topic will be an eye-opener for you.

Writing programs in machine language is not an easy task for the programmer.
To overcome this problem, many different programming languages have been
created, to enable instructions to be given in forms other than machine language.
These instructions need to be translated into machine language, before a
computer can run them. This topic will give an explanation on the different types
of programming languages. Next, C language and its environment will be
introduced. By the end of this topic, one example of a simple C program will be
discussed.

Copyright © Open University Malaysia (OUM)


52 TOPIC 3 PROGRAMMING LANGUAGE

3.1 PROGRAMMING LANGUAGE TYPES


Programmers write programs using programming languages. There are many
categories of programming languages. Programming languages that are most
popular and normally used are high-level languages. In this topic, we will see
different types of languages, which are: machine language, assembly language
and high-level language.

3.1.1 Machine Language


Every computer has its own machine language, that is, its native language.
Programs written in machine language are normally stated in binary numbering
system (0 and 1) or in the hexadecimal numbering system. Every machine
language instruction will state the operation to be executed, along with the
memory cell involved in that operation.

3.1.2 Assembly Language


The second level of language is assembly language. Programming in machine
language was felt to be too difficult and slow. To make programming easier,
mnemonic language that resembles the English language was created and used
to represent operations in machine language. This is the basis of assembly
language. To run a program in assembly language, a program called the
assembler is used to translate the program to machine language.

ACTIVITY 3.1

Study the example of assembly language in the book Introduction to


Computers and Information System, 2nd Ed. page 228, Maxwell
Macmillan by Szymenski, R.A and Associates. Can you understand the
language? Can you list a few words in mnemonic language?

3.1.3 High-level Language


Do you know the other factors that contributed to writing programs with
machine language and assembly language to discontinue? Programs written in
machine language or assembly language are machine-dependent. Assuming we
write a program in assembly language for a particular computer and want to run

Copyright © Open University Malaysia (OUM)


TOPIC 3 PROGRAMMING LANGUAGE 53

this program on another type of computer; it has to be written again in assembly


language for that computer. A language that is machine-independent is needed
to make it easier for programs to be transferred from one computer to another.
Many high-level languages have been created for this reason. With high-level
language, a programmer is able to write programs that are simple and clear. For
example, the following statement is written in C language (which is one of the
high-level languages) to code an example on calculating a sales amount.

amount = itemPrice + salesTax;

Compared to assembly language, high-level language resembles the natural


language more, making it easier to read and understand.

Just like assembly language, a program in high-level language needs to be


compiled into machine language before it can be executed. The process of
compilation is accomplished by the compiler program. Some high-level
languages and their uses are listed in Table 3.1 below.

Table 3.1: High-level Languages

High-Level
Explanation
Languages
C A universal language that is usually used to write system software or
system applications.
C++ An extension from C language that provides support for object-
oriented programming.
Ada Language that is developed for the Defence Department in the United
States, for its real-time systems.
Lisp For artificial intelligence applications.
Pascal For teaching programming.
Fortran For scientific and engineering applications.
COBOL For processing business data.

ACTIVITY 3.2

Before we continue reading the next topic, create a networked mind map
of the three levels of programming languages that you have just read.
Present that in your tutorial.

Copyright © Open University Malaysia (OUM)


54 TOPIC 3 PROGRAMMING LANGUAGE

SELF-CHECK 3.1

Give two advantages of writing programs in C language compared to


machine language.

3.2 C LANGUAGE
Let us take a step back to the past, to get a brief history of C language.

The C language history has links with the existence of B and BCPL programming
languages. BCPL is a language that was used to write operating systems and
compilers, which was developed by Martin Richards in the year 1967. In the
1970s, Ken Thompson developed the B language that was used in developing the
UNIX operating system at Bell Laboratories. Based on B language, Dennis Ritchie
developed the C language at Bell Laboratories in 1972. This language was then
used to develop UNIX.

The C program development can be done on many computers, as C language


does not depend on the machine or hardware. Through this portability feature,
programs that are written in C language can be transferred to any computer,
with minimal changes. Other than using important concepts from BCPL and B,
many different features like pointers, were added into C, to make it a strong
language. Another advantage of C is its wide usage and its high ability.

Due to the existence of many variations of C language, the American National


Standards Institute (ANSI) has created a standard C, which is called ANSI C.
This standard enables us to write C programs that are portable.

For more information on the history of C programming, visit the web site
http://syazwan.tripod.com/introc.htm or any other relevant sites.

3.3 C PROGRAMMING ENVIRONMENT


Generally, the C programming system is composed of its environment, its
language and standard library:

(a) Environment is related to the process it goes through, to develop a C


program that can be executed.

Copyright © Open University Malaysia (OUM)


TOPIC 3 PROGRAMMING LANGUAGE 55

(b) Language refers to the aspect of syntax or the representation of algorithms


in C language.

(c) C standard Library makes available the supporting functions that can be
reused in program development. Among functions that are available in the
standard library are: mathematical functions like sin( ) and sqrt( ), functions
to do input and output, graphical functions and others.

Figure 3.1 on the next page shows a C development environment. It shows the six
phases involved in the process of developing a C program, which are:

(a) Editing;
(b) Pre-processing;
(c) Compiling;
(d) Linking;
(e) Loading; and
(f) Executing.

Further explanation on each phase will provide an indication on the


development of programs in the MS-DOS environment. For Windows operating
systems, the environment can be created through the MS-DOS prompt icon.

Copyright © Open University Malaysia (OUM)


56 TOPIC 3 PROGRAMMING LANGUAGE

Figure 3.1: C development environment

SELF-CHECK 3.2

Identify a software that you can use to edit and compile programs.

Copyright © Open University Malaysia (OUM)


TOPIC 3 PROGRAMMING LANGUAGE 57

3.4 SAMPLE C PROGRAM

Program 3.1

/* This program will print a greeting


Welcome to OUM */ A

#include <stdio.h> B

void main(void) {
printf(“Welcome to OUM!\n”); C
}

In this section, we will look at an example of a simple C program (see Program


3.1). This program will display the following output when executed:

Welcome to OUM

The statement that is marked as A in Program 3.1 is a comment to explain the


programÊs meaning. Comments are any text that is surrounded by the symbols /*
and */. Comments are inserted to give information or explanation on the
program code. A program can contain as many comments as needed and can be
put anywhere in the program code. Comments are not compulsory in a program,
but we are encouraged to include comments so that programs can be easily read
and understood.

Statements that are marked as B in Program 3.1 are said to be pre-processor


statements. Pre-processor statements are easily recognised because they start with
the symbol #. Here, pre-processor statements used are the #include statement.
When executed, the pre-processor will insert a copy of a header file called stdio.h
into the program code, at the given statement line. This statement is needed in
Program 3.1 because the header file has the function declaration printf(). We
will see later how the program will use the function to output something.

Notice however that the file name stdio.h in the pre-processor statement is
surrounded by the symbol < and >. This is actually to let the pre-processor know
that the file is found in the usual place. This usual place is dependent on the
computerÊs environment. For example, in the UNIX environment, the normal place
is stated in the file .profile. In the DOS mode, it is normally stated in the file
autoexec.bat.

Copyright © Open University Malaysia (OUM)


58 TOPIC 3 PROGRAMMING LANGUAGE

The code that is marked as C in Program 3.1 is a function definition. The function
that is defined in the program is called main() function. The main() function is
a special function that is the starting point in the execution of any C program.

Notice that the function definition consists of two parts. The first part is the
function head that provides specific information on the function defined; for
example, function name. The second part is the function body which consists of
statements enclosed in { and }. When a function is called, the statements within
the body will be executed. In the case of main() function in the program 3.1, the
body only contains one statement which is:

printf(“Welcome to OUM!\n”);

This statement is the calling of the function printf(), which is one of the
functions that is available in the C standard library functions. We can call this
function printf() if we need to output a string on the computer screen. In the
statement above, the string “Welcome to OUM!\n” is passed to the printf()
function to be output.

The function will display every character in the string, except the enclosing
double quotes (which is the character „) and the control character \n at the end of
the string. The double quotes are the markers for the start and end of the string.

The control character \n is called the new line character. When this character is
found in the printf() function, it will move the cursor to the beginning of the
next line. The new line character is one of the many control characters in the
printf() function. Every control character will have a specific meaning in the
functions given.

SELF-CHECK 3.3

In Section 3.4, there are symbols that were used in Program 3.1. Can you
explain them briefly?

Symbols Explanation
/*.........*/
#include
{.........}
“\n”

Copyright © Open University Malaysia (OUM)


TOPIC 3 PROGRAMMING LANGUAGE 59

ACTIVITY 3.3

1. Write/edit program 3.1 using a notepad and save the file with the
name atur.c.

2. Compile the program.

3. Execute the program.

4. Compare the output.

5. Edit the program by changing the statement printf („Open


University Malaysia‰);

6. Edit the program 3.1 so that the output below is displayed:

WELL
WELCOME
WELCOME TO
WELCOME TO OUM!

Machine language is the computerÊs natural language. Programming in


machine language is in the binary format.

Assembly language is a mnemonic language and is closer to the English


language in its representation of operations and operands.

High-level language is closer to natural language.

A program written in assembly language or high-level language has to be


translated into machine language, before it can be executed.

C Language is a high-level language.

In the C environment, a program has to go through the following phases in


its development process: editing, pre-processing, compiling, linking, loading
and executing.

Copyright © Open University Malaysia (OUM)


60 TOPIC 3 PROGRAMMING LANGUAGE

C Language Environment
Assembly language Linker
C standard library Loader
Compiler Machine language
Editor

Copyright © Open University Malaysia (OUM)


Topic Data Types
4 and Variables

LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Differentiate three types of data;
2. Choose the type of data that is suitable for the variable, depending on
the type of value to be represented;
3. Differentiate between variables, reserved words and standard
identifiers;
4. Identify variables that are valid and invalid; and
5. Write syntax to declare and initialise variables.

INTRODUCTION
In the first part of this topic, we are going to see two types of input and output
data. One is of character type, for example, your name, and another is of the
numeric type, for example, your age. Data of character type is represented by
char data type. Numeric data is represented by data types int, float or
double.

In the second part, you will learn about variables. Why are variables important?
When a composer composes a new song, he/she will give a title to the song.
Your parents spent some time choosing a name for you. Similarly, when we
write a program, we need to choose an appropriate name for the file, variables,
constants, functions, etc. This name is known as the identifier. The identifier is
the official word used for any name in a high-level programming language. In
this topic, we will go into detail about variables and how to name them.

Copyright © Open University Malaysia (OUM)


62 TOPIC 4 DATA TYPES AND VARIABLES

4.1 CELL SIZES AND QUALIFIERS


Bytes is the unit for cell sizes. Variables are assigned cell sizes or memory spaces
that are different, according to their data type. Variables of int type are given a
cell size of 2 bytes, that can keep numbers up to a maximum of 32767.

Variables of float type are assigned a memory cell size of 4 bytes and can keep
larger numbers, up to 1038.

Let us see an example of initialising variables and memory cell sizes assigned for
each declaration in Table 4.1 below.

Table 4.1: Relationship between Declaration, Variables and Total bytes

Declaration Memory Total Bytes


int age; age 2 bytes
float height; height 4 bytes
long int multiples; multiples 4 bytes

The size of the memory cell can double by using the qualifier long in a variable.
See the example above.

4.2 INTEGER DATA TYPE (int)


The int data type is to represent negative or positive numbers, for example
77, 0, 999, +999. The memory cell size for int types differs according to
the different computer systems. In the computer family of 80386 processors and
below, the memory cell size for int is 2 bytes. For processors like SPARC, the
cell size for int is 4 bytes.

4.3 CHARACTER DATA (char)


The char data type is used to represent characters such as letters, digits or
special symbols like „?‰.

To assign a character to a variable, we will need to put single quotation marks as


in: Â Â, next to the character, for example: ‘A’, ‘z’, ‘3’, ‘?’.

Copyright © Open University Malaysia (OUM)


TOPIC 4 DATA TYPES AND VARIABLES 63

A character can be read, printed or changed to an integer value. We can also


make character value comparisons, by using operators like equal (==) or not
equal (!=), and relational operators such as <, <=, > and >=. To understand how
character values can be compared, we need to know how each character is
represented in a computer. Each character has its own unique numeric code,
using the American Standard Code for Information Interchange, commonly
known as ASCII codes.

If you want to know more about ASCII codes, you can visit the relevant websites.
The binary representation of this code is kept in the memory cell and the values
can be known. The binary numbers can be compared by using relational
operators, just like comparing normal numbers. The character code usually used
is ASCII code. The character value range that can be represented by char type is
between -128 to 128.

4.4 REAL DATA TYPE


ANSI C, introduced by the American National Standards Institute (ANSI),
describes three types of data type that can be used for manipulating real data
types:

(a) float;
(b) double; and
(c) long double.

All the types above can keep real values such as 0.001, 2.0 and 3.14159.
The choice is made depending on which range of real values are to be
represented. Table 4.2 below shows the range and number of bytes that are
needed for each of the real type numbers.

Table 4.2: Real Data Type

Real Data Type Number of Bytes Precision Range


float 4 6 10-37 .. 1038
double 8 15 10-307 .. 10308
Long double 16 19 10-4931 .. 104932

However, on some computer systems, the implementation of double and long


double is the same for the number of bytes allocated.

Copyright © Open University Malaysia (OUM)


64 TOPIC 4 DATA TYPES AND VARIABLES

ACTIVITY 4.1

There are three types of basic data types: int, char and float.
char can contain letters, digits and symbols. Why do we still need int
and float when char can contain all types of characters? State your
opinion.

SELF-CHECK 4.1

1. How many real data types are there? List them.

2. Given the declaration below, how many bytes are assigned to


each data type?

Variable Declaration Bytes Used


float weight;
double volt1;
char letter;
int hour, minute;
long int second, length;
long double volt2;

3. State the data type that is suitable for each of the values below so
that memory space wastage does not happen:
(a) 0.000067 (d) 123.123456789
(b) # (e) -40000
(c) 30000 (f) 1000000

4.5 VARIABLE NAMING


Variables are an example of an identifier. It is used in certain program blocks. It
is initialised before it can be used. To declare a variable, we need to associate a
name and the data type to represent a particular value.

Copyright © Open University Malaysia (OUM)


TOPIC 4 DATA TYPES AND VARIABLES 65

Next, let us see how each of the characteristics above is applied in a program.

Variables are named as an identifier that is declared by the user. This name has
to be:

(a) Appropriate;
(b) Easy to understand; and
(c) A name that gives a clear meaning towards the value that it represents.

This name is used to name a memory area that will be used to keep the value of
the variable.

4.5.1 Rules to Name a Variable


The guidelines to choosing a name for a variable in the C language are as follows:

(a) Variable names can only contain letters, digits and underscores “_”;
(b) Variable names cannot start with a digit (number); and
(c) Reserved words in C cannot be used as variable names.

Here are some examples of variable names that are valid.

tot3 big_Total total BigTotal big_total

We can give variable names up to 31 characters. The 32nd character onwards will
not be taken into consideration (except for global variable names, which will not
be discussed in this module).

System identifiers usually start with the character „_‰. Here, we are not
encouraged to use the character „_‰ as the beginning for identifiers, (for example:
_total) to avoid confusion. Both lower case and capital letters can be used to
name variables. However, the C language is case sensitive, where lower case
letters are considered different from capital letters. Observe that each of the
variable names below is different in C.

total Total toTAL TOtal toTal

Copyright © Open University Malaysia (OUM)


66 TOPIC 4 DATA TYPES AND VARIABLES

The best way to name a variable, is with a name that represents the value that is
kept in the identifier. Therefore, sometimes a variable name can be made up of
two words or more. We cannot separate the words with spaces, because it is
against the first rule of naming identifiers, which states that identifiers that have
a space in between are not valid.

For identifiers that have two or more words, we can join them with a “_”
character (like big_total). Nevertheless, the usual practice is to write it as:

(a) Start with the first word being a lower case letter; and
(b) Start the second word with an upper case letter.

Therefore, the identifier above is better written as bigTotal.

SELF-CHECK 4.2

State whether the variables given are VALID or INVALID.

Variable VALID or INVALID


(a) Address2
(b) 33road
(c) _empty

4.5.2 C Reserved Words and Standard Identifiers


Reserved words are words that have special meanings in C and cannot be used
for other reasons. All reserved words come in lower case letters.

To learn more about this topic, refer to Pengaturcaraan C, Marini Abu Bakar et.
al. (2000).

Like reserved words, standard identifiers also have special meanings in C. In the
sample programs that you have seen before, the standard identifier printf is an
operational name that is declared in the stdio.h library. Standard identifiers
can be re-declared and used by the programmer for other reasons, unlike
reserved words. However, after re-declaring the standard identifier for another
reason, it cannot be used for its original use.

Copyright © Open University Malaysia (OUM)


TOPIC 4 DATA TYPES AND VARIABLES 67

ACTIVITY 4.2

So far, you have been introduced to variables, reserved words and


standard identifiers. Can you think of the differences among them?

SELF-CHECK 4.3

The following identifiers are not valid. Provide reasons as to why each
one is not valid.

Identifier Reason
(a) 2001SeaGames
(b) SEA GAMES
(c) %passes
(d) width+height
(e) double

4.6 VARIABLE TYPES


Variables can represent different types of data. Data types that are used will
determine the variable type. Look at Table 4.3 below. The basic variable types
below are usually used in C programs.

Table 4.3: Basic Variable Types

Declaration Type
char Character
int Integer
float Real numbers
double Real numbers with high precision

Copyright © Open University Malaysia (OUM)


68 TOPIC 4 DATA TYPES AND VARIABLES

When a variable has a certain data type, it means that the variable can only
represent data of that particular type. For example, a variable of type integer, C
assumes that only whole numbers can be used to represent those values.

There are also extended data types that use a qualifier. Unsigned, signed,
short, long, unsigned short, signed short, unsigned long and
signed long, are qualifiers that exist in C.

4.7 VARIABLE DECLARATIONS


Variables can be used to keep input data and the calculation of results or logic
manipulations. Values that are kept by variables can change throughout program
execution.

Syntax:

data_type variable_name;

Next are some examples of variable declarations:

Table 4.4: Variable Declarations

Data Types Variable Names


int marks1, marks2, marks3, marks4;
double averageMarks;
char grade;

When declaring variables, the compiler will be notified of four items:

(a) Variable name;


(b) Variable type;
(c) Size of cell of variable in the memory; and
(d) Variable storage class.

Different variables are used to keep different types of data. Therefore, in the
variable declaration, it has to be mentioned what data type the variable will
contain. In the example above, identifier marks1, marks2, marks3 and
marks4 are declared as type int, identifier averageMarks is of type double

Copyright © Open University Malaysia (OUM)


TOPIC 4 DATA TYPES AND VARIABLES 69

and identifier grade is of type char. Notice in the example above, few variables
of the same type can be declared in a group, by separating the names of variables
with a comma.

Cell sizes will be discussed in the next topic. However, storage classes will not be
taught in this course.

4.8 VARIABLE ASSIGNMENT


We can assign values to a variable by using the following statement:

variable = value;

Consider the next example:

/* 1 */ int number1, number2, multipliedNumber;


/* 2 */ number1 = 10;
/* 3 */ number2 = 25;
/* 4 */ multipliedNumber = number1 * number2;

When statement /* 1 */ is declared, the memory cell assigned to each


variable is:

? ? ?

number1 number2 multipliedNumber

Statement /* 2 */ assigns 10 to variable number1. and

Statement /* 3 */ assigns 25 to variable number2.

? ? ?

number1 number2 multipliedNumber

Copyright © Open University Malaysia (OUM)


70 TOPIC 4 DATA TYPES AND VARIABLES

Next, statement /* 4 */ is executed. When assignment statement


multipliedNumber = number1 * number2; is executed, the right
side of „=„ will be calculated first, which involves performing multiplication
on values kept by variables number1 and number2. The result is 250 and
this value will be assignment to the variable multipliedNumber that is on
the left of „=„. Next is the result of the execution of statement /* 4 */.

10 25 250

number1 number2 multipliedNumber

SELF-CHECK 4.4

1. Given a program code segment below, what is the value of the


variable marks after all the statements have been executed?

int marks;
marks = 10;
marks = 20;
marks = 30;

2. Sketch the memory cell of the program code segment below.

int num, newValue


num = 9;
newValue = num;
newValue = -num;

3. State whether the variables below are valid. If they are not valid,
provide reasoning for this.

(a) tot_Credit_Hours (c) current_bill

(b) _car_tyres_types (d) 8_8_88

Copyright © Open University Malaysia (OUM)


TOPIC 4 DATA TYPES AND VARIABLES 71

4. State which of the identifiers below are (a) C reserved words (b)
standard identifier, (c) other valid identifier and (d) invalid identifier.

(a) void (d) printf

(b) MAXIMUM_BIL (e) xyz123

(c) double (f) char

Variables are used to keep data temporarily in memory.

Variables have characteristics such as name and type, and they are used to
represent a value.

Variables are named as an identifier that is declared by the user.

Variables can represent different types of data. There are three types of basic
data types: Integer Data Type (int) - which is to represent negative or
positive numbers, Character Data (char) - which is used to represent
characters such as letters, digits or special symbols, and Real Data which
has three types of data type that can be used for manipulating real data
numbers.

Variables can be used to keep input data and the calculation results or logic
manipulations.

C reserved words Syntax


Identifier Variables
Standard identifiers

Copyright © Open University Malaysia (OUM)


72 TOPIC 4 DATA TYPES AND VARIABLES

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

Copyright © Open University Malaysia (OUM)


Topic Constants
5
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Identify four types of constants that exist in C language; and
2. Differentiate the four types of constants by its writing.

INTRODUCTION
Constants are fixed values that cannot change throughout the execution of the
program. Constants can be categorised into many types according to its
respective data type, which is integer constant, real constant, character constant
or string constant. This topic will help you identify each constant more clearly.

5.1 INTEGER CONSTANT


Integer constant refers to a value (integer number) that is fixed. There are a few
types of integer constants. It is divided by the number system that is being used,
such as decimal, octal or hexadecimal system.

Example:

Decimal :0 2 99
Octal :0 07 074
Hexadecimal : 0X 0X1 0X7A

Copyright © Open University Malaysia (OUM)


74 TOPIC 5 CONSTANTS

5.2 REAL CONSTANTS


Real constants take their value just like real values in the number system. Float
dot notation or exponent notation, or both, can represent real constants. A suffix
is added to the floating-point constant, to specifically state the type. The floating-
point constant that does not have a suffix is categorised as type double. See the
examples in Table 5.1.

Table 5.1: Real Constants

Suffix Data Type Example


f or F float 3.7F
l or L long double 3.7L

Exponent notation for real constants can be written as 1.234567e5. This is the
same as the scientific notation 1.234567 x 105. The value is the same in this
equation:

1.234567 x 105 = 1.234567 x 10 x 10 x 10 x 10 x 10


= 1.234567 x 100000
= 123456.7 (floating point has moved to
the right five times)

SELF-CHECK 5.1

Change the exponent numbers to decimal numbers.

Exponent Numbers Decimal Numbers


(a) 10300e-2
(b) 1.23456e+6
(c) 123.45e+3

Copyright © Open University Malaysia (OUM)


TOPIC 5 CONSTANTS 75

A floating-point constant number can be made up of four parts. Let us see the
example in Figure 5.1 for a better idea of the four parts:

Figure 5.1: Four parts of a floating-point constant

If a floating point exists, the integer part, or divisor or both, must exist. If there is
no floating point, both the integer part and exponent must exist. Both “e”or
“E”are accepted as a sign of an exponent. Here are some examples of valid
floating-point constants. For example:

3.14159
-3.14159 (negative value)
314.159e-2F (float type)
0e0 (same value as 0.0)
1. (same value as 1.0, but more difficult to read)

Copyright © Open University Malaysia (OUM)


76 TOPIC 5 CONSTANTS

SELF-CHECK 5.2

1. Write the following numbers in scientific notation:

Decimal Numbers Scientific Notation


(a) 1300
(b) 123.45
(c) 0.00426

2. Give reasons why the real constants below are invalid.

Constant Reasons Why Invalid


(a) 3.14,129
(b) 314159
(c) 2E1.5
(d) 3E 12
(e) .e0

5.3 CHARACTER CONSTANT


The character constant is quite unique because it must be surrounded by single
quotes. For example:

‘A’ ‘z’ ‘?’ ‘5’

Character constants have certain integer values that are determined by the
character code or coding system, used by a computer. Most computers use ASCII
code representation to represent characters. For example: character ÂAÊ is valued
at 65 in the ASCII representation. Table 5.2 provides a sample of a part of the
ASCII table.

Copyright © Open University Malaysia (OUM)


TOPIC 5 CONSTANTS 77

Table 5.2: ASCII Table

Source: http://upload.wikimedia.org

5.4 STRING CONSTANT


In C language, string constants are made up of some characters surrounded by
double quotes. Below are some examples of string constants.

“OUM” “Information Technology” “X”


“” “1, Jln TTS 4/6, TTS” “123”

Any strings (including spaces) in between double quotes are a character array.
Arrays that have only numerical digits are not a number, but are numeric digit
arrays where no arithmetic operation can be performed on them.

Double quotes only surround the array; they are not part of the array. Each string
constant will have a null character (written as ‘\0’) automatically assigned by
the C compiler as an end of the character array. An example of the array “OUM”
is actually “OUM \0”. The length of a character array is the number of characters
in the array, plus a null character. Therefore, the length of the character array
“OUM” is 4.

Copyright © Open University Malaysia (OUM)


78 TOPIC 5 CONSTANTS

Since the character array has an end character, therefore a character array for a
character is not the same as a character constant. For example, the character array
“A” is not the same as the character constant ‘A’ because “A” is the combination
of a character constant ‘A’ and null character‘\0’.

5.5 SYMBOLIC CONSTANT


Symbolic constants are names that replace array characters. Array characters can
represent numeric constants, character constants or character array constants.
Therefore, symbolic constants allow the symbolic name to be shown at the
numeric constantsÊ location.

This symbolic constant is usually written at the beginning of the program.


Symbolic constant declaration is given as:

#define constant_name constant_value

Example:

#define PI 3.14
#define TRUE 1
#define NAME “ALI”

Notice that the symbolic constant is written using capital letters, to differentiate it
from other variables. Also, a symbolic constant declaration does not end with a
semicolon (;).

During compilation process, every symbolic constant will be changed with the
value that is declared. The advantage of using symbolic constant is that the name
of the symbolic constant explains its meaning in the code more clearly than the
value only.

Copyright © Open University Malaysia (OUM)


TOPIC 5 CONSTANTS 79

ACTIVITY 5.1

Discussion topics:

(a) What is a character array constant? How is it different from a


character constant? Can a character constant represent numbers?

(b) When writing numeric constants, what is the difference between


octal, decimal and hexadecimal constants?

(c) Can the escape characters be written as character constants? Give


examples.

SELF-CHECK 5.3

1. For each value below, state whether it is a valid constant. If valid,


state the type of constant. If invalid, state the reason.

(a) 1234567 (d) Âa/nÊ

(b) \t (e) 0Xabc

(c) „Z\0‰

2. Which one of the answers below is a valid integer, double, float, char
or string constant? For every valid constant, state the data type.

(a) 15 (d) .123F

(b) ÂXYZÊ (e) ÂxÊ

(c) Â*Ê (f) „X‰

Copyright © Open University Malaysia (OUM)


80 TOPIC 5 CONSTANTS

Constants include many types of constants such as integer and fixed point
constants, character constants such as ‘A’ and character array constants
such as “ABC”.

Character constant and character array (string) constant differ from each
other.

An integer constant refers to a value (integer number) that is fixed.

Real constants take their value just like real values in the number system.
Float dot notation or exponent notation, or both, can represent real
constants.

The character constant is quite unique because it must be surrounded by


single quotes.

String constants are made up of some characters surrounded by double


quotes.

Character constant Floating-point


Constants Integer constants
Divisor Null character
Escape sequence Real constants
Exponent String constant
Exponent numbers

Copyright © Open University Malaysia (OUM)


Topic Input and
6 Output
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Use the function printf() to produce output data to the screen
using a particular format;
2. Use the function scanf() to produce input data from the keyboard
using a particular format; and
3. Display output according to program segments.

INTRODUCTION
We have looked at some output functions in previous topics. These functions
send data to the output device (usually the computer screen) using the formats
that are given. Technically, printf() and scanf() functions are not part of C
language, but are part of the C system. Both these functions exist in the C library
and are kept together with the C system. Even though the object codes for the
functions are made available by the C system, it is your responsibility as a
programmer to declare this function when you want to use it in your program.

ANSI C has introduced a new method of declaring embedded functions, known


as function prototypes. Function prototypes for functions that are embedded in
the C standard library can be found in the header files. Function prototypes for
the functions printf() and scanf() are found in the header file stdio.h. In
the code examples in this topic, we will see how the header file stdio.h is
inserted.

Copyright © Open University Malaysia (OUM)


82 TOPIC 6 INPUT AND OUTPUT

6.1 printf() FUNCTION


When translated, the function printf() is sometimes known as a function to
print. We need to remember that printing here means printing to the computer
screen and not to the printer.

The function format for printf()is:

printf(output_format [, value_list]);

output_format: An array that will determine the form of the output depending
on the value list.

value_list: Can be made up of variables, constants, statements or


combinations.

6.1.1 Printing Strings


Data that is easiest to print or output is called a string. We will just need to write
the string that needs to be printed as the output_format in the
printf()function. The string will then print as we have written it. As an
example, the following statement:

printf(“Welcome to OUM.”);

Will produce the following output on the screen:

Welcome to OUM.

Notice that all the characters in the double quotes „ ‰ are printed, including the
spaces.

The printf() function does not execute a new line command automatically.
This means that the cursor placed on the screen will be at the end of the last
character of the sentence printed.

The next printf() statement will be printed starting from the cursor
placement earlier. Therefore, an escape sequence Â\nÊ is put at the end of the
statement if the cursor is to be on a new line.

Copyright © Open University Malaysia (OUM)


TOPIC 6 INPUT AND OUTPUT 83

Other than the escape sequence Â\nÊ there are other characters that can be used in
the string output_formats as given in Table 6.1.

Table 6.1: Escape Sequence Characters in Output Format

Escape Sequence Meaning


'\a' Bell
'\b' Backspace
'\f' Form feed
'\n' New line
'\r' Carriage return
'\t' Tab
'\v' Vertical tab
'\\' \
'\'' '
'\"' "
'\055' Octal character value 055
'\xA9' Hexadecimal character value 0xA9
'\0' Null character

ACTIVITY 6.1

1. Write a simple program using the statements below:

printf(“Line 1”);
printf(“Line 2”);

What is the output?

2. Add „\n‰ to the first statement:

printf(“Line 1\n”);
printf(“Line 2”);

3. Write the output to the segment code below:

printf(“Line 1\n Line 2\n\n”);


printf(“Line 3\n”);

Copyright © Open University Malaysia (OUM)


84 TOPIC 6 INPUT AND OUTPUT

6.1.2 Printing Values


If a printf() function call has a list of values to be printed, then the
output_format must use the specifications for those values. Consider the
specification list given in Table 6.2 below:

Table 6.2: Output Specification List

Specification Meaning
%s Output a string
%c Output a character
%d Output an integer
%f Output float/double
%e Output float/double using scientific notation

Next, we will see how to use each output specification.

(a) %s Specification
Assume name is a string variable that can be assigned the value Najwa
Mawaddah. Consider how the specification %s interprets the variable to
output in Program 6.1.

Program 6.1

/* Prints name */
#include <stdio.h>

void main() {
char name[] = “Najwa Mawaddah”;

printf(“%s”, name);

Do you know what the output will be? Yes, the output will be:

Najwa Mawaddah

The variable name will be compared to the specification %s and then


output.

Copyright © Open University Malaysia (OUM)


TOPIC 6 INPUT AND OUTPUT 85

(b) %c Specification
Now, let us look at the %c specification. Do you know the use of this
specification? This specification will be compared to the character value
that will be printed. Study Figure 6.1 to understand this concept.

Figure 6.1: How %c specification works

Every character constant will be compared with the specification sequence


and output. The value list can also be a list of variables. The same
comparison can be made.

character1 = ‘O’;
character2 = ‘U’;
character3 = ‘M’;
printf(“%c %c %c “,character1, character2,
character3);

(c) %d and %f Specification


When we want to print a numeric value, we have to use the output
specification that is suitable to the type of value. Specification %d is used to
print integer values, whereas %f specification is used to print real numbers.
Program 6.2 illustrates how to print integer and real numbers.

Copyright © Open University Malaysia (OUM)


86 TOPIC 6 INPUT AND OUTPUT

Program 6.2

/* Printing integer and real values */


#include <stdio.h>
void main() {
int value1;
float value2;
value1 = 10;
value2 = 5.55;

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


printf(“Second value = %f\n”, value1 – value2);

At the second printf() function call, the statement value1 – value2 will be
evaluated first and the result is 4.45. This value will fit the %f specification in
the string given. Since the float data type has a precision of 6, therefore, the
output obtained is in precision of 6 decimal spaces. The output displayed is as
follows:

First value = 10
Second value = 4.450000

Output specification can be combined into one printf() statement. You can
refer to relevant online websites to see how this can be done.

Copyright © Open University Malaysia (OUM)


TOPIC 6 INPUT AND OUTPUT 87

ACTIVITY 6.2

1. Write and compile the computer program below:

/* Program with specification combination output */


#include <stdio.h>

void main () {
char name[] = “Najwa Mawaddah”;
int age = 20;
float height = 1.53;

printf(“%s %s %s\n”, “Name”, “Age”, “Height”);


printf(“%s %s %s\n\n”, “~~~~~~~~~~~~”,
“~~~~~~~~~~”, “~~~~~~~~~~”);
printf(“%s %d %f\n”, name, age, height);
}

2. Change the printf() statement with the following and execute the
program:

printf(“%15s %10s %10s\n”, “Name”, “Age”, “Height”);


printf(“%15s %10s %10s\n\n”, “~~~~~~~~~~~~”,
“~~~~~~~~~~”, “~~~~~~~~~~”);
printf(“%15s %10d %10.2f\n”, name, age, height);

3. Given the declaration statement below:

int count = 5;
float tot = 10.5;

printf(“\n%s%5d\n%s%12f\n\n”, “Calculation:”, count,


“ Total:”, tot);

What is printed?

4. What is the output produced by the following statements?

(a) printf(“*\t***\t*****\n”);

(b) printf(“*\b***\n*****\n”);

(c) printf(“*\r***\n*****\n”);

Copyright © Open University Malaysia (OUM)


88 TOPIC 6 INPUT AND OUTPUT

5. Given the following declaration:


int i;
char c;
Write the output that will be produced by each of the printf()
statements below:
i = 36;
c = 64;
printf(“%d %c\n”, i, c);
printf(“%c %d\n”, i, c);

6.2 scanf() FUNCTION


In this section, we will learn how to receive input with the scanf() function.
This function allows us to interact with the written program. Input is from the
keyboard.

What happens here is that the value that is input will be matched to the variable,
based on the formats given. Next, the value represented by the variable will be
used in the program and usually produces output. Let us take a look at the
general form for the scanf()function:

scanf(input_format [, variable_list]);

scanf()function needs the input_format which is a string that will determine


the form of input string. This string is similar to the output_format in the
printf()function.

6.2.1 Variable Input


For basic variable (integer, real and character) input, we need to list the address
location for the variables. The address location stated here uses the & operator for
list variables. The following statement will read two inputs:

scanf(“%c%d”, &character, &num);

Copyright © Open University Malaysia (OUM)


TOPIC 6 INPUT AND OUTPUT 89

Assume that character and num are variables of type char and int
respectively. The first input is a character value that will be kept in the memory
location called character. The second input is an integer value that is kept in
the memory location for the variable num.

Program 6.3

/* Program to modify date format */


#include <stdio.h>

void main () {
int day, month, year;

scanf(“%d %d %d”, &day, &month, &year);


printf(“Day: %d, Month: %d, Year: %d”, day, month,
year);
}

Observe Program 6.3 above. When the program is executed, it will wait for us to
enter a value for day, month and year.

Assume the input entered is:

11 9 2001

Then the printf() statement will print the output as follows:

Day: 11, Month: 9, Year: 2001

One main problem in the program above is that the programmer assumes that
the user of the program knows what values are to be entered. Normally, when
writing programs, we will display a suitable message to inform the user of the
type of values to enter.

SELF-CHECK 6.1

printf() function is frequently used with the scanf()function.


Where is this function used?

Copyright © Open University Malaysia (OUM)


90 TOPIC 6 INPUT AND OUTPUT

ACTIVITY 6.3

1. Write, compile and execute the following program which will input
3 name initials and age.

/* Program to input 3 name initials and age */


#include <stdio.h>
void main () {
char name1, name2, name3;
int age;
printf(“Enter three characters that represent
your name’s initials“);
scanf(“%c%c%c”, &name1, &name2, &name3);
printf(“Enter your age “);
scanf(“%d”, &age);
printf(“Hello %c.%c.%c”,name1,name2,name3);
printf(“Next year your age will be %d”,age+1);
}

2. If the data input is as follows:


ANSI C?

what is the output of the statements below?


char a, b, c, d, e, f;
scanf(“%c%c%c%c%c%c”, &a, &b, &c, &d, &e, &f);
printf(“%c%c%c%c%c%c”, a, b, c, d, e, f);
printf(“%c%c%c%c%c%c”, a, b, c, d, f, e);

Copyright © Open University Malaysia (OUM)


TOPIC 6 INPUT AND OUTPUT 91

The function printf() is sometimes known as a function to print on the


computer screen.

Data that is easiest to print or output is a string.

If a printf() function call has a list of values to be printed, then the


output_format must use the specifications for those values.

The %c specification will be compared to the character value that will be


printed.

Specification %d is used to print integer values, whereas %f specification is


used to print real numbers.

The scanf() function allows us to interact with the written program.


Input is from the keyboard.

%c specification %s specification
%d specification printf() function
%f specification scanf() function

Copyright © Open University Malaysia (OUM)


Topic Operators
7 and
Expressions
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Apply five types of operators in writing appropriate statements;
2. Write arithmetic expressions using C syntax; and
3. Evaluate and write expressions to be used in single, double or
compound assignment statements.

INTRODUCTION
When you studied mathematics in secondary school, you would have come
across symbols like +, -, x, < and >. These symbols are used to manipulate data
and are known as operators. Before we write programs that are more complex, it
would be good to remember some symbols that can be used to manipulate the
data. In C language, there are many types of operators. There are arithmetic
operators, relational operators, logic operators, increment and decrement
operators, cast operators and conditional operators. This topic will describe these
operators in detail.

7.1 BASIC ARITHMETIC OPERATORS


To enable our programs to do arithmetic calculations, we need arithmetic
operators. Basic arithmetic operator concepts in C language are the same as the
arithmetic operators that were taught in mathematics in school. Table 7.1 shows
the operator symbols and examples of basic arithmetic operations in C.

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 93

Table 7.1: Operator Symbols and Examples of Basic C Arithmetic Operations

Symbol Meaning Expression Result


+ Add 25 + 8 33
- Minus 120 – 64 56
* Multiply 3 * 7 21
/ Divide 66 / 6 11
% Modulus 66 % 6 0

Most of the symbols above behave in the same way as normal arithmetic
operators. Addition, minus, multiplication and a few cases of division operators
would give the same result as normal arithmetic operators.

Therefore, the addition, minus and multiplication operators will not be discussed
in detail. Please recall the basic concepts of addition, subtraction and
multiplication from your mathematics subject for this.

Please note that the symbol used in the multiplication operation for C is * and not
x.

The division operator in C is quite different from the normal division operation.
There are two types of division operators, which are the integer division and the
real division. Both types of division use the same operation symbol which is /.
However, the operands differentiate the type of division.

(a) Integer Division


Integer division happens when both the operands are of integer type.
Operands can either be a constant or a variable. Let us look at the example
below:

8/2 /* constant divide constant */


98 / value /* constant divide variable,
value must be of int type */
total / 3 /* variable divide constant,
total must be of int type */
total / count /* variable divide variable,
total and count must be of int type */

Copyright © Open University Malaysia (OUM)


94 TOPIC 7 OPERATORS AND EXPRESSIONS

The division result of both the operands is determined. If the division is not
a round number (that is, it has a decimal value), the remainder of the
division is ignored. The result is truncated to an integer value. Consider the
example given in Table 7.2 below:

Table 7.2: Integer Division Operation Example

Operation Calculated Result Result


64 / 8 8 8
12 / 5 2 remainder 2 2
25 / 3 8 remainder 1 8

(b) Real Division


Real division is done when one or both of the operands have a real value.
The division operation done is the same as normal arithmetic division. The
result of the division is a real value.

Table 7.3: Real Division Operation Example

Operation Result
5 / 2.5 2.0
5.5 / 2.0 2.75
5.0 / 10 0.5

Observe Table 7.3 above. In the first example, we immediately get the division
value of 2 and since the division is a real division (one of the operands is a real
number), the result of the division has to be written as a real number, which is
2.0.

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 95

SELF-CHECK 7.1

For each question below, choose the right answer.

1. Consider the program segment below:


int result;
result = 15 / 4;

Which one of the answers given below would keep the value of
result?

(a) 3 (c) 3.7

(b) 3.0 (d) 3.75

2. Consider the program code segment below:

printf(“%.0f”, 15 / 4);

Which one of the answers below would be displayed?

(a) 3 (c) 3.75

(b) 3.0 (d) None of the above

3. Consider the program segment below:

printf(“%.1f”, 15 / 4.0);

Which one of the answers below would be displayed?

(a) 3.0 (c) 3.75

(b) 4.0 (d) None of the above

Modulus operation would have the result of the remainder of the integer
division. The symbol used for this operation is %. Both the operands in this
operation must be integer operands.

Copyright © Open University Malaysia (OUM)


96 TOPIC 7 OPERATORS AND EXPRESSIONS

Table 7.4 shows examples of the modulus operation:

Table 7.4: Modulus Operation Examples

Operation Calculated Result Result


5%3 1 remainder 2 2
7%2 3 remainder 1 1
12 % 2 6 remainder 0 0

SELF-CHECK 7.2

Consider the program segment below:

printf(“%d”, 15 % 4);

Which one of the answers below would be displayed?

(a) 3 (c) 3.7

(b) 3.0 (d) None of the above

7.2 ARITHMETIC EXPRESSIONS


C arithmetic expressions are a combination of one or more arithmetic operations.
These arithmetic expressions can represent algebra expressions. Below are a few
examples of arithmetic expressions in C language.

5 + 6
14 * 5 * 2
21 - 6 + 7 * 4 / 2
7.5 * (2.0 - 4.52)

Before we can write algebra expressions in C arithmetic expression form, we


need to know how the arithmetic expression is calculated. The most important
point in evaluating arithmetic expressions is the precedence level.

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 97

7.2.1 Precedence Level


Precedence level of C arithmetic expressions would determine the arithmetic
operation sequence in solving the problem. For the five basic arithmetic
operations that we have seen, the precedence level is as in Table 7.5 below:

Table 7.5: Operator Precedence Levels

Precedence Operation
High *, /, %
Low +, -

Arithmetic expressions are evaluated according to the precedence levels above.


The operators at the high precedence level will be evaluated first. Look at the
example below:

3 + 10/3

3 + 3

Operator / has a higher precedence level, therefore it is evaluated first. The result
from the 10/3 division would be the operand for the addition operation and the
result is 6.

ACTIVITY 7.1

What happens if the precedence levels are the same?

10 % 6 * 3

If you do not want the arithmetic expression evaluated using the precedence
levels, we need to write the expression using brackets. Expressions in the
brackets would be evaluated first.

Copyright © Open University Malaysia (OUM)


98 TOPIC 7 OPERATORS AND EXPRESSIONS

To ensure the operator with a lower precedence is executed first, the solution is
to use brackets (). For example:

(12 6) * 4
=6*4
= 24

ACTIVITY 7.2

Can you show the steps required to solve the problem below?

(9 (3 + 2)) * 3

7.2.2 Writing Arithmetic Expressions in C


When we write normal arithmetic expressions (algebra expressions) in the form
of C arithmetic expression, we need to be careful on the precedence levels. If
there is a mistake, the result of the evaluation might not be what we want it to be.
Consider the algebra expression example in Table 7.6 written in C arithmetic
expression.

Table 7.6: Changing Algebra Expression to C Expression

Algebra Expression C Arithmetic Expression


14 5 + 6 14 - 5 + 6

8
16 16 - 8 / 2
2
15 5 7
(15 + 5 +7) / 2
2

In order to avoid confusion in writing C arithmetic expressions, we use brackets.


In the third example in Table 7.6, if the C arithmetic expression is written without
brackets (that is as 15 + 5 + 7 / 2), the result will be different from the
original expression. This expression will be evaluated as:

7
15 5
2

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 99

SELF-CHECK 7.3

Given the algebra expression below:

1
1 X2

which of these is the equivalent C arithmetic expression?

(a) 1/1+x*x (c) 1/(1+x*x)

(b) 1/1+(x*x) (d) 1/(1+x)*x

7.3 ASSIGNMENT STATEMENT (=)


In many programming languages, assignment statement is a fundamental
component. In this section, we will discuss assignment statement using the C
languages.

7.3.1 Expression Assignment Statement


Previously, we have been introduced to assignment statements with values.
Assignment statements can also be used with expressions.

variable = expression;

The expression part of the assignment statement is an arithmetic expression or


logic expression (which will be discussed later). The computer will execute this
expression (on the right) and the value is assigned to the variable (on the left).
Expression is not necessarily a constant. It can be a combination of variables and
constants. Expressions should be able to be calculated. This means that if a
variable is used, that variable should be assigned a value before being used in an
expression. Consider example Program 7.1 below:

Copyright © Open University Malaysia (OUM)


100 TOPIC 7 OPERATORS AND EXPRESSIONS

Program 7.1

/* Calculate body weight index */


#include <stdio.h>

void main() {
float weight, height, bodyweightIndex;

weight = 55.5; /* value assignment */


height = 1.55; /* value assignment */
bodyweightIndex = weight /(height * height);
/* expression assignment */
printf(“Your body weight index is %.2f\n”,
bodyweightIndex);
}

ACTIVITY 7.3

Using your computer,


(a) Write, compile and execute Program 7.1.
(b) Change Program 7.1 by allowing the user to input the weight and
height values.

7.3.2 Multiple Expression Assignment Statement


In C assignment statements, in addition to variables and constants, expressions
can also be other expressions. This means that we can form several assignment
statements in one statement such as:

a = b = c = 40;

Observe the example above. Remember that any assignment statement will solve
the expression on the right and assign the value of the expression to the variable
on the left. Look at how the statements are worked out:

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 101

x = y = (z = 10) /* assign value 10 to variable z */


x = (y = (z = 10)) /* expression z = 10 will have value
10.
This value will be assigned to y so
that y is 10 */
(x = (y = (z = 10))) /* expression value y=z=10 is
assigned to x so that x is 10*/

Multiple statements are useful when we want to give initial values to some
variables that are newly declared, that is before they are used. Using the multiple
expression statements, we do not have to write one assignment statement for
every variable. This will reduce the lines of the program code.

The example below shows the variable age and numOfSiblings assigned the
initial value of 0 in one multiple expression. The same goes for the variable
weight and height which are assigned the initial value of 0.0 in one multiple
expression.

int age, numOfSiblings;


float weight, height;

/* giving initial values to variables */


age = numOfSiblings = 0;
weight = height = 0.0;

SELF-CHECK 7.4

Which of these values would be the value assigned to y by the


following statements:

float x, y;
y = x = 10.0 * 2;

(a) 10.000000 (c) 20.000000

(b) 20 (d) None of the above

Copyright © Open University Malaysia (OUM)


102 TOPIC 7 OPERATORS AND EXPRESSIONS

7.3.3 Compound Assignment Statement


In writing programs, sometimes we would like to modify a variableÊs value,
where the variableÊs original value is added to or multiplied by another value
and is assigned back to the original variable. It is normally written as:

weight = weight + 1.5;

If the value of weight originally is 45, the expression on the right (weight +
1.5) will result in the value 46.5 (see (1) in Figure 7.1). This value is assigned to
the variable weight (see (2)). It means that the original weight (45) will be
replaced with the new value which is 46.5 (see state after (2)).

Figure 7.1: Compound statement calculation process [weight=weight+ 1.5]

In C, statements like these can be written using compound operators. Table 7.7
below shows compound operators.

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 103

Table 7.7: Examples of Compound Operators

Operator Example Meaning


+= cnt += 5; cnt = cnt + 5;
-= cnt -= 5; cnt = cnt - 5;
*= cnt *= 5; cnt = cnt * 5;
/= cnt /= 5; cnt = cnt / 5;
%= cnt %= 5; cnt = cnt % 5;

Precedence level for the compound operators is the lowest. This means that this
operator will be evaluated last of all while solving some expressions. Observe the
statement below:

points += currentPoints + bonus * currentPoints;

Based on the precedence level, the statement above is solved in this manner:

points + = currentPoints + bonus + currentPoints;


points = points + currentPoints + (bonus * currentPoints)

SELF-CHECK 7.5

Assume that x has the value of 1 0 . 0 . What is the value that is assigned to x
after the statement below is executed?

x = x - 20.0;

(a) -10 (c) -20

(b) -10.0 (d) 10

Copyright © Open University Malaysia (OUM)


104 TOPIC 7 OPERATORS AND EXPRESSIONS

7.4 RELATIONAL OPERATOR


Arithmetic operators are used to represent arithmetic formulas, to solve
problems that are associated with it. Other than arithmetic operators, C also
provides operators that are used to compare data, known as relational operators.

The task of these operators is to compare the values of two expressions; either
equal to, not equal to, less than, or more than. Table 7.8 below lists the relational
operator symbols and their meanings.

Table 7.8: Examples of Relational Operator Symbols and Relational Expressions

Operator Meaning Relational Expression Value


< Less than 6 < 9 1
<= Less than or equal to 12<=13 1
> More than 7 >10 0
>= More than or equal to 9 >= 5 1
== Equal to 7 == 5 0
!= Not equal to 6 != 5 1

These operators have two operands that can be made up of a variable, constant
or a combination of both. A relational expression is created from a relational
operation. Relational expressions will return the value of 1 if true and 0if false.

SELF-CHECK 7.6

Assume that x has the value of 15.0 and y has the value 25.0. What is the
value for these relational expressions?

Expression Value
x! = y
x >= y - x
x < x
x == y = x - y

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 105

7.5 LOGICAL OPERATOR


Relational operators can only test one case at a time. If we want to test a few cases
that are related, to get a result, we can use the logical operator. Table 7.9 below
lists the logical operators.

Table 7.9: Logical Operators

Symbol Meaning
&& and
|| or
! not

Operator && and must have two operands, whereas the operator ! has only
one operand. The following Table 7.10 shows how logical operator functions. The
table is known as the truth table. In the following table, 1 represents True and 0
represents False.

Table 7.10: Logical Operator Examples

a B a && b a b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1

A !a
0 1
1 0

Logical operators can be combined with relational operators to form a compound


expression that is more complex. In evaluating the logical expression, precedence
levels for the relational operator is higher than the logical operator. Assuming
that a = 1, b = 5, c = 15 and d = 25, notice how these logical
expressions are evaluated:

Copyright © Open University Malaysia (OUM)


106 TOPIC 7 OPERATORS AND EXPRESSIONS

(a) (a >= 1) && (b == 5)


<=> (1 >= 1) && (5 == 5)
<=> 1 && 1
<=> 1

(b) (c >= (b * 3)) (a == 3)


<=> (15 >= (5 * 3)) (1 == 3)
<=> (15 >= 15) (1 == 3)
<=> 1 0
<=> 1

(c) ! (c > a)
<=> ! (15 > 1)
<=> ! 1
<=> 0

(d) ! (a < b) (c > d))


<=> ! (1 < 5) (15 > 25))
<=> ! ( 1 0 )
<=> ! 1
<=> 0

SELF-CHECK 7.7

If a = 5, b = 10, c = 15 and valid has the value of 1, what is the value of the
expressions below?

Expression Result
(a) c = = a + b ! valid
(b) a! = 7 && valid c >= 6

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 107

7.6 INCREMENT AND DECREMENT


OPERATORS
Increment and Decrement operators are unique operators. Table 7.11 below
shows the operators.

Table 7.11: Increment and Decrement Operators

Symbol Meaning
++ Add 1 to the operand
-- Subtract 1 from the operand

This operator needs one operand only. That operand is usually an integer
variable. Do you still remember integer variables? If you do not, please refer to
Chapter 5. It can also be written in the form of an assignment statement. Table
7.12 below explains the meaning of increment, decrement and the statements that
are equivalent to them.

Table 7.12: Increment and Decrement Expressions

Expression Meaning Statement


i++ i = i + 1 i += 1;
++i i = i + 1 i += 1;
i-- i = i - 1 i -= 1;
--i i = i - 1 i -= 1;

To increase or decrease the value of one variable, the position of the operator
does not matter, whether it is a prefix or postfix of the variable. However, when
the operator is combined to other operators in an expression, the position would
determine the value returned. Look at Table 7.13 below:

Table 7.13: Sequence of Increment and Decrement Operator

Expression Meaning
i++ Value i increased after being used in expression
++i Value i increased before being used in expression
i-- Value i decreased after being used in expression
--i Value i decreased before being used in expression

Copyright © Open University Malaysia (OUM)


108 TOPIC 7 OPERATORS AND EXPRESSIONS

Also consider when we use the operator ++i (prefix increment) as shown below:

i = 5;
j = ++i - 2;

In this statement, the initial value for i (which is 5) is incremented before


(making it 6). Then, the new value of i is subtracted by 2; which makes j
become 4. This statement is similar to the statement given below:

i = 5;
i++;
j = i - 2;

ACTIVITY 7.4

1. What is printed?

i = 3;
printf(“%d\n”, i);
printf(“%d\n”, --i);
printf(“%d\n”, ++i);

2. Write the output for the two sets of subprograms below:

Subprogram Output

Postfix decrement

i = 7; printf(“%d\n,i);
printf(%d\n”,i--);
printf(%d\n,i);

Prefix decrement

i = 7; printf(“%d\n,i);
printf(%d\n”,--i);
printf(%d\n,i);

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 109

3. If

Expression j Value
i = 5
j = ++i –2;

Therefore j = ?

i = 5, j = 3;
i++;
j = i – j

Therefore j = ?

7.7 CAST OPERATOR


Sometimes in an expression, we need to combine different types of variables. In
this situation, C does the variable conversions automatically. The type that is
smaller in range is changed to the type that is larger. Automatic changes like this
often happen in arithmetic expressions, combining variables of integer and real
type. Observe the example below:

int total, count;


float average;
.....
average = total / count;

In the statement average = total / count; we need to calculate the


average value and possibly that the average value is of real type. Therefore, we
will declare the variable average as float type.

When the value of total = 10 and count = 2, therefore, the average value
obtained will be 5.0; and when the value of total = 15 and count = 2,
average value obtained is 7.0! In this case, both the operands for the divide
operation are of type integer. So, integer division is carried out and would result
in integer value. Even though this integer value is assigned to a real value, the
decimal part is truncated.

Copyright © Open University Malaysia (OUM)


110 TOPIC 7 OPERATORS AND EXPRESSIONS

Hence in similar cases, we need to do a real division operation. The easiest way
to do this is by changing the value of total variable and/or count to type
float before the division operation is done using the cast operator.

Take note here! We do not redefine total and count as type float because we
want to retain the value as an integer for the other parts of the program. The
changes made are as follows:

average = ((float) total) / ((float) count);

The changes are made only at the parts where they are needed. The cast operator
would change the value of total and count temporarily to a real value.
Therefore, the division that is executed will be real division and will result in a
real value too.

SELF-CHECK 7.8

Consider the program segment below:

printf(“%f\n”, (float) 15 / 4);


printf(“%.1f\n”, (float)15 / 4);
printf(“%.2f\n”, 15 / (float) 4);

What will be printed?

7.8 CONDITIONAL OPERATOR


?: operator is known as conditional operator. It is used for evaluating
conditional expressions. The syntax used is:

expression_1 ? expression_2 : expression_3;

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 111

Generally, to get a value for the conditional expression above, we first need to
determine whether expression_1 is true or false. If expression_1 is true, then
the value of the conditional operator is expression_2, but if expression_1 is
false, the value of the conditional operator is expression_3.

expression_1? expression_2 : expression_3


True
False

Consider the following example:

m ? mx + c : c;

In the example above, m value will be determined. If m is true (non-zero), the


value for the entire conditional expression is mx + c. On the other hand, if m is
false, the value for the entire conditional expression will be the value of c.
Therefore, if m is true and we execute the statement:

y = m ? mx + c : c;

y will be assigned the value of mx + c. However, if m is false, then y will be


assigned the value of c. The statement above is actually a shorter version of the
statement below:

if (m)
y = mx + c;
else
y = c;

Copyright © Open University Malaysia (OUM)


112 TOPIC 7 OPERATORS AND EXPRESSIONS

ACTIVITY 7.5

1. Consider the program segment below:

int x = 3;
int y = 5;
int min;

printf(“%d\n”, min = y < x? y: x);

What is printed?

2. For each of the algebra expressions below, write the equivalent C


arithmetic expression.

(a) b2 - 4ac (b) a (b+c)

3. Assume that i, j and k are integer variables with i = 5 and


j = 3. What are the values of the following statements?

Expression Value
(a) k = j ++;
(b) k = i * j-;
(c) k = ++ j;
(d) k = i * -j;

ACTIVITY 7.6

Write a program to do the following:

(a) Accept the value of temperature in Celsius unit and change it to a


value in Fahrenheit.

(b) Accept the value of a radius and calculate the area and
circumference.

Copyright © Open University Malaysia (OUM)


TOPIC 7 OPERATORS AND EXPRESSIONS 113

Special arithmetic operators are normally used to write programs.

Integer division happens when both the operands are of integer type.
Operands can be a constant or a variable.

Real division is done when one or both of the operands have a real value.

C arithmetic expressions are a combination of one or more arithmetic


operations.

Precedence level of C arithmetic expressions would determine the arithmetic


operation sequence in solving the problem.

Besides arithmetic operators, C also provides operators that are used to


compare data, which are known as relational operators.

Compound statement Precedence level


Conditional operator Relational operator
Integer operands Variable
Logical operator
 

Copyright © Open University Malaysia (OUM)


xxvi COURSE ASSIGNMENT GUIDE

Copyright © Open University Malaysia (OUM)


APPENDIX

Copyright © Open University Malaysia (OUM)


116 APPENDIX

Copyright © Open University Malaysia (OUM)


APPENDIX 117

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)
118 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 119

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)


120 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 121

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)


122 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 123

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)


124 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 125

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)


126 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 127

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)


128 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