BITH131
BITH131
BITH131
Computer Programming
Mount Pleasant
Harare, ZIMBABWE
the errors), they still help you learn the correct thing as the tutor may dwell on matters irrelevant to the
as much as the correct ideas. You also need to be ZOU course.
open-minded, frank, inquisitive and should leave no
stone unturned as you analyze ideas and seek
clarification on any issues. It has been found that Distance education, by its nature, keeps the tutor
those who take part in tutorials actively, do better in and student separate. By introducing the six hour
assignments and examinations because their ideas are tutorial, ZOU hopes to help you come in touch with
streamlined. Taking part properly means that you the physical being, who marks your assignments,
prepare for the tutorial beforehand by putting together assesses them, guides you on preparing for writing
relevant questions and their possible answers and examinations and assignments and who runs your
those areas that cause you confusion. general academic affairs. This helps you to settle
down in your course having been advised on how
Only in cases where the information being discussed to go about your learning. Personal human contact
is not found in the learning package can the tutor is, therefore, upheld by the ZOU.
provide extra learning materials, but this should not
be the dominant feature of the six hour tutorial. As
stated, it should be rare because the information
needed for the course is found in the learning package
together with the sources to which you are referred.
Fully-fledged lectures can, therefore, be misleading
Note that in all the three sessions, you identify the areas
that your tutor should give help. You also take a very
important part in finding answers to the problems posed.
You are the most important part of the solutions to your
learning challenges.
vi
5.5. Real Data Type ......................................................................................................... 66
5.6. Summary .................................................................................................................. 68
Unit 6 Constants ............................................................................................................... 69
6.0. Introduction............................................................................................................. 69
6.1. Objectives ............................................................................................................... 69
6.2. Integer Constant ...................................................................................................... 69
6.3. Real Constants ........................................................................................................ 70
6.4. Character Constant.................................................................................................. 70
6.5. String Constant........................................................................................................ 71
6.6. Summary ................................................................................................................. 73
Unit 7 Input and Output .................................................................................................... 76
7.0. Introduction .............................................................................................................. 76
7.1. Objectives................................................................................................................. 76
7.2.1 Printing strings ................................................................................................ 77
7.2.2 Printing values ................................................................................................ 79
7.3. The Scanf() Function................................................................................................. 83
7.3.1 Variable input.................................................................................................. 84
7.4. Summary .................................................................................................................. 86
8.0. Introduction............................................................................................................. 87
8.1. Objectives ............................................................................................................... 87
8.2. Basic Arithmetic Operators..................................................................................... 87
1. Consider the programme segment below:................................................................... 90
8.3. Arithmetic Expressions........................................................................................... 91
8.3.1 Precedence level.............................................................................................. 91
8.3.2 Writing arithmetic expressions in C................................................................ 92
8.4. Assignment Statement (=)....................................................................................... 94
8.4.1 Expression assignment statement.................................................................... 94
8.4.2 Multiple expression assignment statement ..................................................... 95
8.4.3 Compound assignment statement.................................................................... 96
vii
8.5. Relational Operator................................................................................................. 98
8.6. Logical Operator ..................................................................................................... 99
8.7. Increment and Decrement Operators .................................................................... 101
8.8. Cast Operator ........................................................................................................ 103
8.9. Conditional Operator ............................................................................................ 104
8.10. Summary ........................................................................................................... 106
Unit 9 Selection Central Structure ................................................................................... 107
9.0. Introduction ............................................................................................................ 107
9.1. Objectives............................................................................................................... 107
9.2. The if Statement...................................................................................................... 107
9.3. The Switch and Break Statement.............................................................................. 113
9.4. Summary ................................................................................................................ 116
Unit 10 CASE STUDY......................................................................................................... 117
10.0. Introduction....................................................................................................... 117
10.1. Objectives ......................................................................................................... 117
10.2. Problem Statement ............................................................................................ 117
10.3. Analysis............................................................................................................. 118
10.4. Data Requirements............................................................................................ 119
10.5. Summary ........................................................................................................... 126
Unit 11 Repetition ......................................................................................................... 127
viii
11.5. The Continue Statement.................................................................................... 139
11.5.1 The continue flow control statement............................................................. 140
11.6. The Break Statement......................................................................................... 141
11.6.1 The break control flow statement.................................................................. 141
11.7. Nested Loops .................................................................................................... 142
11.7.1 Tracing nested loops ..................................................................................... 142
11.8. Summary ........................................................................................................... 146
12.0. Introduction....................................................................................................... 148
12.1. Objectives ......................................................................................................... 148
12.2. What is Function? ............................................................................................. 148
12.3. Calling a Function............................................................................................. 149
12.3.1 Calling a function without parameter............................................................ 150
12.3.2 Calling a function with parameters ............................................................... 150
12.3.3 The C standard library................................................................................... 151
12.4. Writing a Function ............................................................................................ 153
12.4.1 Writing a function without parameter ........................................................... 154
12.4.2 Writing a functions with parameters ........................................................... 156
12.4.3 Returning values .......................................................................................... 157
12.4.4 Variable scope............................................................................................... 160
12.4.5 Function prototype ........................................................................................ 167
12.5. Recursion .......................................................................................................... 171
12.6. Functions and Top Down Design...................................................................... 175
12.7. Summary ........................................................................................................... 179
Unit13 File Manipulations................................................................................ 180
13.0. Introduction....................................................................................................... 180
13.1. Objectives ......................................................................................................... 180
13.2. File Support in C.............................................................................................. 180
13.2.1 File format types ........................................................................................... 180
13.2.2 File access types............................................................................................ 181
13.3. File Operations.................................................................................................. 181
ix
13.3.1 The fopen() function ..................................................................................... 182
13.3.2 The fclose() function..................................................................................... 183
13.3.3 The fprintf() function .................................................................................... 184
13.3.4 The fscanf() function..................................................................................... 185
13.3.5 The getc() function........................................................................................ 187
13.3.6 The putc() function ....................................................................................... 188
13.4. Summary ........................................................................................................... 192
Unit 14 Case Study.......................................................................................................... 193
14.0. Introduction ............................................................................................................ 193
14.1. Objectives............................................................................................................... 193
14.2. Menu Driver Programme ......................................................................................... 193
14.2.1 Problem ........................................................................................................ 193
14.2.2 Analysis........................................................................................................ 194
14.2.3 Design........................................................................................................... 194
14.2.4 Implementation ............................................................................................ 196
14.3. Summary ................................................................................................................ 198
x
word
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.
This course is offered under the Faculty of IT & Multimedia Communication. This
module is for Zimbabwe Open University computer programming module.
Course Audience
This course is offered to all students taking the Bachelor of Information Technology,
and Software Engineering. As students you are required to attend this course and
master the subject. This course is crucial for students to understand problem
solving skills and implementing the right concepts, principles and techniques in
programming.
As an open and distance learner, you should be able to learn independently and
optimise the learning modes and environment available to you. Before you begin this
course, please confirm the course material, the course requirements and how the
course is conducted.
Course Objectives
By the end of this course, you should be able to:
Apply computer programming concepts and problem solving methods using
algorithms.
Write, compile and run computer programming using C language.
Module Overview
This course is divided into 14 units. The synopsis for each unit is presented below:
In Unit 1 we explain the concepts of programme and programming and how the
programming can be done in certain phases such as problem solving phase and
implementation phase.
In Unit 2 we explain the algorithms where you students should understand how to
represent the algorithms in correct ways. You will be exposed to the right technique
in creating algorithms including for advanced control structures such as selection and
repetition structures.
Unit 5 deals with different data types that can be used for C programming.
In Unit 6 we describe several constants values for programming such as integer, real
In Unit 7 we explain the concept and practices for input and output in programming.
Text Arrangement Gu i d e
Before you go through this module, it is important that you note the text
arrangement. Understanding the text arrangement should help you to organise your
study of this course to be more objective and more effective. Generally, the text
arrangement for each unit is as follows:
Introduction: In the introduction issues to be discussed in the unit are spelt out.
Unit Objectives: This section refers to what you should achieve after you have
completely gone through a Unit. As you go through each Unit, you should frequently
refer to these unit objectives and outcomes. By doing this, you can continuously
gauge your progress of digesting the Unit.
Activity: Activities are also placed at various locations or junctures throughout the
module. Activity can appear in various forms such as questions, short case studies
or it may even ask you to conduct an observation or research. Activity may also
ask your opinion and evaluation on a given scenario. When you come across an
iii
Activity, you should try to widen what you have gathered from the module and
introduce it to real situations. You should engage yourself in higher order thinking
where you might be required to analyse, synthesise and evaluate instead of just
having to recall and define.
Summary: You can find this component at the end of each Unit. This component
helps you to recap the whole Unit. By going through the summary, you should be
able to gauge your knowledge retention level. Should you find points inside the
summary that you do not fully understand, it would be a good idea for you to
revisit the details from the module.
Key Terms: This component can be found at the end of each Unit. You should go
through this component to remind yourself of important terms or jargons used
throughout the module. Should you find terms here that you are not able to
explain, you should look for the terms from the module.
Prior K nowledge
A basic knowledge of the subject matter is not required for you, students to
follow this module. However, programming knowledge will be an advantage.
iv
Blank page
Unit1
Introduction to Programming
1.0. Introduction
Since their introduction, computers have helped a lot in making everyday human
tasks easier. With the help of a computer, we can pay bills, do banking, even
shop without moving from our seat. You may have used the Automatic Teller
Machine (ATM). Imagine what would happen if computers are not used?
Situations involving computer usage are becoming more important day- by- day.
Equally important is computer programming. Programming is a list of
instructions that is followed by a computer. Without it, a computer will not be
able to function. Programming languages allow us to write these programmes and
therefore communicate with the computer.
In this unit we will discuss programming concepts and the processes that are
involved in developing a programme.
1.1. Objectives
1
ACTIVITY 1.1
Before you start reading, bring out your own understanding of a programme.
Whereas
1
1.3. Programme Development Process
Each of these phases is divided into several parts. Refer to Figure 1.1 which
shows the relationship between these two phases.
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.
2
We will discuss in detail how these three steps are carried out.
(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 more
detailed information from the persons who have identified the problem.
During analysis, ensure you understand and define the problem correctly.
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 almost always
forgotten.
3
Let us read on to know more about the steps mentioned above.
(b) Testing
Testing a programme code is a process of running a programme and
checking for errors. This is to ensure the programme does what it is
intended to do.
Normally, testing is carried out by running the programme code
repeatedly using a set of different data to ensure it functions properly
for every situation. Large input size that cannot be tested by hand has to
be tested now. If an error is found, the programme needs to be
modified until it produces the right output or answer.
(c) Maintenance
Maintaining and updating a programme code involves tasks in modifying
the programme code to eliminate errors that could not be found before and
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 that developed the programme would have left the organisation.
Therefore, it is important for a programmer to write programmes that are
easy to read, understand and maintain. Thus, we must adhere to
programming styles that are accepted by the programming society.
You have now been briefed on all the processes involved in the problem
solving phase and the implementation phase. If you are still not clear,
please read through the text again.
To ensure you have understood what you have learnt, answer the following
questions.
4
Activity 1.2
1.4. Summary
5
Unit 2 Algorithm
2.0. Introduction
In Unit 1 you were introduced to two main phases in developing a programme.
One was the problem-solving phase. In this phase, you were given some
explanation on algorithms. Therefore in this Unit, you are required to focus
entirely on algorithms from the aspect of representation until implementation.
From a historical point of view, Alkhwarizmi (Algorithm) was a mathematician.
This means that the steps will have an end and will stop. At every step, the
following action taken should uniquely be determined by instructions and
data obtained at that time.
2.1. Objectives
6
2.2.Algorithms Representation
Let us have a look at the first algorithm representation which is the flow chart.
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. Below are some symbols
that are used in a flow chart representation.
In order to represent algorithms by using flow charts, we can use the following
as a guide:
1. Identify the symbol used according to its function.
2. Get the right formula.
3. Make sure that appropriate data is used.
4. Test the flow chart by tracing each symbol and comparing it with the
expected output.
7
Based on the guide given above, let us see an example as in Figure 2.2 of a flow
chart on starting a car engine.
ACTIVITY 2.1
1. Sketch a flow chart for the process of going for a tutorial session.
8
Where the flow charts uses diagrams, pseudo-code is written using phrases or
words. To represent algorithms using pseudo-code, we need to follow the rules of
writing pseudo-code as follows:
1. Every step in an algorithm should not have more than two actions.
2. Steps in an algorithm are executed in sequence.
3. The word end or stop is used to show that the process has been ended.
4. The selection structure is also stated in shapes which will also be explained
later. (Refer to Part 2.4)
5. Loops are stated in one of the shapes which will be explained later. (Refer to
Part 2.5)
6. 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
integer, real, character or others.
7. To give an initial value to a variable (if applicable).
8. To use arithmetic symbols to state the addition, subtraction, multiplication,
division operations and brackets to show operation priority.
9. A = B represents exchanging the value of A with B.
10. The relational operators below are used to state the relationship between
two values:
(a) < Less than
(b) <= Less than or equals to
(c) > More than
(d) >= More than or equals to
(e) != Not equal
(f) == Equal
Example 2.1
Change mm unit to kg.
Activity 2.2
10
2.3.1 Identify input and output of problems
ACTIVITY 2.3
Input is all the information that is relevant, 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 on how the output is to be
displayed has also to be identified during the construction of the algorithm. An
example of the output format for display is usually in the form of a table. Below
is the input and output that has been identified for some examples of problems.
Example 2.2
11
Example 2.3
Example 2.4
Given the buying and selling price of an item, determine whether profit
was made, or break even or loss incurred
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 need to build a list of formula that
will relate to each other. Based on Example 2.4, the general formula obtained is:
To ensure that you have understood what has been learnt, try to answer the
following question. Good Luck!
Activity 2.4
12
2.3.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. Each
sub-problem 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, count the number of the letter ‘a’ 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 uppercase or lowercase letter. For example,
in the name “Tatenda Amani” there are 4 'a' s.
Step 2 and 4 can be done easily. But step 3 needs refinement. Step 3 looks like a
sub-problem that seems easy but if it is to be solved using a computer; we need
to have detailed steps on how it is to be executed by a computer. Notice how the
refinement is done by using the guide given next.
For every sub-problem, we need to identify and list the steps taken to solve it.
This method is called refining step-by-step.
13
Figure 2.4: Step-by-step Refinement
Concept
Next is the complete explanation on algorithm that is 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 more characters to be read, execute the
following step. If not, 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.
In this easy example, the number of levels refined is only up to 2 levels. One of
14
the main steps which is step 3 is refined to be step 3.1 and 3.2. Then 3.2 is refined
further into steps 3.2.1, 3.2.2 and 3.2.3. For more complex problems, the level of
refinement may be more until each step becomes detailed and can be executed.
Below are a few guides to summarise the solution:
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 3
types of general selection structures, which are:
1. Single selection
2. Dual-selection
3. Multi-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.
15
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 indentation for steps in the block start_if - end_if that 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.
16
Let’s have a look at the Example 2.6.
Example 2.6
Determine if the customers deserve to get a discount of US10.00
from the total payment charged. Customers will be categorised
as deserving if the total_payment is US60.00.
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 is referring to the total
payment that is charged to the customer.
Let’s now trace the algorithm. Let’s say the total_payment is 80.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, the total_payment will minus 10. Then,
the control of the programme will exit from the block and execute step 6.0.
Therefore, the value of total_payment reported is 70.00.
ACTIVITY 2.5
17
The flow chart is:
Figure 2.6: Flow chart for Example 2.5, single selection structure
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.
18
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.6
2.4.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
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.
But 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.
19
Figure 2.7: Dual-selection structure flow chart
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 charge is $2.00. But if
the total time parked is more than 2 hours, then 6.00 is
charged.
Assume:
in_time = 9.00
out_time = 13.00
total_time = 13.00-9.00 = 4
20
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.
ACTIVITY 2.7
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.
21
Example 2.9
Determine the payment that is charged to the customer
who parked their cars in the parking lot. The payment
rates charges are; 2.00 the first hour, and 1.00 for
each subsequent hour.
In the algorithm above, if total_time > 1, and let us say the total_time is 2, then,
start_if-end_if block (step 6.0-7.0) will not be executed. But the
start_if_not- end_if_not block (step 9.0-10.0) will be executed.
In step 9.3, total_payment now becomes 3; because 1(from step 9.2) 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.
22
ACTIVITY 2.8
1. Now try with the previous data which is the in_time 9:30 and out_time
4.30. Use the algorithm given in Example 2.9 as a reference.
2.4.3 Multi-selection
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>
23
Start
Figure 2.9 shows the flow chart for the general structure of multi-selection.
Example 2.10
Input an integer number and determine whether that number
is negative, positive or zero. Print the results.
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. Let’s say 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 is ignored. Testing at step
7.0, when executed, the result is true. Therefore, it will print „N is positive”.
ACTIVITY 2.9
Try to trace for the value of 10 based on the algorithm above. What is the
printed result?
25
Example 2.11
Input bus passenger 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 to 18 years, then the ticket
price is only 75% of the normal ticket price. It is free for
passengers less than 6 years.
From the question given, we can conclude that there are 5 groups of passengers:
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:
26
Figure 2.10: Flow chart Example 2.11, multi-selection structure
27
Figure 2.11: Types of Loops
For a loop controlling counter, the three components are put in special places,
such as:
start_for
step 1
}
step 2
: Loop Body
step n
End_for
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 by adding the counter by 1. The increment can be 2 or 3 times 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.
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.
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.
29
Example 2.12
In example 2.12, the start_for - end_for block will be executed 5 times. Therefore,
we need to trace the algorithm above and see the table given below.
The loop will stop when the counter I is more than 10, which is when i’s value is
11. At that time the value of total is 25.
30
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 the example 2.13:
Example 2.13
Notice that in step 3.0, the initial_value is a large number that will be decreased
by 2 to decrease its initial_value. Next is the tracing of the loop:
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.
31
ACTIVITY 2.10
What is the effect if i minus 2 is replaced by i plus 2 in the Example
2.13 algorithm in step 3.0? Why does that happen?
Loops like these are controlled by true conditions. There are 2 types of general
loops controlled by conditions, which are:
1. Loops with conditions tested first.
2. Loops with conditions tested later.
Figure 2.13: General Form and Flow Chart of loop structure with condition tested
first
32
Example 2.14
33
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.
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.
34
Table 2.5: Tracing of Loop with Condition Control Tested Later
Counter < 5 Loop Counter Total
0 0
1 1 ← 1 ← (0+1)
True (1<5) 2 2(0+1) ← 3 ← (1+2)
True (2<5) 3 3(1+1) ← 6 ← (3+3)
True (3<5) 4 4(2+1) ← 10 ← (6+4)
True (4<5) 5 (3+1)
5 ← 15 ←
False (5<5) (4+1)
5 (10+5)
15
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 un-certain loops
because the number of loop executions are not known before the execution starts.
Sentry value chosen must not be an input data that is valid. Consider the sentry
controlled loop in Example 2.15.
Example 2.15
Read 1 set of students’ marks where if the marks
are negative then the input ends. Calculate the
average marks.
35
In example 2.15, 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, the step 4.0 in the algorithm has to be changed to Until m!=999 that
is when the mark m! is 999, the statement becomes false and automatically comes
out of the loop.
ACTIVITY 2.11
For the algorithm Example 2.15 above, what if the negative value is a valid
data? Justify your answer.
Sentry value can also be of type character. We can change the example above and
use the character ‘t’ as a sentry value. Consider the changes made in algorithm B
below.
Till now you have learnt three types of control structures. Rest and relax before
going on to the next Unit.
36
2.5.4 Structuring
(a) Problem
Solve the problem of calculating 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 2 times the normal rate. If the
worker’s pay exceeds 500 per week, a tax of 50 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 500.
37
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
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 Ov e rt im e_Rate x
Hourly_Rate)
3.4 End_IF_Not
38
(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
Activity 2.12
39
(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 meters to body weight in
kilograms. The formula is given as:
(d) Create a pseudo-code for this problem. Accept 2 integer values as input,
let’s say 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.
As an example: Input: 3 7
Output: 3 4 5 6 7
Input: 7 3
Output: 7 6 5 4 3
40
2.6. Summary
41
Unit 3 Programming Language
3.0. Introduction
Writing programmes 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 they can be
run by a computer. This unit will give an explanation on the different types of
programming languages. Next, C language and its environment will be introduced.
At the end of this unit, one example of a simple C programme will be discussed.
3.1. Objectives
46
3.2.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 that is to be executed and the
memory cell that is involved for that operation.
ACTIVITY 3.1
Do you know the other factors why writing programmes with machine
language and assembly language did not continue? Programmes written in
machine language or assembly language are machine-dependent. Assuming we
write a programme in assembly language for a particular computer and want to
run 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. Using a
high-level language, a programmer would be 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 the example equivalent to the
one given earlier to calculate the sales amount.
47
Compared to assembly language, the high-level language resembles the natural
language more and with that it is easier to read and understand.
Table 3.1High-level
Languages
High-Level
Explanation
Languages
C A universal language that is usually used to write system
software or system applications.
C++ Extention from C 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
48
3.2. Language
Let us look into the past to see the history of C Language in short.
The C language history has links with the existence of B and BCPL programming
languages. BCPL is a language that is used to write operating systems and
compilers developed by Martin Richards in the year 1967. In the 1970s, Ken
Thompson developed the B language that is 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.
For more information on the history of C programming, visit the web site
http://syazwan.tripod.com/introc.htm or any other relevant sites.
49
3. C Standard Library : makes available the supporting functions that can be
reused in programme 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 six
phases that are involved in the process of developing a C programme that can be
executed that is:
• editing,
• pre-processing,
• compiling,
• linking,
• loading and
• executing.
50
Figure 3.1: C Development Environment
Activity 3.3
Identify software that you can use to edit and compile programmes.
51
3.4. Sample C Programme
Programme 3.1
#include <stdio.h>
B
void main(void) {
printf(“Welcome to ZOU!\n”); C
}
This section will explain one easy C programme example (see Programme 3.1).
This programme will display the following output when executed:
Welcome to ZOU
The statement that is marked as A in Programme 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 programme can contain as many comments as needed and can
be put anywhere in the programme code. The comments are not compulsory in a
programme, but we are encouraged to put in comments so that programmes are
easily read and understood.
Statements that are marked as B in Programme 3.1 are said to be pre-
processor statements. Pre-processor statements are easily known 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 header file called
stdio.hinto the programme code at the given statement line. This statement is
needed in Programme 3.1 because the header file has the function declaration
printf(). We will see later how the programme 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. Whereas in the DOS mode, it is normally stated in the file
autoexec.bat.
52
The code that is marked as C in Programme 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 is made up of two parts. The first part is the
function head that provides specific information on the function that is defined;
for example, function name. The second part is the function body which is
statements enclosed in { and }. When a function is called, the statements within
the body will get executed. In the case of main() function in the program 3.1, the
body only contains one statement which is:
printf(“Welcome to ZOU!\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 ZOU!\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.
ACTIVITY 3.4
In Unit 3.4, there were symbols which were used in programme 3.1. Can
you explain them briefly?
Symbols Explanation
/*.........*/
#include
{.........}
“\n”
53
Activity 3.5
1. Write/edit programme 3.1 using notepad and save the file with
the name atur.c.
2. Compile the programme
3. Execute the programme
4. Compare the output.
5. Edit the programme by changing the
statement printf (“Zimbabwe Open
University”);
6. Edit the programme 3.1 so that the output below is displayed:
WELL
WELCO
ME
WELCOME TO
WELCOME TO ZOU
7. What does the following do in programming?
54
3.5. Summary
55
Unit 4 Variables
4.0. Introduction
Before you read this unit further, how about interpreting the phase below:
Now, let us pay full attention to this unit. 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 programme we need to choose an
appropriate name for the file, variables, constants, functions and the rest. This
name is the identifier. The identifier is the official word used for any name in a
high-level programming language. In this unit, we will go into detail about
variables and how to name them.
4.1. Objectives
56
• appropriate,
• easy to understand and
• give 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.
There is a guideline in choosing a name for a variable in the C language which is:
1. Variable name can only contain letters, digits and underscores ‘_’.
2. Variable names cannot start with a digit (number).
3. Reserved words in C cannot be used as variable names.
Next, there are some examples of variable names that are valid.
We can give variable names up to 31 characters. The 32nd character onwards will
not be taken into consideration (except global variable names that would not be
discussed in this text).
System identifiers usually start with the character ‘_’. There, we are not encouraged
to use the character ‘_’ as the beginning for identifiers (like _total) to avoid
confusion. Both lower case and capital letters can be used to name variables.
However, the C 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.
57
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. This is because it
is against the first rule in naming identifiers. 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:
• Start with the first word being a lower case letter
• Start the second word with an upper case letter.
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.
Just like reserved words, standard identifiers also have special meanings in C. In
the sample programs that you have seen before, 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 which is not so for
reserved words. However, after re-declaring for another reason, the standard
identifier cannot be used for its original use.
ACTIVITY 4.1
So far, you have been introduced to variables, reserved words and standard
identifiers. Can you think of the differences among them?
The following identifiers are not valid. State why each of them is not valid.
Identifier Reason
(a) 2001SeaGames
(b) SEA GAMES
(c) %passes
(d) width+height
(e) double
58
4.3. Variable Types
Variables can represent different types of data. Data types that are used will
determine the variable type. Consider Table 4.1 below. These data types are
usually used in C programmes.
When a variable has a certain data type, it means that the variable can only
represent data of that 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 longare qualifiers that exist in C.
data_type variable_name;
59
When declaring variables, the compiler will be notified of four items:
1. Variable name
2. Variable type
3. Size of cell of variable in the memory
4. 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 and
identifier grade is of type char. Notice in the example above, a 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 Unit. However, storage classes will not be
taught in this course.
Activity 4.2
State whether the variables given are valid or invalid.
4.5.Variable Assignment
We can assign values to a variable by using the following statement:
variable = value;
60
61
Activity 4.3
3. State whether the variables below are valid. If not valid, state
the reason.
62
4.6. Summary
63
Unit 5 Data Types
ES
5.0. Introduction
We have seen two types of input and output data. One is of character type, for
example, your name and another that 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.
5.1. Objectives
By the end of this unit, you should be able to:
state the cell size and range for a particular data
differentiate 3 types of data
choose the type of data that is suitable for the variable depending on the type
of value to be represented
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 32767that is a
range of -32 768 to 32 767.
Variables of float type are also assigned 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 5.1 below.
64
Table 5.1: Relationship 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 longin a variable.
See the example above.
Int data type is to represent negative or positive numbers. For example - 77, 0,
999, +999. T h e memory cell size for int types differs according to different
computer systems. In the computers family of 80386 processors and below, the
memory cell size for int is 2 bytes. For processors like SPARC, the cell sizes for
int is 4 bytes.
Char data type is used to represent characters like letters, digits, or special
symbols like ‘?’.
To assign a character to a variable, we need to put single quotes as in: ‘ ‘ for
example: ‘A’, ‘z’, ‘3’, ‘?’.
A character can be read, printed and changed to an integer value. We can also do
character value comparisons by using operators like equal (==) or not equal (!=),
and relational operators like <, <=, > 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 numeric code that is unique, using the
ASCII Codes (American Standard Code for Information Interchange).
If you want to know more about ASCII codes, visit websites that are relevant.
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. Character code usually used is ASCII code.
Character value range that can be represented by char type is between -128 to 128.
65
5.5. Real Data Type
ANSI C (American National Standards Institute) describes three types of data types
that can be used for manipulating real data types:
1. float
2. double
3. long double
All types above can keep real values like 0.001, 2.0 and 3.14159. Choice is made
depending on which range of real values are to be represented. Table 5.2 below
shows the range and number of bytes that are needed for each of the real type
numbers.
66
ACTIVITY 5.1
1. There are three types of basic data types that can be stated till now,
which are: 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? Give your opinion.
4. State the data type that is suitable for each of the values below so
that memory space wastage does not happen:
67
1
5.6. Summary
• Cell sizes that are allocated for one variable is dependent on the data type
declared for it.
• Before determining the data type that is suitable, you have to observe all the
possible values that can be taken by a variable.
• Int data type is to represent negative or positive numbers.
• Char data type is used to represent characters like letters, digits, or special
symbols like ‘?’.
• ANSI C (American National Standards Institute) describes three types of data
types that can be used for manipulating real data types: float, double and long
double
68
Blank page
Unit 6 Constants
OUTCOME
6.0.Introduction
Constants are fixed values that cannot change throughout the execution of the
program. Constants can be categorised into many types following its data type,
which is integer constant, real constant, character constant or string constant.
This unit will help you identify each constant more clearly.
6.1.Objectives
6.2.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 used like
decimal, octal or hexadecimal systems.
Example:
Decimal : 0 2 99
Octal : 0 7 74
Hexadecimal : 0X 0X1 0X7A
69
Activity 6.1
6.3.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 6.1.
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:
70
Floating point constant like 333.77777e-22.
333 . 77777 e - 22
If 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’ can be 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 (floattype)
0e0 (same value as 0.0)
1. (same value as 1.0, but more difficult to read)
Activity 6.2
69
2. Give reasons why the real constants below are invalid.
6.4.Character Constant
70
'\f' form feed
'\n' newline
'\r' carriage return
'\t' Tab
'\v' vertical tab
'\\' \
'\'' '
'\”' “
'\055' Octal character value 055
'\xA9' Hexadecimal character value 0xA9
'\0' Null character
6.5.String Constant
In C language, string constants are made up of some characters surrounded by
double quotes. Below are some examples of string constants. For example:
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 done on it.
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 by the C compiler as
an end of the character array. An example of the array “ZOU”is actually “ZOU
\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 “ZOU” is 4.
Because 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 ‘\0’.
71
ACTIVITY 6.3
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.
(d)(a) 15 .123F
(e)(b) ‘XYZ’ ‘x’
“X”(c) ‘*’ (f)
72
6.6.Summary
• 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 are different.
• 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.
73
Blank page
Unit 7 Input and Output
7.0. Introduction
We have looked at some output functions in previous units. 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 is part of the C system. Both these functions exist in the C library and are
kept together with C system. Even though the object code for the functions are
made available by C system, it is your responsibility as a programmer to declare
this function when you want to use it in your programme.
7.1. Objectives
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.
76
7.2.1 Printing strings
Data that is easiest to print or output is a string. We just need to write the string
that needs to be printed as the output_format in the printf()function. The string
will print as we have written it. As an example:
Notice that all the characters in the double quotes „ “ are printed including the
spaces.
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.
Other than the escape sequence ‘\n’ there are other characters that can be used in the
string output_formats as given in Table 7.1.
77
Table 7.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 7.1
78
7.2.2 Printing values
(a) %sspecification
Assume NAME is a string variable that can be assigned the value Peter
Moyo. Consider how the specification %s interprets the variable to output in
Program 7.1.
Program 7.1
/* Prints name */
#include <stdio.h>
void main() {
char name[] = “Peter Moyo”;
printf(“%s”, name);
Do you know what will the output be? Yes, the output will be:
Peter Moyo
79
(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 7.1 to understand this concept.
character1 = ‘U’;
character2 = ‘N’;
character3 = ‘I’;
character4 = ‘T’;
character5 = ‘E’;
character6 = ‘M’;
printf(“%c %c %c %c %c %c “,character1,
character2, character3, character4, character5,
character6);
80
Programme 7.2
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. Because 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. See relevant web
sites on how this can be done.
81
ACTIVITY 7.2
Activity 7.2
1. Write and compile the computer programme below:
void main () {
char name[] = “Peter Moyo”;
int age = 20;
float height = 1.53;
(a) printf(“*\t***\t*****\n”);
(b) printf(“*\b***\n*****\n”);
(c) printf(“*\r***\n*****\n”);
82
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);
ACTIVITY 7.3
1. printf()function is frequently used with the scanf() function. Where are the
two function used?
In this section, we will see how to receive input with the scanf() function. This
function allows us to interact with the written programme. 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 programme and usually produces output. Let us take a look at the
general form for 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.
83
7.3.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:
scanf(“%c%d”, &character, &num);
will read two inputs. Assume character and numare 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 variable num.
Programme 7.3
/* Programme 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 programme 7.3 above. When the programme is executed, it will wait for
us to enter a value for day, month and year.
11 9 2001
One main problem in the programme above is that the programmer assumes
that the user of the programme knows what the values to be entered are.
Normally, when writing programmes, we will display a suitable message to
inform the user of the type of values to enter.
84
Activity 7.4
85
7.4. Summary
86
Blank page
Unit 8 Operators and Expressions
8.0.Introduction
When you studied mathematics in secondary school, you saw symbols like +, -, x,
<, > etc. These symbols are used to manipulate data. These symbols are known as
operators. Before we write programs that are more complex, it would be good to
remember some symbols 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 operator and conditional
operator. This chapter will explain in detail about these operators.
8.1.Objectives
By the end of this unit, you should be able to:
write appropriate statements using 5 types of operators
write arithmetic expressions using C syntax
evaluate expressions to be used in single, double or compound
assignment statements
87
Table 8.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, Multiply and a few cases of Division operator would give the same
result as normal arithmetic operators.
Therefore, the addition, minus and multiply operators will not be discussed in detail.
Please recall the basic concepts of addition, subtraction and multiplication from your
mathematics subject.
Please note that the symbol used in the multiplication operation is * and not x. The
Division result of both the operands is determined. If the division is not a round
number (that is it has a decimal value), therefore the remainder of the division
is ignored. The result is truncated to an integer value. Consider the example
given in Table 8.2 below:
88
Table 8.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
Observe Table 8.3 above. In the first example, immediately we get the division value
to be 2. Because the division is a real division (one of the operands is a real number),
therefore the result of the division has to be written as a real number 2.0.
Activity 8.1
Which one of the answers given below would keep the value of result?
A) 3 C) 3.7
B) 3.0 D) 3.75
89
A) 3 C) 3.7
B) 3.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.
Activity 8.2
A) 3 C) 3.7
B) 3.0 D) None of the above
90
8.3.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)
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
91
Operator / has a higher precedence level, therefore it is evaluated first. The result from
10/3division would be the operand for the addition operation and the result is 6.
ACTIVITY 8.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.
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
ACTIVITY8.4
What about the case below? Can you show the steps?
(9 - (3 + 2)) * 3
92
Table 8.6: Changing Algebra Expression to C Expression
7
15+5 +
2
ACTIVITY 8.5
93
8.4.Assignment Statement (=)
variable = expression;
Programme 8.1
#include <stdio.h>
void main() {
/* expression assignment */
Activity 8.6 }
94
ACTIVITY 8.6
In C assignment statements, other than variables and constants, expressions can also be
other expressions. This means we can do several assignment statements in one
statement just like:
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:
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 programme code.
The example below shows the variable age and numOfSiblings assigned the initial
value of 0in one multiple expression. The same would be for the variable weightand
95
heightassigned initial value of 0.0in one multiple expression.
ACTIVITY 8.7
y = x = 10.0*2
A) 10.000000 C) 20.000000
B) 20 D) none of the above
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 Diagram 8.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)).
96
Figure 8.1: Compound statement calculation process [weight=weight+ 1.5]
In C, statements like this can be written using compound operators. Table 8.7
below shows compound operators.
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:
Based on the precedence level, the statement above is solved in this manner:
97
ACTIVITY 8.8
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 B) -10.0
C) -20 D) 10
8.5.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 that is 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, more than etc. Table 8.8 below lists the relational operator
symbols and their meanings.
98
Activity 8.9
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
8.6.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 8.9 below lists the
logical operators.
Table 8.9: Logical Operator
Symbol Meaning
& and
||& or
! not
Operator &&and ⎢⎥ must have two operands whereas the operator !has only
one operand. Table 8.10 below shows how the logical operator functions. The
table is known as the truth table. 1represents truth and 0 represents false.
Table 8.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
99
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. Assume a =
1, b = 5, c = 15and d = 25, notice how these logical expressions are evaluated:
(c) ! (c > a)
<=> ! (15 > 1)
<=> ! 1
<=> 0
ACTIVITY 8.10
100
If a= 5, b= 10, c= 15 and valid has the value 1, what is the value of the
expression below?
Expression Result
a) c = = a + b ⎥⎥ !valid
b) a! = 7 && valid ⎥⎥ c >= 6
Increment and Decrement operators are unique operators. Table 8.11 below shows
the operators.
This operator needs an operand only. The 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 8.12 below explains
the meaning of increment, decrement, and the statements that are equivalent to them.
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 8.13 below:
101
Expression Meaning
i++ Value i increased after used in expression
++i Value i increased before used in expression
i-- Value i decreased after used in expression
--i Value i decreased before used in expression
Also consider when we use the operator ++i (prefix increment) as shown below:
i = 5;
j = ++i - 2;
i = 5;
i++;
j = i - 2;
Activity 8.11
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 sub programmes below:
Sub programme Output
Postfix decrement
i = 7; printf(“%d\n,i);
printf(%d\n”,i--);
printf(%d\n,i);
102
Prefix decrement
i = 7; printf(“%d\n,i);
printf(%d\n”,--i);
printf(%d\n,i);
3. If
Expression jValue
i=5
j = ++i –2;
Therefore j = ?
i = 5, j = 3;
i++;
j=i–j
Therefore j = ?
8.8.Cast Operator
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.
103
When the value of total = 10 and count =2, therefore average value obtained is 5.0. But
when the value of total = 15and 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.
In cases like this, 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 part where they are needed. 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.
ACTIVITY 8.12
8.9.Conditional Operator
?: operator is known as conditional operator. It is used for evaluating
conditional expressions. The syntax used is:
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.
104
expression_1? expression_2 : expression_3
True
False
m ? mx + c : c;
y = m ? mx + c : c;
if (m)
y = mx + c;
else
y = c;
Activity 8.13
105
3. Assume 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;
14
8.10. Summary
106
Unit 9 Selection Central Structure
9.0.Introduction
There are three main structures in algorithm. They are the sequence structure,
selection structure and repetition structure. In a structural programming language, we
can also divide the logical flow of a programme into three basic control structures
which are:
1.sequence
2. selection
3.repetition
The sequential structure is a control flow that we have seen through examples in the
previous units. Programmes that we have written so far (by using the assignment
statements as well as printf() function and scanf() function) are to execute the
statements one by one in the sequence that they are written. The selection control
structure represents the selection structure in the algorithm, whereas the repetition
structure is to represent the repetition structure. In this unit, we will see the selection
control structure using the if, switch and break statement.
9.1. Objectives
The if statement is used to represent the selection structure. The selection structure
allows us to choose and execute only one of the many choices available based on a
certain condition. In C language, we use the relational expression, or the logical
expression to represent a selection condition. We have seen the selection structure for the
algorithms divided into 3 main types, which are single selection, dual selection and multi
selection. The if statement can also be divided into 3 similar forms which are:
107
Table 9.1: The if Statement
Statement here could mean to be more than one statement. These statements are
called compound statements. The compound statements must be surrounded by the
braces { and }.
if (k < j) {
min = k; /* this compound statement */
printf(“k less than j\n”); /*will be executed when k < j*/
}
The compound statement above will be executed when the value of k is less than j.
Notice that the compound statement is written by tabbing a few spaces from the if
statement.
108
The opening brace { is written on the same line as the if statement whereas the
closing brace } is written parallel to the if statement on a new line after the compound
statement. Writing programmes with a good style will make it easier for us to read the
program and will make it easier to find errors that surface.
ACTIVITY 9.1
We need to be careful when writing compound statements.
Consider what would happen if we left out the braces {}, like the code segment
below:
if (k < j)
min = k; /* executed when k < j */
printf(“k less than j\n”); /* will always be executed,
even when the
expression k < j is
false */
Programme 9.1
void main() {
float weight, height, bodyWeightIndex;
printf(“Enter your weight (kg): “);
scanf(“%f”, &weight);
109
Programme 9.2
void main() {
float weight, height, bodyWeightIndex;
printf(“Enter your weight (kg): “); scanf(“%f”, &weight);
printf(“Enter your height (m): “);
scanf(“%f”, &height);
bodyWeightIndex = weight / (height * height);
printf(“Your body weight index is %.2f\n”,
bodyWeightIndex);
if (bodyWeightIndex >= 30.0)
printf(“You’re obese! Do more exercise and less
food.\n”);
else if (bodyWeightIndex >= 25.0)
printf(“Your body weight is more than ideal
weight.\n Try reducing.\n”);
else
printf(“Congratulations! Your body weight
is normal.\n”);
}
110
Programme 9.3
void main() {
char chr; scanf(“%c”, &chr);
ACTIVITY 9.2
bodyWeightIndex
weight height Output
Message
80.0 1.5
60.0 1.5
55.0 1.5
(a) Given the data above, edit, compile and execute program 9.1.
Fill in the information.
(b) Modify Programme 9.1 to 9.2. Test the data above and fill in
the information.
111
(c) Edit, compile and execute Programme 9.3.
2. What is the output of the following programme segment: (a) int code;
code = 2;
if (code = 1)
printf(“Man\n”);
else printf(“Woman\n”);
(b) int i;
i = 14;
if (i % 2 == 0)
printf(“Even Number\n”);
else
printf(“Odd Number\n”);
Switch and break statements are used to select only one choice from many choices that
exist. This statement is very useful when the choice is dependent on the value for one
variable or simple expression. The value for the expression can only be of type int and
char, but not of type float. Consider the syntax for the statements switch and break:
switch (expression) {
case expression-1 :
statement-1; break;
case expression-2: statement-
2;
break;
:
case expression-m :
statement-m; break;
default : /* can be ignored */
statement-n;
break;
}
The break statement will bring the programme control out of the switch statement
without executing the next case statement. If the expression cannot be matched, and the
default statement is available, then statement-n will be executed. If the default
statement does not exist, control will exit the switch statement.
ACTIVITY 9.3
113
Programme 9.4
/* This programme will print the name of the breakfast food based on the
menu choice*/
#include <stdio.h>
void main() {
int choice;
scanf(“%d”, &choice);
switch (choice) {
case 1 :
printf(“SadzaStew\n”);/* if choice == 1 */
break;
case 2 :
break;
case 3 :
printf(“Fish\n”);/* if choice == 3 */
break;
default :
*/
}
114
Look at Programme 9.4 Assume the choice value that is the input, is 2 and is
compared to the expression in the first case statement. Because 2 != 1, therefore the
comparison is continued to the second case statement which is case 2. If this
comparison is true, the statement printf(“Rice chicken\n”) is executed and next the
break statement will bring the control out of the switch statement without test the next
case statement.
If the input value of choice is 7, and each comparison with the case statement is
false, then the statement for the default statement which is printf(“Not in the
menu\n”) will be executed.
Consider the input and output results of the example execution of the programme
code segment in Table 9.1 below:
Case and break statement above can be written in the form of if-else-if statements as
below:
if-else-ifscanf(“%d”, &choice);
if (choice == 1)
printf(“SadzaStew\n”); /* if choice == 1*/
else if (choice == 2)
printf(“Rice Chicken\n”);/* if choice == 2*/
else if (choice == 3)
printf(“Fish\n”); /* if choice == 3*/
else
printf(“Not in the menu\n”); /* if choice other than 1,2 or 3 */
Break statement plays an important role in allowing the switch statement make
only one statement just like the if-else-if statement. If the break statement is not
used then the control will continue to the next case statement after the case
statement that has been successfully compared.
As extra reference, go to http://gd.tuwien.ac.at/languages/c/
programming-bbrown/c_028.htm and do the interactive quiz at the
address http://gd.tuwien.ac.at/languages/c/programming-
bbrown/c_029s.htm
115
ACTIVITY 9.4
ACTIVITY 9.4
Use Programme 9.4 and remove the break statement. Think of the result.
Prove what you have thought about by compiling the programme in the
computer.1. What will be printed by the switchstatement below if the value
for colour is ‘R’?
switch (color) { /*no break statement */ case
‘R’: printf(“Red\n”); case ‘B’:
printf(“Blue\n”); case ‘Y’:
printf(“Yellow\n”);
}
9.4. Summary
• There are three forms which are if, if-else and if-else-if and each
represents single selection, dual-selection and multi-selection.
• The if statement is used to represent the selection structure.
• Switch and break statements are used to select only one choice from many
choices that exist.
• This statement is very useful when the choice is dependent on the value for
one variable or simple expression.
116
Unit 10 CASE STUDY
LEARNING OUTCOMES
10.0. Introduction
Computer programmes are not only used to do boring tasks. You can also have
fun by writing computer game programmes. Now that you have learnt the basic
syntax for C language, we will demonstrate a computer game case. This example
will show how to solve problems in stages using methods discussed in Unit 1.
Then we will write programmes using the C syntax that were introduced in Unit 4
to Unit 9.
10.1. Objectives
By the end of this unit, you should be able to:
analyse programme development processes following the phases stated in
Units 1 to 3
apply C library functions in programs depending on examples
describe how selection control structure is used in a problem
Have you played computer games? In this case, we will write an easy computer
game programme. You may have probably played this game when you were
younger. It is called “paper, rock, and scissors”. Two players usually play the game.
Every player uses their hand to represent one of the three objects. Putting their
palms at a horizontal level represents “paper”, making a fist is “rock” and putting up
two fingers is “scissors”. Players will sit facing each other and count
“one, two, three!”. At the count of three, both players will show their choice. If their
choices are the same, then the result is a tie. If not, the result will be based on:
117
Figure 10.1: Symbols used for computer games
10.3. Analysis
To simulate this game, we will write a programme that will allow a user (player 1)
to play with a computer (player 2). Both players can choose an integer 0, 1, or 2 that
will each represent paper, rock and scissors.
Representation Number
Paper 0
Rock 1
Scissors 2
As an example, let us say rand() returns 1694. The expression value (rand()
% 3) is 2. To ensure the rand() function creates a different number every time
the program is executed, we would use the following function call:
118
srand(time(NULL));
The time (NULL) function returns seconds calculation that has been lapsed since
1 January 1970 (UNIX systems date of birth). By passing this integer second
calculation (surely different each time the time(NULL) function is called) to the
srand()function, will determine where the rand() function starts. Thus, the value
returned by the rand()function will always be different. Both the
rand() and srand() function prototypes is in the file stdlib.h whereas the
time()function prototype is in the time.h file. Because of that we need to insert
the pre-processor instruction #include <stdlib.h> and #include<time.h> in the
programme. To decide the winner is easier if we build the table below:
T shows a tie result that will be obtained when the choices of the Player and the
Computer are the same. P shows the combination of choices by the Player and
the Computer that ends with the Player winning. T shows the combination of
choices by the Player and the Computer that ends with the Computer winning.
Therefore, we have 7 conditions to show the game results message that is to be
printed.
Input
119
Output
Initial Algorithm
1. Start.
2. Display introductory message and instruction.
3. Input player choice as integer value.
4. Generate computer choice as integer value.
5. Do comparison to display player and computer choice in
text form.
6. Do comparison to determine the winner based on the player
and the computer choices and display the result.
7. End.
Steps 1, 2, 3 and 7 are simple and do not need any details. On the other
hand, steps 4, 5, and 6 need more details. Let us see the detailed steps.
120
if_else if (player == 1) start_if_2
5.2.2 Display “ROCK”.
end_if_2
if_else if (player == 2) start_if_3
5.2.3 Display “SCISSORS”.
end_if_3
5.3 if(computer == 0) start_if_1
5.3.1 Display “PAPER”.
end_if_1
if_else if (computer == 1) start_if_2
5.3.2 Display “ROCK”.
end_if_2
if_else if (computer == 2) start_if_3
5.3.3 Display “SCISSORS”.
end_if_3
end_if_1
if_else if ( ((player == 0) && (computer ==
1))|| ((player==1)&&(computer==2))||(player
== 2) && (computer== 0))) start_if_2
6.1.2 Display “YOU WIN!”.
end_if_2
if_else if ( ((computer == 0) && (player ==
1)) || ((computer == 1) && (player ==
2))||((computer == 2) && (player == 0)))
start_if_3
121
Programme 10.1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main(){
“RESULT”);
=========“);
switch (player){
break;
The programme interacts as follows:
case 1: printf(“%15s “, “ROCK”);
break;
122
case 2: printf(“%15s “, “SCISSORS”);
break;
switch (computer){
Activity 10.1
case 0: printf(“%15s “, “PAPER”);
break;
break;
break;
if (player == computer)
printf(“%15s\n”, “GRACE”);
123
***PAPER, ROCK, SCISSORS***
In this game you are given three choices:
0 is paper
1 is rock
2 is scissors.
ACTIVITY 10.1
1. You do not need to write a programme for this problem. You need
to show how to calculate the charges for using water for a particular
month that is provided by the Water Utility Company. Charges are
calculated based on these information:
outstanding payment amount
• previous meter reading
• current meter reading
125
10.5. Summary
126
Unit 11 Repetition
11.0. Introduction
Do you still remember the repetition structure in Unit 2? With this structure, we
can represent problems that repeat until a certain condition is fulfilled. In the
logical flow of a program, this repetition structure can be interpreted as a repetition
control structure.
In this unit, we will introduce to you the repetition control statement. C has three
types of control statements that are concerned with repetition, which is for, while
and do-while statements.
11.1. Objectives
By the end of this unit, you should be able to:
implement C repetition structure using for, while and do-while
statements
differentiate between for, while and do-while statements
use continue and break statement as a jump instruction
write nested loops depending on the problem given
127
Figure 11.1: for execution statement
In the Figure 11.1, you can see that the statement is made up of two parts, the
head and the body. The for statement's head is to control the repetition statement
that is contained in the body.
You will notice that it is made up of three statements, which are the initialisation,
test, and update. Initialisation is the statement that is assigned an initial value at
the beginning of the execution that is before the first loop. Test is the statement
that will determine if the repetition is to be continued or not. The third statement is
the update that will be assigned after each repetition is executed. The flow
chart in Figure 11.1 explains the concept of the for control structure execution.
Example 11.1
Here is an example of a forstatement.
128
Consider the initialisation, test and update for this statement. We can see that
the body of the for loop is made up of one printf() statement that will print the
current value of x.
Refer back to Figure 11.1, can you see that the printf() statement is repeated
eight times? This is because the test component will be valued as false when the
variable xis greater than 8. The following fact will be understood when the initial
value of xis 1 and the variable is added by 1after each repetition. Therefore, the
printf()statement will be executed eight times.
1 2 3 4 5 6 7 8
ACTIVITY 11.1
Create a flow chart for Example 11.1 that is in the text above.
ACTIVITY 11.1
3. Write the segment code again below by changing the for loop
with the whileloop?
for (c=’A’; c <= ‘Z’; c++)
printf(“%c\t”, c);
According to C syntax, the for statement body has to be one statement. What
happens if a group of statements needs to be repeatedly executed? The way is to
combine the statements into a compound statement. The compound statement is
formed by surrounding the statements with the symbols { and }.
129
Consider Programme 11.1 that will read 10 numbers and then output the total and
average.
Programme 11.1
/* Input 10 numbers and then output the total and
average */
#include <stdio.h>
void main ()
{ int x;
int number; int total; float average;
total = 0;
for (x = 0; x < 10; x++)
Compound statement
{ //display message
printf (“Enter an integer value”) //input integer
//latest total
scanf(“%d”, &number);
total = total + number;
}
ACTIVITY 11.2
Based on Programme 11.1, trace the forloop and display the output generated.
130
11.3. The While Statement
Other than the for loop, repetition can also be coded as the while statement. See
Figure 11.2.
Besides the for statement, the while statement also has a head and body.
However, the head for this statement has only one component, which is the test
that will determine whether the execution of the body is to be repeated. Just like
the for statement, the while statement can be made up of one statement or a
compound statement. An example is shown where the while statement has more
than one statement.
Consider the segment code below that will input a positive number n and then
calculate the total of all the numbers from 0 to n-1.
131
total = i = 0;
printf(“Enter a number greater than 0”);
scanf(“%d”, &n);
while (i != n) {
total += i;
i++;
}
Figure 11.2 shows the execution of the while statement in the form of a flow
chart.
ACTIVITY 11.3
Try to sketch the execution flow for the segment code above for Example:
Calculating the average of a set of data given in program 11.3
132
2. Write the output generated by the programme code below:
int i;
i = 9;
while (i > 0)
{
printf(“%d\n”, i); i -= 2;
}
If we compare the flow of the for statement execution with the while statement
execution, we can see the equality between them. Still, a for loop can be changed
into a while loop that is similar to it and vice versa. We will see now how to
change a for loop into a while loop.
We can use the segment code below as a template to write a while loop which is
comparable to the for loop.
initialisation;
while (test)
{
statement;
update;
}
Sketch the execution flow for the while loop code template above. Compare
the flow chart in Figure 11.1.
133
11.3.2 Integer expression and loop initialisation
1
while (x != 0)
{
total += x;
x--;
}
2
while (x)
{
total += x;
x--;
}
Statement while2 is comparable to statement while1 since both will end when the
value of x reaches zero. Sometimes the test component of a while statement is
false at the beginning of execution of the statement. In this case, the body of the
loop will not be executed at all.
134
11.3.3 The endless loop
When we write a repetition statement, the most important thing that we look into is
its stopping condition. We need to ensure that the execution of the statement will
eventually end. Observe the following code segment:
In that code segment, an integer number will be input and assigned to the
variable num. Variable x is initialised to the value 0. The while statement will
increase variable x by 1repeatedly until the value of the variable is the same as
the value of num.
The code segment above looks reasonable. Still, what will happen if a negative
value is input? We will see that the execution of the while statement will not end.
The test component for the statement is always true since the value of variable x
will not be the same as num. If this condition happens, we would say that an
endless loop has been created.
ACTIVITY 11.5
Try to rewrite the programme above using the forrepetition control structure.
Programme 11.2 is another example that uses loop determined by condition. The task
of this programme is to input a number of data, count the even and odd numbers
and at the end output a summary.
11.
Programme 11.2
/* Input the number of data followed by the data itself. Then count the number of
even and odd numbers for input data.*/
#include <stdio.h>
void main() {
if(num%2==0)
136
11.3.5 The while loop controlled by sentry
Consider programme 11.2 again. This programme needs to know how many data
is to be input because that is the number of data being input. Still, there might be
situations where the number of data being input cannot be determined earlier.
Therefore,
A loop controlled by sentry is a loop that will repeat according to a value
that is called the sentry value.
(i) Sentry value is the value that is out of the boundary of valid data.
(ii) Loops like these are suitable to be used in situations where the number of
repetitions cannot be determined.
Activity 11.7
Generally, the statement will be executed until the test is false (zero). The do-
while loop execution can be described as:
1. statement executed
2. test done
3. If test is true (non-zero), then repeat step 1 till 3.
4. If test is false (zero), stop looping.
The do-whileloop execution can be described through the flow chart in Figure
13.3.
Because the testing is done at the end of the loop, the number of repetitions
possible for any do-while statement is at least once. For the while loop, testing is
done before looping, therefore the number of repetition possible for the while
loop is at least zero. Observe the code segment below:
ACTIVITY 11.8
Try to plot a Figure like Figure 11.1 and 11.2 for the do-while statement.
List the differences between the three repetitive control structures.
Write a code segment that uses a while loop which would execute
similarly to the execution of the do-whileloop below.
do{
scanf(“%d”, &data);
}
while (data != -1);
Other than the test component, there are two statements available in C for
controlling looping statements in the for, do-while and while which are continue
and break statements. We will see the continue statement in this section. The break
statement will be explained in Unit 11.6.
On the other hand, the test component of the while statement will be valued to
determine the next loop. The syntax for the continue statement is:
139
continue;
This for statement will repeat the execution of its body 10 times. For each
repetition, the value of x will be tested if it is even (that is x % 2 equals 0) or odd
(x % 2 doesn’t equal 0). If even, two messages will be displayed. For example, if
the current value of x is 4, then the message output is:
4 even number
Print even numbers only!
What happened is that the current loop is ended; the second printf()
statement in the body of the statement is not executed. Alternatively, the test
component in the for statement will be continually tested for the next loop.
140
0 even number
Print even numbers only !
2 even number
Print even numbers only !
4 even number
Print even numbers only !
6 even number
Print even numbers only !
8 even number
Print even numbers only !
Previously, we have seen the continue statement and its usage in controlling
repetition. In this section, we will see the break statement which also has the same
reason but with a different execution effect compared to the continue statement.
In the previous unit, we learnt the use of a break statement to exit from the
execution of a switch statement. Besides that, the break statement can also be used
to exit from the execution statement of a for, while and do-while.
The code segment below uses a break statement to exit from the for statement
execution. At the beginning of the execution, an integer number between 1 to 10 is
input. Then the code segment will output a list of integers from 1 to the
number that have been input. When the for has finished looping, a message will
be displayed.
printf(“Enter a number between 1 and 10:”);
scanf(“%d”, &num);
for (x = 1; x <= 10; x++) {
if (x == num)
break;
printf(“%d “, x);
}
printf(“\nExit from loop when the value is reached %d”, i);
141
Notice that the head of the for loop specifies the number of repetitions as 10
times. But, when the value of i is the same as the value input by the user, the
repetition statement for will stop immediately because of the break statement
execution inside the if statement. Control will move to the printf() statement after
the for statement.
Next is the output that is generated if the users input the number 6.
Activity 11.9
Complete the code segment below so that the output generated is as
follows:
3 6 9 12 15 18 21 24 27 30
i = 1;
while (1) {
printf( );
if ( )
break;
;
}
142
for (i = 0; i < 2; i++) { A
for (j = 0; j < 5; j++) {
printf(“%d, %d\t”, i, j);
} B
printf(“\n”);
}
Notice that the code segment has two for statements that are marked as A and B.
Statement B is part of the statement that is in the body of statement A. From the
heading of statement A, we know that the statement execution is done twice. The
same as statement B, the body will repeat 5 times.
143
144
There are two for statements that are involved and are marked A and B.
Statement A will repeat its execution of body for every number set that needs
processing. For every repetition, the following items will be executed for every
number set:
(i) Input how many numbers will be input for that set.
(ii) Input every number in that set and at the same time update its totals.
(iii) Calculate the average for that set.
(iv) Output the average for that set.
Execution of step (ii) would surely need looping because for every set, the
numbers would be input one at a time.
Activity 11.10
scanf(“%d”, &data);
for (row=1; row <= data; row++) {
for (col=1; col <= row; col++)
printf(“%d”, col);
printf(“\n”));
}
145
11.8. Summary
• The three types of statements that are made available in C for us to code
repetition, which are the for statement, the while statement and the do- while
statement.
• The other statements that are relevant to repetition are continue and break
statement.
• Other than specifying the test component, we can use the continue and
break statements to control execution of repetition statement.
146
Unit 12 Functions
ARNING OUTCOMES
12.0. Introduction
So far, the programme examples given are easy and small. In fact, all programme
statements can be put into one function which is the main() function. This
structure is not suitable for large programmes because it makes the programmes
hard to read and understand. Proper code arrangement is needed so that it can
clarify logical structure and flow of programme execution. This will make sure
programs are easier to read, understand and maintained.
12.1. Objectives
ACTIVITY 12.1
Before you continue reading, try to think, what can you say about functions in the
context of programming?
Functions can be seen as a small programme code that would do a specific task.
For example, we might write a function to execute a task of displaying a curve on
the screen. With this function, we do not need to write the code to execute the
task for every curve that we want to display. We just need to call the function and
provide the information that is needed by it for the execution of the task of
display. We can see how the use of functions reduces the repetition of code in
programs.
148
We have actually used functions in previous examples. As an example, we used
the functions printf() and scanf() that are available in the C standard library,
to output and input data. Other than using functions that are available, we will
see later how programmers can define their own functions.
To execute a function, you need to call the function. Calling a function means
transferring the control of the programme from where it is called to the function
and continue with executing the function code. When calling a function, we can
assume the function as a black box. In other words, we can use the function even
without knowing how it does its task. For example, so far we have been using the
printf() function to do output. However, deep knowledge about this function is not
one of the requirements to use it.
In C, calling of functions is executed by calling its name. By doing this, the control
of the programme will be transferred to the function code. After the function code
is executed, the control will be transferred back to the place where it was
called from, and the next statement will be executed.
There are functions that need certain information from the calling statement so
that it can execute its task. For example, for a function to calculate the area of any
square shape, it would need to know information on the dimension of the given
shape. Without this information, the function would not be able to do the
calculation.
149
Figure 12.1: Function Calling
No parameter
function_name()
The following code segment will call the functions above to display an alien with
three heads, two bodies and six legs.
int i;
for (i=0; i < 3; i++)
draw_head();
} draw_body();
draw_body(); How to call functions
without paramneter
for (i=0; i < 6; i++)
draw_legs();
150
function_name(parameter_list)
When sending parameters to a function, the parameter sequence that is sent must
be the same as the parameter sequence that has been specified by the function.
For example, let us say a function is to calculate the area of a square. It needs the
width and height parameters of the square. When calling the function, the
parameters that need to be sent should also be the width followed by the height of
the square.
In addition, the type of each parameter sent must be equivalent to the type
specified by the function for its parameters. For example, if any parameter
specified by a function is a type char, the matching parameter sent to the
function should also be equivalent to a char.
draw_alien() function above requires three parameters. The first and second
parameters are two integer (int) values that each specifies the number of heads and
number of feet the alien has to display. The third parameter is of type float that
represents the measurement for each of the alien’s heads.
The next code segment will call the function above to display five aliens with
three heads, six legs as well as having a head circumference of 1.23 meter.
int i;
for (i=0; i < 5; i++)
draw_alien(3, 6, 1.23); /*function call
using parameters */
C Language provides library functions that has many types of functions already
defined and can be used again by programmers. For example, sqrt() function to
calculate square root is available in the mathematics standard library. The next
program contains examples of reusing this sqrt()function.
#include <stdio.h>
#include <math.h>
void main(void)
{
double num, amount;
printf(“Enter number: “);
scanf(“%f”, &num);
/* available function calls with
Amount = sqrt(num) parameters */
printf(“Square Root %lf: %lf”, num, amount);
}
Let us look at the sqrt() function calls in the programme code above that causes
the execution of the function code. In the call, the value of the argument num is
passed from the calling function to be used in the calculation.
For example, let us say the number being input is 16.0. Therefore, the variable
amount calls the sqrt() function to calculate the square root of that number. After
the function code is executed, the control of the programme will move back to the
calling programme. The result of the calculation will be returned and assigned to
the amount variable. The programme ends by outputting the result of the
calculation using the printf() function.
Notice however that the programme above contains the pre-processor directives
#include <math.h>. This instruction will cause the header file math.h to be included
with the programme code before compilation. The header file is needed because it
contains useful information on the functions that are available in the mathematics
standard library including the function sqrt() that will be reused in the programme
code above.
152
12.4. Writing a Function
To build a function you need to know how to call and define the function.
Previously, we have seen how to call a function where the code is already
available. Now we are going to learn how to define our own functions. The
general definition of functions is as follows:
returntype functionname(variable_declaration_list)
{
function heading
variable _declaration_list
statements function body
}
As mentioned above, the function declaration is divided into two parts, which are
the head and the body. The function heading specifies the following information:
(i) returntype
This is the data type that would be returned by the function. If the function
does not return anything, we can state the returntype as void. Return
type will be explained in detail in section 12.4.3.
(ii) functionname
This states the name of the function declared. Usually, the rules to name a
function are the same to name a variable.
(iii) variable_declaration_list
This is the declaration of every function parameter and is divided by a
coma. In C, function parameters are special parameters that are assigned
values passed by the calling function while calling a function. If the function
does not have any parameters, the variable_declaration_list can be replaced by
the keyword void. Parameters that are declared at the head of the function
declaration are also known as formal parameters. It is to differentiate them
from actual parameters, which are parameters that are sent from the calling
function during the function call.
153
The function body declaration is divided into:
(i) variable_declaration_list
The variable_declaration_listis a group of variable declaration that
can only be used in the function body.
(ii) statements
The statementsare a group of statements that are executed when the
function is called.
ACTIVITY 12.2
The function naming rules are the same as the naming of variables. Try to list
the rules again.
Notice however the keyword void after the name of the function. This states that
the function is declared without any parameters.
154
void main(void)
{
printf(“This is a square\n”);
draw_sides4(); /*calling a function without a parameter*/
printf(“Good Luck!”);
}
This is a rectangle
*****
*****
*****
*****
Good Luck!
155
12.4.2 Writing a functions with parameters
The draw_sides4() function in the 12.4.1 would only be able to display a rectangle
with 4 rows and 5 columns. Now we are going to parameterise the function so that
it can display any rectangle. In addition, it can display a rectangle using any
character. Next is the result of updating the function:
We are introduced to three parameters, which are the width, height, and
character that represent the width and height of a rectangle and a character that is
used by the function to display its shape. Notice how the parameters are used in
the function body to make the function more general than the one before it.
For example, previously the loop on the outside will loop for 4 times. This time,
the number of loops depends on the value of the parameter height that is
passed by the calling programme. The next programme shows an example of
calling the function above.
void main(void)
{
printf(“This is a rectangle\n”);
draw_sides4 (5, 4, ‘*’); /*calling function with parameters*/
printf(“Good Luck!”);
}
Output generated by this programme is the same as the output that was given in the
previous section.
156
Figure 12.3: Calling Functions with Parameters
Notice that the returntype for both the functions draw_sides4() that was given
earlier is stated as void. This means that both the functions do not return any values
to the calling program.
For the functions that do return values, returntype must be stated for the type of
data returned. Returning values to the calling function is done through the keyword
return. Return statement syntax is given as:
return statement;
157
#include <stdio.h>
double circleArea(double radius)
{
double area; Definition of function
area = 22.0/7 * radius * radius;
return area;
}
void main(void)
{ double j, area;
printf(“Enter radius: “);
scanf(“%f”, &j); Parameter function
area = circleArea(j); call and return
printf(“Circle area. %d”,area); of value
Function Call
Function
No return value Use void Parameter
definition
With return value Use return Parameter and return
158
Activity 12.3
159
12.4.4 Variable scope
160
Figure 12.4b: Variables x and y as global variables
The next programme declares both variables x and y as global variables. Thus, it
can be reached in any of the functions in the programme.
#include <stdio.h>
int x, y; /* global variable */
void f1(void)
{
printf(“x = %d y = %d\n”, x, y);
}
void main(void)
{
printf(“Include two numbers: “);
scanf(“%d%d”, &x, &y);
f1();
}
161
Now, observe the next programme:
Programme 12.1
#include <stdio.h>
void calcSquare(float a, float b)
{
/*a and b are calSquare()’s local variables*/
b = a * a;
}
void main(void)
{
float x, y; /*main() function’s local variables */
x = 3;
y = 20;
calcSquare(x,y);
printf(“%1.1f square is %2.1f\n”, x, y);
}
Notice that x and y are local variables for the function main(), whereas a and b
are local variables in the calcSquare() function. When the programme starts to
execute, the main function becomes active and the local variables x and y are
created. Figure 12.5 below shows the state of the variables before calling the
calcSquare() function.
When the function calcSquare() is called, the memory space for variables a and b is
created. After that, the values x and y are sent to the function with respective values
copied into parameters a and b. The programme control is later transferred to the
calcSquare() function. Memory space that is created when the function is called is
shown in Figure 12.6
162
Figure 12.6: Memory states when the calcSquare()function is called
Let us try to look at the box above that represents the memory area for the entire
programme. The box labelled as main shows the memory area for the
function main(). Memory of local variables for the function which are x and y are
created from this memory area.
Two small boxes labelled x and y represent memory for both the variables. Just
like the main() function, a box labelled x and y represents memory space for
the caclSquare() function. Two small boxes labelled a and b in the box represent
memory area for local variables which are parameters a and b. Notice that the
values of a and b each represent values of x and y. This is because of parameter
passing that happens when the function calcSquare() is called.
Next, the statement in the calcSquare() function body is executed that makes the
value of the expression a * a is assigned to b. The result, value of b is now 9, as
shown in Figure 12.7.
163
Figure 12.7: Memory area after the execution of calcSquare()
function
The programme output above shows that the execution of the programme is not
what we had hoped. From the output, we found that the value of b did not change
after the call to calcSquare(). Even when the calcSquare() function does the square
calculation and keeps the value in b, the result of the calculation is not assigned to
y when returning from the function. This is why the value of y is still the same
before the call to the function.
We are allowed to name a local variable in a function the same name as another
variable in another function. This is because the local variables can only be
reached by the function that has declared it; therefore, there is no confusion when
the name is used to reach a variable in a function. As an example, consider the area
variable in the programme below:
164
#include <stdio.h>
double calcSquareArea(double width, double height)
{
double area; /*local variable */
area = width * height;
return area;
}
double calcCircleArea(double radius)
{
double area; /*local variable */
area = 22.0/7 * radius * radius;
return area;
}
void main(void)
{
double radius, l, t, area; /*local variables*/
printf(“Enter width and height: “);
scanf(“%f%f”, &l, &t);
area = calcSquareAread(l, t);
printf(“Square Area: %lf”, area);
printf(“Enter radius: “);
scanf(“%f”, &radius);
area = calcCircleArea(radius);
printf(“Circle Area: %lf”, area);
}
Notice that the name area was used to name three local variables, that were
declared in the main() function, calcSquareArea() and calcCircleArea(). Similarly
with the radius, it is used to name a variable in the main() function and another
variable in the calcCircleArea().
In the programme code above, every reference to the variable is matched to the
variable declaration. As an example, consider the statement area = 22.0/7 * radius
* radius; in the calcCircleArea() function. Radius referred to in the statement is to
the local variable radius in the function and not the variable radius in the
main()function.
C does not allow us to declare more than one local variable with the same name.
Nevertheless, we can declare a local variable that has the same name as a global
variable.
165
Consider the programme below:
#include <stdio.h>
int x, y; /* x and y are global variables */
void f1()
{
int x;
x = 0; /* local variables */
y = 0;
}
void main(void) {
x 10; y = 15; f1();
printf(“x = %d y = %d\n”, x, y);
}
In this programme, two global variables are declared as x and y. Function f1()
also declares a local variable by the name x. The arrow at the statement x = 0; in
function f1() shows that the reference to x in the statement is referring to the
local variable xand not the global variable x.
With that, the value of the global variable x does not change when the function
f1() is called in the main() function. On the other hand, f1()function has
changed the local variable y to 0. The output generated by the programme is
as follows:
x = 10 y=0
ACTIVITY 12.4
Use the tracing method as in Programme 14.1. What would happen in this last
example, when the value x does not change but y does?
166
Write the output that is generated by the programme below:
#include <stdio.h>
int A(int x)
{
printf(“Value received by A(): %d\n”, x);
x = x*x;
printf(“Value returned by A(): %d\n”, x);
return x;
}
void main(void)
{
int x;
x = 10;
printf(“Value of x in main() before sent to A(): %d\n”, x); A(x);
printf(“Value of x in main() after returning from A(): %d\n”, x);
}
When the C compiler compiles a function call, it will need information about the
function to be called. As an example, consider the following statement:
x = displaySquare(width, height);
With that, the compiler should report a compilation error when the statement
above is compiled. This error can only be traced if the compiler knows the
167
returntype of the displaySquare() function. This would not create a problem if
the compiler has compiled the function declaration before compiling the statement
above. Nevertheless, consider the programme below:
#include <stdio.h>
void main(void)
{
int width, height, x;
printf(“Enter width and height: “);
scanf(“%d%d”, &width, &height);
x = displaySquare(width, height);
}
void displaySquare(int width, int height)
{
int i, j;
for (i=0; i < height; i++)
{
for (j=0; j < width; j++)
printf(“*”);
printf(“\n”);
}
}
Notice that the displaySquare() function declaration is put after the function main()
that has the statement that calls the function. When the compiler compiles the
statement, it does not have the information about the displaySquare() function
because its declaration has not been compiled yet.
The reason for the function prototype is to provide information on the type of
value that is returned from the function (if have) and the number and type of each
parameter. The following function prototype is accepted because the names of the
parameters can be ignored.
168
However, putting a parameter name in the function prototype is good because
the user can know the reason for each of the function parameter.
Next is the programme with the function prototype displaySquare() inserted.
#include <stdio.h>
void displaySquare(intwidth, int height); Function prototype
void main(void)
{int width, height, x;
printf(“Enterwidth and height: “);
scanf(“%d%d”, &width, &height);
x = displaySquare(width,height); Function
} call
void displaySquare(intwidth, int height)
{
int i, j;
for (i=0; i < height; i++) { Function
for (j=0; j < width; j++) definition
printf(“*”);
printf(“\n”);
}
}
169
ACTIVITY 12.5
170
12.5. Recursion
Notice that (n-1)*(n-2)*...*1is the value for the factorial (n-1). In other words,
n! = n * (n-1) * (n-2) * ... * 1
= n * (n-1)!
The diagram on next page shows the calculation of the value for factorial 4based
on the observation above. To calculate the value of factorial 4, we would need to
get the value of factorial 3. Likewise, to calculate the value for factorial 3, we
would need to get the value of factorial 2. This continues until the value of
factorial 0 is needed to calculate factorial 1. Case 0! is a special case because
the formula above cannot be used for value of n which is equivalent to 0. For
this case, the factorial value of 0is defined as 1.
4! = 4* 3!
= 4* (3 * 2!)
= 4* (3 * (2 * 1!))
= 4* (3 * (2 * (1 * 0!)))
= 4* (3 * (2 * (1 * 1)))
= 4* (3 * (2 * 1))
= 4* (3 * 2)
= 4* 6
= 24
Based on the above, the formula to calculate the value of a factorial for a round
number n is shown below:
171
1, if n = 0
n! =
n*(n-1)!, if n > 0
We can write a function to calculate the value of a factorial based on this formula.
Notice the function factorial()code on the next page:
int factorial(int n)
{
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
172
Figure 12.8: Tracing of factorial (4)execution
Programme 12.2 below inputs a number between 0 and 15 and continuously calls
the function factorial()to calculate its factorial value for that number recursively.
Programme 12.2
/* Counting factorial value of n recursively */
#include <stdio.h>
void main(void) {
int n;
long int factorial(int);
printf(“Enter value n “);
scanf(“%d”, &n);
if ((n < 0) || (n > 15))
printf(“n is outside range\n”)
else
printf(“%d! = %ld\n”, n, factorial(n));
}
long int factorial(int n) {
if (n == 0)
return 1; /* stopping condition */
else
return (n * factorial(n-1));/* recursion */
}
Two things must be taken into consideration when we write recursive function
definition. Both regard the stopping of the function. The first is there and should
be a condition to stop the function. Once the condition is satisfied, the function
should not call itself. This is because as long as the function calls itself, the
execution will not end. This situation is called endless recursion. This is
shown by the following function definition:
void forever(void)
{
printf(“I will not end\n”);
forever();
}
Refer to the recursive function factorial() that we saw earlier. The condition to stop is
when the value of its parameter is zero, which is n==0. When this condition is met, the
function will immediately return the value 1 to its caller. The Figure below shows the
role of the condition in the execution of factorial(4).
173
The second is to ensure that for every call towards the recursive function, the
condition to stop has to be fulfilled at last. Consider the function printLines()
definition below:
void printLines(int i)
{
if (i <= 0)
return;
else
{
printf(“*”);
printLines(i-1);
}
}
This function will display recursively one line of ‘*’whose length is determined by
its parameter. For example, if we call printLines(10), ten ‘*’ characters will be
displayed on one line.
Consider the else part which contains the call to itself. The parameter that is
passed is i-1. This means that every time the function calls itself, the parameter
passed will decrease by one. This is so that the final call will be printLines(0) and
this will ensure that the stopping condition is fulfilled. Notice that the
stopping condition for the function is i <= 0and not i == 0. This is to ensure that
the function will end even when the parameter received is a negative value.
174
ACTIVITY 12.6
void main(void)
{
printf(“prod(-2): %ld\n”, prod(-2));
printf(“prod(0): %ld\n”, prod(0));
printf(“prod(1): %ld\n”, prod(1));
printf(“prod(8): %ld\n”, prod(8));
}
As an example, consider the problem drawing certain shapes to the screen. For
example, Figure 12.9 shows a stick-woman drawing.
175
*
*
* *
*
*
/\
/ \
/ \
--------
-
/\
/ \
/ \
Figure 12.9: Stick-woman
drawing
Notice that the stick-woman drawing is made up of an oval, a triangle and two
lines joined at an angle. Therefore, the problem of drawing a stick-woman can be
broken into three sub-problems.
Beginning Algorithm:
1. Draw Oval
2. Draw Triangle
3. Draw Two Lines Joined at an Angle
Let us say sub-problem 1 and sub-problem 3 can be solved directly. To solve sub-
problem 2, we see the triangle as two lines joined at an angle but with a
horizontal line. Therefore, we break sub-problem 2 into two sub-problems at the
next level as shown below:
Refining Step 2:
2. Draw Triangle
2.1. Draw Two Lines Joined at an Angle
2.2. Draw Horizontal Line
At this level, any sub-problem introduced can be solved easily. We can build a
structure chart like the one shown in Figure 12.10 that shows the original problem
and sub-problems and the relationship between them.
176
Figure 12.10: Structure Chart showing stick-woman drawing
177
Programme 12.3
/*Drawing Stick-Woman */
#include <stdio.h>
void draw_oval(void);
void draw_joinedLine(void)
void draw_horizontalLine(void);
void draw_triangle(void)
void main(void)
{
draw_oval();
draw_triangle();
draw_joinedLine ();
}
void draw_oval(void)
{
printf(“ ** \n”);
printf(“ * * \n”);
printf(“ * * \n”);
}
void draw_triangle(void)
{
draw_joinedLine();
draw_horizontalLine();
}
void draw_joinedLine(void)
{
printf(“ /\\\n”);
printf(“ / \\\n”);
printf(“/ \\\n”);
}
void draw_horizontalLine(void)
{
printf(“———\n”);
}
178
12.7. Summary
179
Unit13 File Manipulations
13.0. Introduction
In the examples that we have seen so far, the data manipulated by
programmes have either been hard coded or input by users through the
keyboard. The output generated was displayed on the video screens. This
type of input output is suitable for certain types of programmes, for
example, programmes that need to respond to users.
13.1. Objectives
By the end of this unit, you should be able to:
use C to support file manipulation
apply the fopen() and fclose() functions to open and close files
input data from file and channel output to a file using
special functions
C provides many types of support for file input output operations. With this
support, we can write C programmes to read data from files. Programme
data can be kept in data files that can be used repetitively. In addition, we
can write programs that channel output to files.
If the file is kept in hard disk media, we can get a permanent copy of
the programme output. File support that is available can also be used by
programmes to communicate with other programmes using file connections;
for example, a file which is being output from one programme is an input file
to another programme.
There are two types of file formats supported by C, which are text files
and binary files. This unit will concentrate on text files only. One way to
create a text file is to use a text editor. Text files are sequential characters
that are normally kept in secondary memory like hard disks.
180
Every text file will have a special character at the end of its file (end of file).
This character acts as an end of a file indicator. In addition, every line of
characters in the text file will end with a <newline> character. This
character is also special because it acts as a new line indicator.
Let us say we create a text file in a hard disk to keep these three
sentences. Assume that we did not press the enter key after typing the last
sentence.
Sentence 1.
Sentence 2.
Sentence 3.
In the hard disk, the characters that are contained in the file are kept in
sequential order as:
Notice that the new line character <newline> is put before the second
sentence and the third sentence. This is done so that when the file contents
are displayed, the sentences will be displayed on the next line. Notice also
that the character <eof> is put at the end of the file as an indicator
that there are no more characters after it.
There are two ways to access data kept in a file, sequential access or random
access. Ways of access influences how the data is read, written, updated and
deleted by the programme.
Only sequential file access will be discussed in this unit. Usually, there are
three operations that can be done to a sequential access file, which are create
file, edit (change, add), and delete data and reading a file.
181
13.3.1 The fopen() function
Before any operation can be carried out on a file, it must be opened first. In
C, when opening any file, we must send file name and access mode (either
we want to read, write or add data to a file). The relevant function used
is fopen(). Format to invoke (call) it is as below:
fopen(file_name, access_mode)
FILE *fptr;
Fptr = fopen(“datafile”’ “r”);
fptris a variable that is declared to keep the file pointer. After the calling
of fopen()function ends, the pointer pointing to the file “datafile”will be
returned by the function. The pointer will then be assigned to fptr.
Access mode of any file determines the operations that can be done on that
file. Table 13.1 shows the access modes that are specified in the
fopen()function calls.
182
The code segment below show the usage of fopen() function to open the file
input and file output. File input is opened for reading only whereas; file
outputis opened for writing only.
Sometimes the file that is required to be opened cannot be opened using the
fopen() function. For example, we want to open a file to be read, but the file
does not really exist. In this situation, the fopen() function will return a null
pointer (represented by the value NULL) if it fails to open the file in the
required mode.
It is important that we can trace the event so that the errors that cause the
file operation to return a null pointer can be avoided. The code segment below
shows how to trace the return of null pointer by fopen().
The if statement in the code segment tests whether the opening of inputfile is
successful or fails by testing if fptr is equivalent to NULL or not. If fptr is
NULL, it means that the file failed to be opened. If this happens an error
message will be displayed followed by calling of the exit()function. The
exit() function is a library function to stop execution of a programme. To use
it, we must use the header file stdlib.h together with the programme by
entering the pre- processor command at the beginning of the programme.
#include <stdlib.h>
When we have finished operating on a file, the file needs to be closed. The
fclose() function is a function to close a file.
183
Calls to the function to close a file is pointed to by a file pointer fptr as shown
below:
fclose(fptr);
#include <stdio.h>
#include <stdlib.h>
void main (void) {
FILE *fptr;
fptr = fopen(“datafile”, “r”);/*open file to read*/
if (fptr == NULL) {
printf(“File datafile cannot be opened\n”);
exit(1)
;
}
:
:
fclose(fptr); /* file closed */
}
We can use the fprintf() function to print all types of data from a file. The
syntax to call the function is as follows:
Calls to the fprintf() function is nearly the same as calling the printf()
function. The difference with printf() is that it has an additional parameter;
the first parameter is a file pointer to some output file.
184
Programme 13.1
The fscanf() function can be used to read many types of data from a file.
The syntax to use the function is as follows:
We will see later how the fscanf() function resembles the scanf() function; the
difference is in the fscanf() first parameter which is a file pointer to some
input file.
Programme 13.2 below reads data from file data1 and displays the data on the
screen. The data that is contained in the file is the metric number as well as
the grade for a group of students.
185
Programme 13.2
After the file data1 has been successfully opened, the programme will read
the first data in the file which is the total number of students. Based on the
number of students, the programme will loop to read the metric numbers, and
the grade for each student. An example of the file data1 that is appropriate to
the programme is given below:
186
File: data1
10
1101 C
1102 E
1202 A
1203 B
1302 B
1305 C
1306 D
1401 C
1402 B
1500 C
The first line in file data1 has the total number of students, which is 10. Each
line after that, has data for each student, which is the metric number,
followed by the grade. The output generated by the programme for the data
file is given below:
If the fscanf() function reaches the end of the file while reading, it will return
an EOF value. This value can be used as a sentinel value while reading data
from a file.
getc(FILE *ptr);
187
The ptr is a pointer that the file will read. The getc() function would return
the character that was read from the file. If the function returns an EOF value,
which means the end of the file has been reached.
Programme 13.3 aims to show the contents of a file to the screen. It uses the
getc() function to read the next character from the file and the putchar()
function is to display the character on the screen. This process continues
until getc() function reaches the end of the file.
Programme 13.3
#include <stdio.h>
#include <stdlib.h>
void main (void)
{
FILE *fptr;
char nfile[20]
char letter;
188
putc(int aks, FILE *ptr)
aks is a character that will be the output; whereas, ptr is a pointer to the output
file.
Programme 13.4 below uses the putc() function to copy the contents of an input
file to another output file.
Programme 13.4
/* Copy contents of one input file to another output file */
#include <stdio.h>
#include <stdlib.h>
void main (void) {
FILE *f_input, *f_output
char input_name[20];
char output_name[20];
char letter;
printf(“Enter input file name: “);
gets(input_name);
f_input = fopen(input_name, “r”);
if (f_input == NULL) {
printf(“Error in opening file %s\n”, input_name);
exit(1);
}
printf(“Enter output file name: “);
gets(output_name);
f_output = fopen(output_name, “w”);
if (f_output == NULL) {
printf(“Error to open file %s\n”,
output_name);
exit(1);
}
printf(“\nCopying File %s to file %s\n”, input_name, output_name);
while ((letter = getc(f_input)) != EOF)
putc(letter, f_output);
fclose(f_input);
fclose(f_output);
}
189
ACTIVITY 13.1
1. So far, you have learnt a few instructions in this unit. Can you
state the use of these?
Instruction Usage
1. fopen()
2. fclose()
3. fprintf()
4. fscanf()
5. getc
6. putc
190
3. Consider the programme code below:
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
FILE
*fptr;
int length, height, num, i;
fptr = fopen(“input”, “r”);
if (fptr == NULL)
{
printf(“Numbers File cannot be opened.”);
exit(1);
}
fscanf(fptr, “%d”, &bil);
for (i=0; i < num; i++)
display(i,num);
fclose(fptr);
}
void display(int length, int height)
{
int i, j;
for (i=0; i < height; i++)
{
for (j=0; j < height; j++)
printf(“*”);
printf(“\n”);
}
}
Write the output that will be generated if the contents of input file
is as this: 3
191
13.4. Summary
192
Blank page
Unit 14 Case Study
14.0. Introduction
In this unit, we will see complete samples to two problems. The first
problem is on writing programmes using user-driven menu selection. The
second problem is on writing programmes to display a calendar for any
year. For both problems, explanation on development process will be given.
14.1. Objectives
By the end of this unit, you should be able to:
develop a programme using steps shown
14.2.1 Problem
One technique of interaction between programme and user is using the menu.
Menu is a list of items that can be selected by the user. Once the menu is
displayed, the programme will wait for the user to input their choice. After
the user has chosen, the programme will continue processing based on the
chosen item.
In this section, we will develop a programme that will do these
conversions:
• convert time from minutes into hours
• convert distance from centimetres to metres
• convert temperature from Fahrenheit to Celsius.
The programme 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 display the result. Then, the programme will display the
menu again and the process will continue until the user decides to stop the
program.
193
14.2.2 Analysis
1 hour = 60 minutes
1 metre = 100 cm
1 Celsius = (5/9) * (Fahrenheit - 32)
14.2.3 Design
Variable Explanation
Choice users choice from the menu
Minutes value of minutes input by the user
Hour keeps the converted value from minutes to hours
cm value of cm input by the user
Metres keeps the converted value from cm to metres
194
Fahrenheit value of Fahrenheit input by the user
Celsius keeps converted value from Fahrenheit to Celsius
Beginning Algorithm
1. Start
2. Do
2.1 Choose conversion type
2.2 IF (1 <= choice and choice <= 3) Start_IF
a. Do the conversion and display the result
End_IF
End_DO (choice != 4)
3. End
Notice how the 2nd step involves a loop to repeat Step 2.1 and Step 2.2
until the user chooses to stop the programme when the choice value is 4.
195
2.2a.3 If else if (choice == 3) start if
a. Do temperature conversion
b. Display fahrenheit and celsius
end if
14.2.4 Implementation
196
Programme 14.1
/* Programme to convert time, distance and temperature */
#include <stdio.h>
void main(void) {
int choice;
int min;
Activity 14.1 /* minutes */
float hr; /* hour */
float cm; /* centimetre */
float mtr; /* meter */
float fahr;/* fahrenheit */
float celc;/* celsius */
do {
/* display menu */
printf(“\n\t\tCONVERTER\n”);
printf(“\t\t==================\n”);
printf(“\t1. Time: minutes to hours\n”);
printf(“\t2. Distance: cm to meters\n”);
printf(“\t3.Temperature:Fahrenheit to Celsius\n”);
printf(“\t4. Program End\n”);
printf(“\tYour Choice: “);
scanf(“%d”, &choice);
197
case 3 :
printf(“Temperaturein Fahrenheit: “);
scanf(“%f”, &fahr);
celc = (5.0/9.0) * (fahr - 32);
printf(“%.2f Fahr = %.2f Celcius\n”,fahr,celc);
break;
}
}
} while (choice != 4);
}
ACTIVITY 14.1
14.3. Summary
198
References
A number of reference lists can be found on the internet but the following texts
are important to all the units.
Kelly and Pohl, (1998) ‘‘A Book on C’’ fourth edition, Addison-Wesley.
199