0% found this document useful (0 votes)
8 views410 pages

c4PT (A) C Textbook 04S209

This document is a textbook on programming techniques in C, covering various topics such as programming languages, variables, constants, and data types. It includes chapters on program development, logic, selection structures, modular design, functions, iteration, arrays, and file handling, along with case studies and review questions. The textbook is designed to provide a comprehensive understanding of C programming and its applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views410 pages

c4PT (A) C Textbook 04S209

This document is a textbook on programming techniques in C, covering various topics such as programming languages, variables, constants, and data types. It includes chapters on program development, logic, selection structures, modular design, functions, iteration, arrays, and file handling, along with case studies and review questions. The textbook is designed to provide a comprehensive understanding of C programming and its applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 410

PROGRAMMING

TECHNIQUES in C
c4PT(A)_C_Textbook_04S209.doc

Incorporating components of
B070A Create Code for applications.

TEXTBOOK

Copyright Notice
The Information Technology Department of TAFESA copyrights this publication.
This publication may not be reproduced or transmitted in any form or by any means, electronic or mechanical, including
photocopying, recording, storage in an information retrieval system, or otherwise, without the permission of the copyright
holder.
CONTENTS

Chapter 1 – Introducing C ................................................... 1


Overview................................................................................................................................ 2
Programming Languages.......................................................................................................... 2
Introducing ANSI C................................................................................................................ 5
Variables ................................................................................................................................ 7
Constants.............................................................................................................................. 11
Example - Simple Calculation................................................................................................ 15
Chapter 1 Review Questions ................................................................................................. 31

Chapter 2 - Simple Sequence Programs............................ 32


Overview.............................................................................................................................. 33
C variables and constants...................................................................................................... 33
INPUT in C- The scanf statement.......................................................................................... 35
PROCESSING .................................................................................................................... 36
OUTPUT - printf statement................................................................................................... 37
Pausing Program Output........................................................................................................ 38
Example Programs ................................................................................................................ 40
Simple Debugging ................................................................................................................. 44
Case study PFeeCalc (Placement Fee Calculator).................................................................. 49
Case study - PFeeCal1 ......................................................................................................... 55
Chapter 2 Review Questions ................................................................................................. 56

Chapter 3 - Program Development.................................... 57


Overview.............................................................................................................................. 58
Program development ........................................................................................................... 58
Problem Definition and Program Specification........................................................................ 61
Structured Programs ............................................................................................................. 66
Pseudocode.......................................................................................................................... 66
An Alternative to PseudoCode - Nassi-Shneiderman Diagrams.............................................. 68
More on Documentation........................................................................................................ 71
Documented Examples.......................................................................................................... 72
Case study – PFeeCal2......................................................................................................... 78
Chapter 3 Review Questions ................................................................................................. 79
CONTENTS

Chapter 4 - Logic and expressions.................................... 81


Overview.............................................................................................................................. 82
Logical Expressions............................................................................................................... 82
Additional C operators.......................................................................................................... 86

Chapter 5 - Selection: IF Structure................................... 89


Overview.............................................................................................................................. 90
Selection Using Pseudocode.................................................................................................. 90
Selection - C Code ............................................................................................................... 93
Selection Examples ............................................................................................................... 95
Documented Examples.......................................................................................................... 97
Case Study - PFeeCal3 ...................................................................................................... 109

Chapter 6 - Selection: Nested IF Structure .................... 111


Overview............................................................................................................................ 112
Nested IF structures............................................................................................................ 112

Chapter 7 - Selection: Case Structure............................. 123


Overview............................................................................................................................ 124
CASE structures ................................................................................................................. 124
Program testing................................................................................................................... 131
Chapter 7 – Selction Structure Review Questions ................................................................ 136

Chapter 8 - Modular Program Design ............................ 137


Overview............................................................................................................................ 138
Why Use Modular Design? ................................................................................................. 138
Using Modules.................................................................................................................... 140
Scope and Life of Variables ................................................................................................ 144

Chapter 9 - Functions ....................................................... 148


Overview............................................................................................................................ 149
Using functions in C............................................................................................................. 149
Parameter passing............................................................................................................... 155
Case Study - PFeeCal4 ...................................................................................................... 163
CONTENTS
Chapter 9 – Review Questions ............................................................................................ 163

Chapter 10 – Iteration: The While Loop ........................ 164


Overview............................................................................................................................ 165
Types Of Iteration............................................................................................................... 165
The While Loop.................................................................................................................. 166
Data validation.................................................................................................................... 167
Sentinel controlled processing.............................................................................................. 170
Nested while loops in C ...................................................................................................... 178
Debugging loops ................................................................................................................. 187
Case Study - PFeeCal5 ...................................................................................................... 194

Chapter 11 - Iteration: The Repeat Until Loop.............. 195


Overview............................................................................................................................ 196
Post-test Loops .................................................................................................................. 196
Applications of Repeat Loops ............................................................................................. 198
Case Study - PFeeCal6 ...................................................................................................... 208
Case Study – PFeeCal7 ...................................................................................................... 208

Chapter 12 - Iteration: The For Loop............................. 209


Overview............................................................................................................................ 210
FOR loops.......................................................................................................................... 210
Choosing The Appropriate Loop......................................................................................... 214
Nested For Loops .............................................................................................................. 214
Chapter 12 – Iteration Structure Review Questions.............................................................. 218

Chapter 13 - Strings......................................................... 219


Overview............................................................................................................................ 220
String Facilities in C............................................................................................................. 220
String Functions .................................................................................................................. 222

Chapter 14 - One-dimensional Arrays ............................ 235


Overview............................................................................................................................ 236
Introducing Arrays .............................................................................................................. 236
Input and Output of Arrays.................................................................................................. 240
CONTENTS
Common Array Manipulation Tasks .................................................................................... 244
Arrays as parameters .......................................................................................................... 247
Worked Example................................................................................................................ 249
Passing a Character Array to a Function. ............................................................................. 255
Case Study - PFeeCal8 ...................................................................................................... 260
Chapter 14 – Arrays Review Questions............................................................................... 260

Chapter 15 - Combining Techniques............................... 261


Overview............................................................................................................................ 262
Quick Review..................................................................................................................... 262

Chapter 16 - Text Files ..................................................... 265


Overview............................................................................................................................ 266
What Is A File?................................................................................................................... 266
Why Use A File? ................................................................................................................ 266
Using Data Files In Programs .............................................................................................. 267
Open a file .......................................................................................................................... 267
Read from a file................................................................................................................... 268
Close a file.......................................................................................................................... 268
Processing The Data In A File ............................................................................................. 268
Write to a file ...................................................................................................................... 271
Append to a file .................................................................................................................. 272
Make a copy of a file .......................................................................................................... 272
Chapter 16 Review Questions ............................................................................................. 274

APPENDIX A – Integrated Development Environment 275


Installing the C IDE............................................................................................................. 278

APPENDIX B – NS Diagrams and Flowcharts............... 279


Nassi-Shneiderman Diagrams.............................................................................................. 279
Selection Using NS Diagrams.............................................................................................. 282
Flowcharts:......................................................................................................................... 288
Flowcharts for sequence...................................................................................................... 288
Basic symbols ..................................................................................................................... 288
Selection With Flowcharts................................................................................................... 292
CONTENTS
Iteration With Flowcharts.................................................................................................... 297
CONTENTS

APPENDIX C – C Programming Standards .................. 301

1. C Programming standards ........................................... 301


1.1. Object Naming Conventions......................................................................................... 302
1.2. Simple Declarations...................................................................................................... 303
1.3. Complex Declarations .................................................................................................. 303
1.4. Functions ..................................................................................................................... 304
1.5. Code Blocks................................................................................................................ 304
1.6. Executable Statements.................................................................................................. 305
1.7. Expressions.................................................................................................................. 305
1.8. Flow Control ............................................................................................................... 307
1.9. Comments ................................................................................................................... 308
1.10. Defined Constants...................................................................................................... 310

APPENDIX D – Textbook Exercises Selected Solutions 311

APPENDIX E - Case Study PfeeCal Solutions ............... 377

Glossary.............................................................................. 400
Page 8
CHAPTER 1 – INTRODUCING C
Upon successful completion of this chapter you will be able to:

• Identify past and current programming languages, including C

• Understand the difference between interpreters and compilers

• Define a variable

• Define a constant

• Define a data type

• Use standard naming conventions for variables and constants

• Enter the C code, compile and run some example programs

Summary of new terms:

Assembly language - a language very close to machine language.


Procedure-oriented language – a language closer to the English language designed to be used for
a certain type of problem
Object-oriented programming language - based on the design of objects.
Interpreter - translates a single program line into machine code and if there are no errors the code
is immediately executed.
Compiler - translates the whole code into a machine code file before the program is executed.
Variable - allows us to refer to the area of memory via a more meaningful English name.
Constant – a meaningful English name given to data that does not change during the running of the
program.
Datatype - the type of data to be stored needs to be defined when the variable is created.
ANSI C - American National Standards Institute standard for the C language.
ASCII - American Standard Code for Information Interchange.

Page 1
OVERVIEW
This chapter gives an overview of the past and current programming languages, including C. It gives
an explanation on how the compiler works. The important concepts of variables, constants and
datatypes are covered. The chapter concludes with some example programs to try.

PROGRAMMING LANGUAGES
The processor (CPU) of a computer operates at a very primitive level, using instruction codes that
perform operations such as moving data from place to place, doing arithmetic and comparing data.
These instruction codes are called machine language.

Programming in machine language is possible, but very difficult and inefficient. During the last 50
years, many programming languages have evolved to make the task easier. Programming languages
allow a task to be described using a notation, which is closer to English or to standard mathematical
notation, and with the structure of the program more obvious. This can operate at three levels:

• Assembly language.

• Procedure-orientated languages.

• Object-orientated languages.

Assembly language

It is possible to program a computer in a language very close to the machine language. This is
assembly language, where the instructions of the CPU are represented by symbolic codes called
mnemonics. Assembly language programming is a tedious business. It was commonly used for
operating systems, device drivers and so on. It is rarely used these days, although some device
drivers and other low-level software are still sometimes written in assembly language.

Machine code Assembly language


00101111 01001010 ADD 74
00010000 00000011 MUL 3

A special program called an assembler translates the assembly language to machine code. Writing in
assembly language is still a tedious task since an assembly language instruction still represents only 1
machine code instruction. However, it is simpler than writing in machine code because the
mnemonics are easier to remember.

Procedure-orientated Languages

Programming languages like FORTRAN, COBOL, BASIC were designed to be used for a certain
type of problem, (e.g. FORTRAN code looks very algebraic and is used for scientific applications).
These languages are sometimes classified as procedure-oriented languages.
Page 2
High-level languages are written according to a set of rules called syntax. Standard versions exist
and so they are machine independent. Procedure-oriented language programs need to be translated
to machine code by a translating program. These translating programs are known as compilers or
interpreters.

When a translator detects a (syntax) error in a procedure-oriented language program, an error


message is given which makes the task of programming easier. Since actual English words and
familiar sentence-like structures are used, procedure-oriented language programs are said to be self-
documenting.

BASIC
• Stands for Beginners All Purpose Symbolic Instruction Code.
• Developed in 1964 as a language to learn programming.
• Many different versions/dialects existed e.g. GWBASIC, Commodore 64 Basic,
QuickBasic, Visual Basic, now dominated by VB.net
• Earlier versions encouraged unstructured programming e.g. GWBASIC.

PASCAL
• Developed in 1968 for teaching programming, now replaced by C or Java as a teaching tool.
• Encourages the writing of structured programs.
• Can be used on a wide variety of hardware platforms. E.g. mini, micro, mainframe.
• Easy to learn and use.
• Often used for applications programming e.g. accounting packages.

FORTRAN
• Considered the first programming language (developed in 1957).
• Designed for use by scientists, engineers, and mathematicians.
• Suitable for programming mathematical equations.

C
• A low level language used to develop operating systems
• Close relationship with UNIX.
• A high level language used as a procedural language to encourage the writing of structured
programs.
• Is portable.

Object-Orientated Languages
The increasing use of graphical user interfaces encouraged the development of object-oriented
languages. Object-oriented programming languages are based on the design of objects. An object is
a collection of data and the procedures that can be performed on it. A button on the screen is a
typical object. Its data consists of its size, position, colour and the text on the button. The procedures
that can be performed on it include creation, deletion, and reacting to a mouse click on the button.

Page 3
In practice, object-orientated languages work in a similar way to procedural languages. They must
be translated by a compiler or interpreter. The programs themselves are highly structured, and often
call upon a large library of object types supplied by the language (for the commonly used objects of
graphical user interfaces and databases, for example).

The most commonly used object-orientated languages are:


C++
This is an object-oriented version of C. It is probably the most commonly used programming
language at present, but it’s certainly not the easiest object-orientated programming language
to learn or use.
Java
Java is also based on C, but it tidies up many of the inconsistencies of the C syntax and
structure. The Java compiler does not translate the program into the machine code for a
particular processor, but into a special code for a Java virtual machine (JVM). All computers
can simulate the JVM, so a compiled Java program can be run on any computer. Java is
therefore much used on the Internet.
C#
C# is an object-orientated language built with the hindsight of many languages, mostly Java
and C++. It was introduced in 2000 for Microsoft’s new .NET platform. It is now
considered to be the programming language to use when programming within the .NET
architecture.
VBA
Visual Basic for Applications is an object-based extension of Basic used for writing macros
in Microsoft Office applications. VBA is considered to be object based rather than object
oriented.
VB.NET
A new version of Microsoft’s popular language VB. VB.NET, is a fully object-oriented
language.
Delphi
Delphi is an object-oriented version of Pascal. It allows very easy development of programs
using graphical user interfaces and databases.

Interpreters and Compilers


Interpreters
1. Translate a single program line into machine code and if there are no errors, (i.e. translation
errors) the code is immediately executed.
2. Step 1 is repeated for each program line until all lines have been translated and executed or
until there is a translation error.
3. If a translation error occurs the interpreter displays an error message and the translation and
execution process stops.
4. Every time the program is run it needs to be re-translated.

Older languages such as BASIC or DBASE IV are examples of languages that use interpreters.
Page 4
Compilers
A compiler translates each piece of code only once before the program is executed. In addition, the
object code created can be saved to disk therefore the program code does not have to be re-
translated every time it needs to run, although code must be re-compiled if changes are made to the
program.

1. If there are no translation errors the entire program is translated into object code.
2. The object code is then linked with any code from a language library to create the machine
code, which is stored in memory or on disk until execution is required.

Note:
• The compiler does not execute the machine code (the operating system does this!).
Therefore you do not need the compiler to run a .exe file.
• Every time the program is run it does not need to be recompiled (except if the source code
is changed).

In C, the programmer creates a text file, for example Eg1.c, which can actually be created using any
text file editor such as notepad but then compiled with a C compiler.

Library
Objects

Compile Link

Eg1.c Eg1.obj Eg1.exe

Source Code Object Code Executable Image

There is actually another step carried out before compiling. The preprocessor modifies the source
code before being sent to the compiler. There are a number of ways the source code can be
modified such as including another file or replacing text. These are textual changes to the actual
content of the source code and are not concerned with the rules of the language as this is what the
compilation step does. Commands to the preprocessor are identified by the # (hash) symbol. The
only two commands that we need to use at this level are:
#include
#define
These commands are called preprocessing directives.

INTRODUCING ANSI C
C was originally designed in 1972 by Dennis Ritchie at Bell Laboratories and was built to run on a
PDP-11 with a UNIX operating system. It was based on B (Thompson 1970), which in turn was
derived from the British language BCPL (1967). The original concept was to provide programmers
with a useful tool incorporating a wide range of operations from high level to low level, almost
reaching the Assembly Language level.

Page 5
C offers substantial programming freedom and flexibility. This freedom however, can create un-
readable and un-maintainable software. Therefore, greater programmer responsibility is required
to maintain good programming standards.

In 1983, the American National Standards Institute formed a technical subcommittee on C language
standardisations, X3J11, to provide a standard for the C language, its run-time libraries, and its
compilation and execution environments. The standard was finalised in 1988 and is equivalent to the
International Standards Organisation (ISO) standard. Some revisions of the standards have taken
place over the past years. The latest version of the C standard, approved in 1999, is officially known
as ISO/IEC 9899-1999 and is often referred to as C99. These standards define what is in the
language.

See the appendix for the C programming coding standards used in this book.

The only real way to learn a programming language is through practice. Even though much of what
you will do in this chapter will be revisited we need to get our hands dirty sooner rather than later.
Do not worry if you do not understand every detail of the following examples.

Features of C
C is a general purpose language, which offers: -

- economies of expression
if ((ch = getchar()) !=EOF)
- the standard control structures
while, for, do, if-else, switch etc.
- a wide range of data types
int, float, array, pointers etc.
- a wide range of operators
+ - / * < > << >> etc.
- modular design
functions

C - the good side

• A standard has been defined - American National Standards Institute (ANSI) and International
Standards Organisation (ISO) identical standards

• C programs are generally faster than those created in other languages as it closer to the
hardware than other languages.

• C is memory efficient because of the lack of built in features. These features must be included as
required.

• Theoretically C programs are easily transported from one hardware platform to another. ANSI
C compilers are available on almost all recent hardware.

• Good support for structured design through the use of Functions.

Page 6
• C offers a clean interface into the Assembly Language level.

• Large support libraries exist, offering a wide range of additional features.

• C provides ready access to the lower levels, providing support for specialist hardware.

C - the bad side

• Due to the lack of strong type checking it is easy to produce obscure and hard to solve bugs.

• A lack of run time checking can produce more obscure and hard to solve bugs.

• The ability to produce concise and brief code can make for un-readable and un-maintainable
software. This puts the onus on the programmer to maintain good standards.

The standards and conventions used in this book will hopefully eliminate the “bad side” of C
programming and help you to develop structured, easy-to-read C code!

VARIABLES
When programs are run, values for data items used during input, processing and output are stored in
the computer’s memory. Before we can do anything with the data in a program we must get it “into”
the computer. How do we store data in the computer for our programs to use?

All data to be manipulated must be in main memory first. Each memory location is numbered –
it has an address. Rather than refer to memory via the numeric address, defining a variable allows us
to refer to the area of memory via a more meaningful English name. Essentially a variable is a
symbolic named place in memory where data is stored.

The type of data to be stored needs to be defined when the variable is created. For example whether
a whole number, a number with a fractional component, a single character or a collection of
characters (known as a string) is to be stored. This is very important because the computer needs to
know how to interpret the binary data stored at that address when we use the variable in our
programs. We refer to this as the variables Datatype or just Type.

Consider the following example. A variable called Age has been defined which points to a memory
address that has the 8 bit binary code 01000001 stored in it.

Variable Name Memory address Binary code stored in memory

Age 01000001

Page 7
This binary code can be interpreted in two ways:
1. An integer using binary arithmetic will give the whole number (integer) 65.

0 1 0 0 0 0 1
1 x 20 = 1
0 x 21 = 0
0 x 22 = 0
0 x 23 = 0
0 x 24 = 0
0 x 25 = 0
1 x 26 = 64
0 x 27 = 0
Total = 65

OR

2. An ASCII code (American Standard Code for Information Interchange) that represents the
capital letter ‘A’.

The computer has the problem – how is the binary number going to be interpreted – as the whole
number 65 or the ASCII character ‘A’? The answer is that we must tell the computer how to
interpret the binary code by stating the datatype of the variable when it is declared.

Obviously if we have called our variable Age, we want the computer to interpret the binary code as
the number 65 so that the datatype will be defined as an integer.

The data stored in a variable can change in value but the “type” of data, its datatype, cannot change
once the variable has been defined.

In summary a variable has 3 main attributes

1. A variable name that refers to an address in the computer’s memory.


2. A datatype that tells the computer how much space to allocate for the variable and how to
interpret the binary code stored in memory.
3. A current value that is stored in the computer’s memory.

Naming Conventions for Variables

As discussed, variables are symbolic names we give to a memory location. The actual location in the
computer’s memory used to store the value is invisible to the programmer and usually of no concern.
There are few limitations in choosing the names for variables, but here are a few guidelines:

1. Use a meaningful name, e.g. a variable used to store the hours should not be called X, use a
word that describes the variable such as Hours or Hrs (an obvious abbreviation.)

2. Always start the variable name with a capital letter, not a number or any other special
character. Use a combination of upper and lower case to improve the readability of the
name, e.g. grosswage could be written as GrossWage.

Page 8
3. Never have spaces within the variable name.

As stated always be as descriptive as possible when choosing your variable names. In C you must
be careful not to use reserved words though. Reserved words are special words used by a language
to describe and express the language. They have special meaning and must only be used for that
meaning. The following gives a list of some commonly used keywords used in ANSI C.

case char const default do


else float for if int
return of switch void while

Apart from these general guidelines, there are usually standards, which exist depending on the
specific programming language being used and the business you are working for.

Standard Data Types

What are the different types of data that computer deal with and those most programming languages
are able to handle?

Integer
Holds only whole numbers e.g. -1, 0, 3, 57. Integers are often used for counter variables or when
the program requires a whole number for a particular operation. Integers are stored using the binary
number system. An advantage of using integers is that calculations (such as addition, multiplication
etc.) are exact which is in contrast to numbers with decimal components called real numbers.

In this book we will be using the datatype int to store integers.

Real Numbers
Holds numbers that include decimal places e.g. 14.75. The numbers stored may only be
approximates as they are often rounded off. For example, the exact value of 1/3 cannot be displayed
in decimal format so the real data type would store it as 0.3333. Reals are often used to store the
results of calculations or when an input is expected to contain decimal places. Real numbers are
stored using the floating-point representation. The name floating-point comes about for its ability to
store the fractional component by moving the decimal point to a different position and then storing
two separated integer values. For example decimal value of 125.468 in floating-point representation
3
would be .125468 * 10 . The two integer numbers stored are 125468, this is called the mantissa
and 3, this is called the exponent. Notice we have derived these two numbers by moving (floating)
the decimal point three places to the left.

In C we will be using the datatype float to store real numbers.

Page 9
Character
Holds only a single character. The types of characters, which can be stored, include digits (0-9),
letters (a-z) or special symbols ($,*,#,!). The computer stores characters by converting them to an
integer according to a predefined table. The most common table is the ASCII character set
(American Standard Code for Information Interchange).

In C we will be using the datatype char to store characters.

String
A string datatype is a sequence or collection of characters.

The sequence of characters in a string data item can be combinations of any of the following:

1. Upper case alphabetic characters (e.g. A).


2. Lower case alphabetic characters (e.g. a).
3. Numeric characters (e.g. 9).
4. Other keyboard characters (e.g. *).
5. Other characters from the ASCII character set (e.g.J).

Note that although a string data item may be a sequence of numeric characters (e.g. “5072”), this
string data item cannot be used in arithmetic calculations.

There are a number of techniques for storing string data but essentially they all involve storing each
characters ASCII value and, in some way, a count of the number of characters in the string.

In C we will be using the datatype an array of char to store a string. This will be covered in a later
chapter.

Boolean
This data type can contain only two values, those that represent either True or False. Some
programming languages have a boolean datatype so that variables can be declared with true/false
values. There was no boolean datatype in older versions of ANSI C, but programmers can still use
the concept when required. This is normally done using the integer datatype.

Declaring Variables in a C Program

Below is in an example of how to declare variables in the ANSI C programming language:

float TotalPay = 0;
int HoursWorked = 0.0;
char FirstInitial = 0;

Page 10
To declare one or more variables in a program:

1. Start with the datatype e.g. float. This tells the compiler that the following program element will
be a variable. It also tells the computer how much space to allocate for the variable and how to
interpret the binary code stored in memory.
2. Give the variable a name e.g. TotalPay.
3. Initialise the variable. Give it a current value, usually zero for numeric data.
4. End the variable declaration with a semi-colon (;).

You can now use the variable TotalPay in your program to store a variety of different values during
the running of the program.

CONSTANTS
Programs also need to deal with data that does not change during the running of the program. These
are known as constants. A constant can appear in a program literally, such as the number 1.5 or we
may choose to give the constant a name such as, CHARGE_PER_KILOGRAM. Hence we have
two types of constants, literals eg 1.5, ‘Y’, “END”, 150 etc. and symbolic constants eg
CHARGE_PER_KILOGRAM, CONTINUE_VALUE, FINISH_INDICATOR, MAX_AGE. It
is important to realise that constants, whether literal or symbolic, still use memory and still are of a
certain datatype. For example in the C language the number 120 would be of type int (short for
integer, a whole number) whereas 120.6 would be of type float (real number).

Naming Conventions for Constants

As discussed, symbolic constants are English names we give to a literal constant.

Here are a few guidelines to help with naming constants:

1. Use a meaningful name.


For example, a constant used to store the inflation rate should not be called X, use a word that
describes the constant such as INFLATION_RATE.

2. Always start the constant name with a letter, not a number or any other special character. All
constants should be written in UPPERCASE.

3. Use the underscore character _ to improve the readability of the name. As shown in the above
example INFLATION_RATE is more readable than INFLATIONRATE.

4. Never have spaces within the constant name.

Apart from these general guidelines, there are usually standards, which exist depending on the
specific programming language being used and the business you are working for.

Page 11
Declaring Constants in a C Program

Below is in an example of how to declare a constant in the ANSI C programming language:

#define INFLATION_RATE 0.15

To declare a constant in a C program:

1. Start with the directive #define.


2. Give the constant a name e.g. INFLATION_RATE.
3. Give the constant its value.

Note common errors to be aware of:


There is no semicolon at the end of the #define statement. Also note there is no equal (=) sign
inbetween the constant name and its value.
You can now use the constant INFLATION_RATE anywhere in your program and it will always
use the value 0.15.

Why use Constants?


A constant is defined and given a value at the start of the program. The constant name is then used
throughout the code where necessary. For example, a constant GST could be defined as 10 using

#define GST 10

The symbolic constant name GST is then used throughout the code rather than the literal constant 10.
If GST increases to 12, the value 12 only needs to be changed once where GST is defined:

#define GST 12

The body of the code does not need to be changed since it used the constant name GST rather than
the literal constant 10. If a literal constant of 10 was used throughout the code then the programmer
would have to replace every occurrence of the literal constant 10 with the literal constant 12.

Using Variables and Constants


A program to calculate the discounted price of goods purchased after receiving a fixed amount of
discount of 10% may contain the following statement

DisountedPrice = RetailPrice – RetailPrice * 0.10

For this program it would be expected that the input (the retail price) and the output (the discounted
price) would vary each time the program was run. These data items would be represented by
variables. However, the discount rate (0.10) would be the same each time the program was run and
this data item would be represented by a constant. In the example the constant shown is a literal.

The use of symbolic constants (also known as named constants) is valuable for reducing errors in
programs where the same data value is used many times and for making programs more readable. In
the calculation of the discounted price the statement would be better written using a symbolic
constant, DISCOUNT_RATE. In C this would appear as:

Page 12
#define DISCOUNT_RATE 0.10
.
.
DisountedPrice = RetailPrice – RetailPrice * DISCOUNT_RATE

Example – constants and variables

In the formula which calculates the Tax on a given GrossPay:

Tax = (GrossPay - BASE) * 0.20

Base is a symbolic constant (it will be given a value such as 100 in the declarations of a program) but
0.20 (the tax rate of 20%) is a literal constant.

So in the above example:


Tax and GrossPay are variables.
Base is a symbolic constant.
0.20 is a literal constant.

Page 13
Datatypes in C
There are several different datatypes available in C for our variables, and as you have seen you
define the type when you declare the variable. The following table summarises the available
datatypes in C, but don’t panic, the three shown in bold italic are the most common, and the ones
you will be expected to be more familiar with.

Type Size (bits) Range


char 8 -128 to 127
unsigned char 8 0 to 255
signed char 8 -128 to 127

int 16 -32,768 to 32,767


unsigned int 16 0 to 65,535
signed int 16 -32,768 to 32,767

short int 16 -32,768 to 32,767


unsigned short int 16 0 to 65,535
signed short int 16 -32,768 to 32,767

enum 16 -32,768 to 32,767

long 32 -2,147,483,648 to 2,147,483,647


long int 32 -2,147,483,648 to 2,147,483,647
signed long int 32 -2,1%w,483,648 to 2,147,483,647
unsigned long 32 0 to 4,294,967,295

float 32 3.4 x 10-38 to 3.4 x 1038

double 64 1.7 x 10-308 to 1.7 x 10308

long double 80 3.4 x 10-4932 to 1.1 x 104932

The other very important datatype in C is pointer. It is not classified as a basic datatype but
understanding pointers is crucial when programming in C, we will spend a lot of time on pointers in
later chapters.

You would have noticed that there is no Boolean or string datatype in C. This is correct. Boolean
and Strings are handled in special ways in C. A later section will explain how C can still handle
Boolean and string data but there is no simple in-built datatype.

Page 14
EXAMPLE - SIMPLE CALCULATION

PROGRAM SPECIFICATION

Description
A program to calculate the sum of two numbers

Inputs
Name Description Legal Values Data Type Source
First First number entered No restriction Integer keyboard
Second Second number entered No restriction Integer keyboard

Processing
Calculate Sum = First + Second

Outputs
Name Description Destination
Sum Sum of numbers screen

Overall Tasks
Input numbers
Calculate Sum
Output Sum

PSEUDOCODE
PROGRAM Sum
INPUT First
INPUT Second
Sum = First + Second
OUTPUT Sum
END Sum

Page 15
C Code
1. /**********************************************************************
2. * Program | Sum
3. * Author | Your name goes here
4. * Date written | The date goes here
5. * System | MS-DOS
6. *---------------+
7. * Function | Input two numbers and print their sum.
8. */
9.
#include <stdio.h>
#include <conio.h>

int main(void)
{
int First = 0;
int Second = 0;
int Sum = 0;

clrscr();
printf("*** Program example ***\n\n");

printf("Enter first number > ");


scanf("%i", &First);
printf("Enter second number > ");
scanf("%i", &Second);
Sum = First + Second;
printf("The sum is %i\n", Sum);

printf("< Press Any key to continue >");


getch();
return 0;
}

Page 16
General points about C programs

There a several key points to note about the above program.

1. C is case dependent. Therefore, it is quite legal to declare several variables with the same
name but different case. For example, the variables surname, Surname, SURname and
SURNAME would all be treated as different variables in C. This can lead to dangerous
programs and should be avoided.

2. There are no limitations on the layout of a C program. The programmer designs the layout of the
program. Providing the programmer thinks about this layout, more readable software will be
produced. You should follow the standards given for program layout.

3. All C programs consist of one or more functions. In these programs we have declared a function
main and called a function printf and scanf.

Every program must have a function main and execution of the program begins on the first
executable line after the declaration.

Usually a function will perform a specific task then return a result to the calling function. In these
programs main calls printf to display "Hello world".

4. Keywords are special words used by a language to describe and express the language. These
keywords are not usable for function names, variables or constants. They have special meaning
and must only be used for that meaning. The following table gives a complete list of keywords
used in ANSI C.

auto break case char const continue default do double else enum extern float for
goto if int long register return short signed sizeof static struct switch typedef
union unsigned void volatile while

5. The above example uses the keyword return. Every function must end with the word return.

6. C does not provide support for any Input / Output, therefore you must include the appropriate
library modules to perform functions like printing, reading, writing etc. include is a compiler
directive. It tells the compiler to include the file described in angle brackets when compiling. In
this case the file stdio.h, which contains all the required I/O functions for this program.

7. All functions contain statements. In order to separate one function from another, each defines
the start and end of its statements. The { bracket always defines the beginning of the function
body and } defines the end of the function body.

8. Each statement in a C is ended with a ; semicolon.

9. Non-printable characters. There are a number of characters required by a programmer that


are not displayable on printers and screens (eg. the newline character). C provides access to

Page 17
these escape sequences with the \ character. The following table displays all possible escape
sequences.

\a bell \\ backslash
\b backspace \? question mark
\f formfeed \' single quote
\n newline \" double quote
\r carriage return \ooo octal number
\t horizontal tab \xhh hexadecimal number
\v vertical tab

10. Comments are denoted by /* and */. All text between these separators is ignored by the
compiler and treated as comments. Whilst the content and flow of this program is fairly obvious,
in more complicated cases, these comments form a critical part of the program documentation.
You will notice that there are comments at the top of the program, which gives important
information about who wrote the program, when it was written and what it does. This is not a
requirement of C, but you should include this useful documentation in all your programs.
Older versions of C only recognised comments denoted by /* and */. Newer versions of C also
recognise comments by using //.

Page 18
Practical Exercise 1
Enter the following C code examples and get them working. You are not expected to understand the
details of the programs yet; this is an exercise in using the IDE. Experiment with cutting, pasting,
copying, deleting, searching and replacing.

Exercise 1.1
PROGRAM SPECIFICATION
Description
A program to display "Hello World" on the screen two times.
Inputs
Nil

Processing
Output "Hello World" twice

Outputs
"Hello World" to the screen

Overall Tasks
Output "Hello World" twice

PSEUDOCODE
PROGRAM EX01
OUTPUT "Hello World"
OUTPUT "Hello World"
END EX01

C Code
/**********************************************************************
* Program | Ex1-1
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | This program demonstrates simple printing by
* displaying “Hello world” on the screen twice.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
clrscr();
printf("*** Program Ex 1-1 ***\n\n");

printf("Hello World\n");
printf("Hello ");
printf("World");
printf("\n");

Page 19
printf("< Press Any key to continue >");
getch();
return 0;
}

Page 20
Exercise 1.2
PROGRAM SPECIFICATION
Description
A program to display "Hello World" on the screen five times.

Inputs
Nil

Processing
Output "Hello World" five times

Outputs
"Hello World" to screen

Overall Tasks
Output "Hello World" five times

PSEUDOCODE
PROGRAM EX02
Count = 1
WHILE Count <= 5
OUTPUT "Hello World"
Count = Count + 1
ENDWHILE
END EX02

C Code
/**********************************************************************
* Program | Ex1-2
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | This program demonstrates looping by
* displaying “Hello world” on the screen 5 times.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
int Count = 0;

clrscr();
printf("*** Program Ex 1-2 ***\n\n");

Count = 1;
while (Count <= 5)
{
printf("Hello World\n");
Count = Count + 1;
}

Page 21
printf("< Press Any key to continue >");
getch();
return 0;
}

Page 22
Exercise 1.3
PROGRAM SPECIFICATION
Description
A program to display "Hello World" on the screen as many times as requested.
Inputs
Name Description Legal Values Data Type Source
Times Times to repeat the output of No restriction integer keyboard
“Hello World”
Processing
Output "Hello World" required times
Outputs
"Hello World" to screen
Overall Tasks
Input Times to Repeat
Output "Hello World" required times

PSEUDOCODE
PROGRAM EX03
INPUT Times
Count = 1
WHILE Count <= Times
OUTPUT "Hello World"
Count = Count + 1
ENDWHILE
END EX03

Page 23
C Code
/**********************************************************************
* Program | Ex1-3
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Ask user to enter the number of times to repeat,
* | then display “Hello world” that many times.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
int Count = 0;
int Times = 0;

clrscr();
printf("\n\n*** Program Ex 1-3 ***\n\n");

printf("Enter number of times to repeat > ");


scanf("%i", &Times);
Count = 1;
while (Count <= Times)
{
printf("Hello World\n");
Count = Count + 1;
}

printf("< Press Any key to continue >");


getch();
return 0;
}

Page 24
Exercise 1.4
PROGRAM SPECIFICATION
Description
A program to display your name on the screen 5 times
Inputs
Name Description Legal Values Data Type Source
FirstName Person’s first name No restriction string keyboard
Processing
Output name 5 times
Outputs
Name Destination
FirstName screen
Overall Tasks
Input FirstName
Output name 5 times

PSEUDOCODE

PROGRAM EX04
DEFINE MAX_NAME_LENGTH = 21
INPUT FirstName
Count = 1
WHILE Count <= Times
OUTPUT "Hello World"
Count = Count + 1
ENDWHILE
END EX04

Page 25
C Code
/**********************************************************************
* Program | Ex1-4
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Requests a name, displays the name 5 times and
* | rings a bell.
*/

#include <stdio.h>
#include <conio.h>

#define MAX_NAME_LENGTH 21

int main(void)
{
int Count = 0;
char FirstName[MAX_NAME_LENGTH] = {0};

clrscr();

printf("*** Program Ex 1-4 ***\n\n");

printf("What is your first name?");


scanf(" %s",&FirstName);

Count = 1;
while (Count <= 5)
{
printf("%s\n",FirstName);
Count = Count + 1;
}
printf("\a\a\a\a\a");

printf("< Press Any key to continue >");


getch();
return 0;
}

Page 26
Exercise 1.5
PROGRAM SPECIFICATION

Description
A program to display 2 numbers in ascending order
Inputs
Name Description Legal Values Data Type Source
First First number entered No restriction Real keyboard
Second Second number entered No restriction Real keyboard
Processing
Determine Order
Outputs
First and Second in ascending order to the screen
Overall Tasks
Input numbers
Determine Order
Output numbers in Order

PSEUDOCODE

PROGRAM EX05
INPUT First
INPUT Second
IF First <= Second THEN
OUTPUT First, Second
ELSE
OUTPUT Second, First
END IF
END EX05

Page 27
C Code
/**********************************************************************
* Program | Ex1-5
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Input two numbers and print in ascending order.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
int First = 0;
int Second = 0;

clrscr();
printf("*** Program Ex 1-5 ***\n\n");

printf("Enter first number > ");


scanf("%i", &First);
printf("Enter second number > ");
scanf("%i", &Second);

if (First <= Second)


{
printf("Ascending order %i, %i\n", First, Second);
}
else
{
printf("Ascending order %i, %i\n", Second, First);
}

printf("< Press Any key to continue >");


getch();
return 0;

Page 28
Exercise 1.6
PROGRAM SPECIFICATION
Description
A program to calculate either half or double a number.
Inputs
Name Description Legal Values Data Type Source
Choice Choice to halve or double H or D char keyboard
a number
Number Number entered No restriction Real keyboard
Processing
Calculate either half or double the number
Outputs
Result of calculation to the screen
Overall Tasks
Input Choice, Number
Calculate half or double the number
Output result

PSEUDOCODE

PROGRAM EX05
INPUT Choice
INPUT Number
IF Choice = ‘H’ THEN
OUTPUT Number/2
ELSE
OUTPUT Number * 2
END IF
END EX05

Page 29
C Code

/**********************************************************************
* Program | ex1-6
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Calculate either half or double a number and output
* the result.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
char Choice = ' ';
float Number = 0.0;

clrscr();
printf("*** Program ex06 ***\n\n");

printf("Enter your choice\n ");


printf("\tH to halve\n");
printf("\tD to double: ");
fflush(stdin);
scanf("%c", &Choice);
Choice = toupper(Choice);
printf("\nEnter your number > ");
scanf("%f", &Number);

if (Choice == 'H')
{
printf("\nHalf of %.2f is %.2f\n", Number, Number/2);
}
else
{
printf("\nDouble %.2f is %.2f\n", Number, Number*2);
}

printf("\n< Press Any key to continue >");


getch();
return 0;
}

Page 30
CHAPTER 1 REVIEW QUESTIONS
1. Explain how a compiler works.

2. Define a variable.

3. What is a constant and why is it useful to use constants in programming?

4. Why is the data type required when declaring a variable?

5. Name the datatypes used in C for integer, real and character.

6. Write the c code to declare:


A variable to store a person’s age in years
A variable to store a peron’s first initial
A constant GST rate of 10%
The height of a person in metres.

Page 31
CHAPTER 2 -
SIMPLE SEQUENCE PROGRAMS

Upon successful completion of this chapter you will be able to:

• Declare and use local variables

• Define and use constants

• Write the C code to input a variable using the scanf function

• Write the C code to perform calculations using the assignment operator

• Write the C code to output a variable using the printf function

• Determine simple errors such as syntax errors and logic errors

Summary of new terms:


Local variable – variable declared inside the main program that can only be used locally to the
main program.
Initialise – set a variable to an initial value.
scanf statement - provides us with a means of reading in formatted input from a standard input
device.
fflush(stdin) statement - used to flush the input buffer of any data it contains.
assignment operator - an equal sign (=), which is used to create an assignment statement.
printf statement – used to print formatted output to standard output, the screen
Non-printable characters - characters not displayable on printers and screens.
Syntax errors - occur when the code attempts to do something that breaks the rules specified for
the particular compiler. The program will not run.
Logic errors – the program will run but the program doesn't do what you want it to do.

Page 32
OVERVIEW
This chapter introduces some basic C programming techniques, such as variable declaration and
simple input (scanf function), processing and output (printf function).

C VARIABLES AND CONSTANTS


In Chapter 1, the concepts of datatypes, constants and variables were introduced, and you have
seen them in use in a number of programs already. In this section, the practical use of variables and
constants is covered in more detail.

Variable declarations
As previously stated in Chapter 1, all variables must be declared before using them. Further, all
declarations must be made before any executable instructions.

A variable declaration consists of the datatype and the name of the variable, followed by a
semicolon (;).

We will declare all the variables as local variables, just inside the function main. Local and global
variables will be covered later.

Example – Variables

Declare the variables Count and Sum as integers – lines 5 and 6.


Declare the variable Initial as a character – line 7.
Declare the variable GrossPay as a floating-point variable – line 8.

1. #include <stdio.h>
2.
3. int main(void)
4. {
5. int Count;
6. int Sum;
7. char Initial;
8. float GrossPay;
9.
10. /* rest of program follows */
11. return 0;
12. }

Initialising variables
When you declare a variable, you can, at the same time, give it an initial value. This is the value the
variable will have when the program starts. The program can change the value as it runs.

It is good practice always to give variables an initial value when they are declared. You can do it by
adding, after the variable name (and before the semicolon) , an equals sign and the value. Initialising
variables is only recommended, but is strictly only necessary for variables used for counters,
accumulations and some calculations.

Page 33
For example:

int Sum = 0;
char Initial = ‘B’;
float GrossPay = 0.0;

Assigning values to Variables


Once the program starts executing, variables are assigned values using the assignment operator =.

Variable = expression;

For example:

Num = 10;
Count = Count + 20;
Character = 'a';
Payment = 21.5;

Defining constants in C
If we wanted to set up the following symbolic constants :

PERIOD_ONE_RATE = 0.05
PERIOD_TWO_RATE = 0.10
YEARS_IN_PERIOD_ONE = 5

they would be written in C using the #define preprocessor directive just after the #include
statements, as follows:

#include <stdio.h>
#include <conio.h>

#define PERIOD_ONE_RATE 0.05


#define PERIOD_TWO_RATE 0.10
#define YEARS_IN_PERIOD_ONE 5

To define one or more constants in a program:

1. Start each line with the word "#define", this tells the preprocessor that the following program
element will be constants.

2. Give the constant a name in uppercase and use the underscore character (_) as a word
separator e.g. YEARS_IN_PERIOD_ONE

3. Give a value to the constant e.g. 5. DO NOT use the = equal sign.

You can now use the constant "YEARS_IN_PERIOD_ONE" in your program and it will represent
the value 5.

Page 34
INPUT IN C- THE scanf STATEMENT
The scanf statement provides us with a means of reading in formatted input from a standard input
device. It is made up of two sections. The first is the control string, which contains formatting
information, and the second section contains an argument list that represents the variables to read
the input into.

int Age = 0;
.
.
scanf("%i", &Age);

The data item %i is for formatting incoming information. It will accept the next input as an integer.
The % symbol tells the compiler that the next character is going to be a conversion character that
indicates the data type of the corresponding data item. The following table contains a list of
commonly used conversion characters. The argument &Age represents the variable that accepts the
input. The ampersand character (&) before a variable signifies to the compiler to read the input into
the variable's location in memory.

Conversion Meaning
Character
%c accepts data item as a single character.
%f accepts data item as a floating point value.
%i accepts data item as an integer.
%s accepts data item as a string followed by the \0 white space
character.

Note: %s strings will be covered later.

The scanf statement always ignores leading whitespace characters when searching for input for
example, newline (\n). ‘’ or ‘ ‘. The only exception to this is when the %c specifier is used in which
case the next character, no matter what it is, is read into the variable. To avoid wrong characters
being read use fflush(stdin) before reading a character (%c).

Although it is the scanf statement that does the actual input into a variable, a printf statement is
necessary to give an input prompt to the user indicating clearly what data they are required to enter.
The above example would be:

int Age = 0;
.
.
printf(“\nEnter your age in years: “);
scanf("%i", &Age);

Page 35
Explanation of fflush(stdin)
The function fflush(stdin) is used to flush the input buffer of any data it contains. We’ll extend the
above example to also input a person’s initial after entering their age:

int Age = 0;
int Initial = ‘A’;
.
.
printf(“\nEnter your age in years: “);
scanf("%i", &Age);
printf(“\nEnter your first initial: “);
fflush(stdin);
scanf(“%c”, &Initial);

This example uses fflush(stdin) to remove the new line character (\n) from the buffer when the enter
key was pressed from entering the Age. When inputting a person’s age, the integer is entered
followed by the enter key (newline character). This newline character will become the entry for the
next character input field if not flushed and the user will not be able to input their character entry,
since the newline character has already been accepted as the input for the person’s initial. Adding
the fflush(stdin) statement just before the scanf will remove all characters from the input buffer and
allow the next key pressed to be the input for the variable.

Note: fflush(stdin) is only required for character data types.

PROCESSING
Arithmetic Operators
The following arithmetic operators are used in C:
brackets ()
multiplication *
division /
addition +
subtraction -

Assignment Operator
The assignment operator is simply an equal sign (=), which is used to create an assignment
statement. It consists of one variable to the left of the assignment operator and an expression on
the right. An expression is one or more variables or numbers with arithmetic operators. The variable
on the left is assigned the value of the expression, using the current values of the variables. An
example is given below.

Answer = Number1 + Number2;

We read this as: the variable Answer is assigned the value that results from Number1 being added
to Number2.

Page 36
OUTPUT - printf STATEMENT
We use the printf to print formatted output to standard output, the screen. It produces formatted
output according to the format string supplied with the function call. To output an integer variable the
C code is

printf("%i", Year);

This example displays the contents of the variable Year in integer notation. If the value of the
variable Year is 2003, the output will be:

2003

Printing text and variables


The printf function can display text as well as the value of variables in the one statement. Below is an
example.

printf("There a %i days in the year %i", Days, Year);

If the value of the variable Days and Year is 365 and 2003 respectively then the output of the printf
statement will be:

There a 365 days in the year 2003

Non Printable Characters


There are a number of characters required by a programmer that are not displayable on printers and
screens. C provides access to these characters via the escape character \ (backslash). It has the
name escape character because it lets the character following it "escape" from its usual meaning and
take on another meaning.

\a bell \\ backslash
\b backspace \? Question mark
\f form feed \' single mark
\n newline \" double mark
\r carriage return \v vertical tab
\t horizontal tab

White spaces characters such as tabs, new line, etc can be included in the printf statement to
enhance formatting. Below is an example.

printf("\n\nPrints two blank lines before and after\n\n");

The two new line characters (\n) before and after the text "Prints two blank lines before and after"
will output two blank lines before and after the text.

Page 37
Formatting Output
Another useful feature of the printf function is its ability to format output for either fixed length or
varied length numeric values.
This is demonstrated below.

Pay = 1020.29;
printf("The employee has earned $%10.2f this week", Pay);

The field width specified for float variable Pay is 10 with 2 decimal places(.2). That is, seven digits
for the integer part, one position for the decimal point and two digits for the decimal part. This is
achieved by putting the integer part a full stop and the decimal part between the conversion
character symbol '%' and the data type 'f'.

The result of this code is shown below.

The employee has earned $ 1020.29 this week

The other useful feature with the printf statement is that if you omit the field width or specify the
field-width as zero, ANSI C will allocate just enough spaces to hold the output. Consider the
example below.

Revenue = 12178.99;
printf("Today\’s revenue was $%.2f",Revenue);

The output of this code is show below:

Today’s revenue was $12178.99

As you can see the just enough spaces are allocated for variable Revenue, to ensure no digits are
lost and that it is display neatly next to the dollar sign. Hence this feature is especially useful when the
length of the output is uncertain.

PAUSING PROGRAM OUTPUT


Depending on the C compiler you are using, when the program finishes, the screen will return to the
C IDE and you will not be able to see your results. You can swap between the IDE and the results
screen by typing Alt/F5 (hold the Alt key down and press the F5 key).

A neater solution is to pause the program so that the final output screen can be viewed. To do this
the getch() function is used. This will wait for a key to be pressed to return to the C program. The
user of the program should also be given a message on the screen to tell them to press enter to
continue.

In summary, to pause the output screen use the following:

printf("\nPress enter to continue...");


getch();

Page 38
Note: getch() is not an ANSI C function, but an extension provided by turbo C. This extension is
defined in the conio package and you need to include the conio header file. This is also the case
when using the clear screen function.

Page 39
EXAMPLE PROGRAMS
Example - Program Tax1
Write a program to read in the GrossPay, calculate the Tax as 25% of GrossPay,
calculate NettPay as GrossPay subtract Tax and print out the NettPay.

Pseudocode
PROGRAM Tax1
DEFINE TAX_RATE = 0.25
INPUT GrossPay {Input}
Tax = GrossPay * TAX_RATE {Processing}
NettPay = GrossPay - Tax
OUPUT NettPay {Output}
END Tax1

C Code

1. /**********************************************************************
2. * Program | Tax1
3. * Author | Your name goes here
4. * Date written | The date goes here
5. * System | MS-DOS
6. *---------------+
7. * Function | Calculate Nett Pay from Gross Pay and Tax.
8. */
9.
10. #include <stdio.h>
11. #include <conio.h>
12.
13. #define TAX_RATE 0.25
14.
15. int main(void)
16. {
17. float GrossPay = 0;
18. float NettPay = 0;
19. float Tax = 0;
20.
21. clrscr();
22. printf("Enter the Gross Pay: ");
23. scanf("%f",&GrossPay);
24. Tax = GrossPay * TAX_RATE;
25. NettPay = GrossPay - Tax;
26. printf(“The Nett Pay is $%.2f”,NettPay);
27.
28. printf("\nPress Enter to continue");
29. getch();
30. return 0;
31. }

Page 40
Example - Program Reverse
Design a program to accept three whole numbers from the keyboard and output them in reverse
order to the screen. (Actually swap the values in the variables.)

Pseudocode
PROGRAM Reverse
INPUT Number1, Number2, Number3 {Input}
Temp=Number1 {Processing}
Number1=Number3
Number3=Temp
OUPUT Number1, Number2, Number3 {Output}
END Reverse

C Code

1. /*********************************************************************
2. * Program | Reverse
3. * Author | Your name goes here
4. * Date written | The date goes here
5. * System | MS-DOS
6. *---------------+
7. * Function | Swaps 3 integers and outputs them in reverse order.
8. */
9.
10. #include <stdio.h>
11. #include <conio.h>
12.
13. int main(void)
14. {
15. int Number1 = 0;
16. int Number2 = 0;
17. int Number3 = 0;
18. int Temp = 0;
19.
20. clrscr();
21.
22. printf("Enter the first integer: ");
23. scanf("%i",&Number1);
24. printf("Enter the second integer: ");
25. scanf("%i",&Number2);
26. printf("Enter the third integer: ");
27. scanf("%i",&Number3);
28. /* swap Number1 and Number3 */
29. Temp = Number1;
30. Number1 = Number3;
31. Number3 = Temp;
32.
33. printf("The numbers in reverse order are ");
34. printf("%i %i %i",Number1,Number2,Number3);
35.
36. printf("\nPress Enter to continue");
37. getch();
38. return 0;
39. }

Page 41
Example - Program Coin1
Design a program to calculate the number of cents in a group of $2, $1, 50 cent, 20 cent, 10 cent,
and 5 cent pieces. The number of each type of coin is entered from the keyboard and the result in
cents returned to the screen.

Pseudocode
PROGRAM Coin1
INPUT TwoD, OneD, FiftyC, TwentyC, TenC, FiveC
Cents = (TwoD * 200) + (OneD * 100) + (FiftyC * 50) + (TwentyC * 20)
+ (TenC * 10) + (FiveC * 5)
OUTPUT Cents
END Coin1

C Code
1. /**********************************************************************
2. * Program | Coin1
3. * Author | Your name goes here
4. * Date written | The date goes here
5. * System | MS-DOS
6. *---------------+
7. * Function | Calculates the total number of cents from the number
8. * | of each type of coin entered.
9. */
10.
11. #include <stdio.h>
12. #include <conio.h>
13.
14. int main(void)
15. {
16. int Cents = 0;
17. int TwoD = 0;
18. int OneD = 0;
19. int FiftyC = 0;
20. int TwentyC = 0;
21. int TenC = 0;
22. int FiveC = 0;
23.
24. clrscr();
25.
26. printf("Enter the number of two dollar coins: ");
27. scanf("%i",&TwoD);
28. printf("Enter the number of one dollar coins: ");
29. scanf("%i",&OneD);
30. printf("Enter the number of fifty cent coins: ");
31. scanf("%i",&FiftyC);
32. printf("Enter the number of twenty cent coins: ");
33. scanf("%i",&TwentyC);
34. printf("Enter the number of ten cent coins: ");
35. scanf("%i",&TenC);
36. printf("Enter the number of five cent coins: ");
37. scanf("%i",&FiveC);
38. Cents = (TwoD * 200) + (OneD * 100) + (FiftyC * 50)
39. + (TwentyC * 20) + (TenC * 10) + (FiveC * 5);
40.
41. printf("The total number of cents is: %i",Cents);
42.

Page 42
43. printf("\nPress Enter to continue");
44. getch();
45. return 0;
46. }

Page 43
SIMPLE DEBUGGING
Algorithms need to be designed to handle any type of input. Typical input errors that can occur
include:

1. Out of range – this happens when a value has been entered which lies outside the legal
values specified.
2. Type mismatch – when the program requests a numeric value and a non-numeric value is
supplied.
3. Division by zero – dividing a number by zero.

These are only a few types of error that can occur. A well-designed algorithm will test for these
errors and take the appropriate action. This may include displaying an error message, allowing for
re-input of the data value or terminating the program if a serious error has occurred.

Program Errors
When attempting to compile and run your program for the first time, it is unlikely to work as
expected. This is because your program contains errors or 'bugs'.

The two main types of errors you will experience when coding programs are:

Syntax errors
This type of error occurs when the code attempts to do something that breaks the rules specified for
this particular compiler.
Here are some examples of syntax errors:
• Trying to use a variable that has not been declared.
• Misspelling a program command e.g. Printf, Scanf instead of printf and scanf.
• Missing a semicolon or full stop where it is needed.
When a syntax error occurs, the program cannot run because the failed compile did not produce the
necessary object file. Therefore, all syntax errors must be removed from the program before it can
be successfully compiled and run.

Logic errors
This type of error occurs when the program simply doesn't do what you want it to do.

Here are some examples of logic errors:


• The expected output doesn't appear.
• The expected output appears but is wrong.
• Output is displayed in the wrong place.
• Output is displayed which shouldn't be displayed.

It is sometimes difficult to eliminate all logic errors, especially with a larger program but they can be
minimised through proper testing of the program. Most compilers include a ‘debugger’ that allows
you to step through the program line by line and help you find these logic errors.

Page 44
Understanding And Correcting Syntax Errors
When a syntax error occurs during a compile, the compiler will stop on the line where the error was
detected. This will in most instances be the line where the error happened or it may be one or more
lines below the line causing the error. An error message will appear on the screen telling you what
the problem is and once you have fixed the problem and recompiled the program, either the next
error message will appear (if there is one) or a successful compile will occur, which, in the latter
instance, will allow the program to run.

Understanding And Correcting Logic Errors


Logic errors don't appear when you are compiling - they only become apparent when the program
is run. When you notice that your program isn't operating as it should be, sometimes you know
straight away where the problem is and can fix it very easily. At other times, finding the problem is
much more difficult.

Here is an example of a logic error:

Example - Program WrongResult

1. /* program WrongResult */
2.
3. #include <stdio.h>
4.
5. int main(void)
6. {
7. int Mark1 = 0;
8. int Mark2 = 0;
9. float Average = 0.0;
10.
11. printf("This program computes the average of two marks");
12. printf("and\n displays the result");
13. printf("\n\nEnter your first mark out of 100: ");
14. scanf("%i", &Mark1);
15. printf("Enter your second mark out of 100: ");
16. scanf("%i", &Mark2);
17. Average = Mark1 + Mark2 / 2;
18. printf("Your average mark is %5.2f ",Average);
19. return 0;
20. }

The logic error here is that the code on line 17 "Average = Mark1 + Mark2 / 2" will not calculate
the average of the two marks. It will instead divide Mark2 by 2 then add that result to Mark1. This
error occurred because a divide operator occurs before an addition. We must enclose the addition
in brackets to ensure the addition happens first.

Page 45
Here is the amended version of the code.

1. /* program RightResult */
2.
3. #include <stdio.h>
4.
5. int main(void)
6. {
7. int Mark1 = 0;
8. int Mark2 = 0;
9. float Average = 0.0;
10.
11. printf("This program computes the average of two marks");
12. printf("and\n displays the result");
13. printf("\n\nEnter your first mark out of 100: ");
14. scanf("%i", &Mark1);
15. printf("Enter your second mark out of 100: ");
16. scanf("%i", &Mark2);
17. Average = (Mark1 + Mark2) / 2;
18. printf("Your average mark is %5.2f ",Average);
19. return 0;
20. }

This amended version of the code may still give incorrect results due to integer division in line 17.
Mark1 and Mark2 are both integers and are divided by an integer giving the result as an integer.
The average has been declared as a float, as would be expected with division, but in C integer
division gives an integer result. For example if 21 was entered for Mark1 and 20 for Mark2, the
resultant output would be 20.00. This is incorrect since the result should be 20.50. To force the
result to be a float, use divide by 2.0 as Average = (Mark1 + Mark2) / 2.0.

Here is another amended version of the code.

21. /* program RightResult2 */


22.
23. #include <stdio.h>
24.
25. int main(void)
26. {
27. int Mark1 = 0;
28. int Mark2 = 0;
29. float Average = 0.0;
30.
31. printf("This program computes the average of two marks");
32. printf("and\n displays the result");
33. printf("\n\nEnter your first mark out of 100: ");
34. scanf("%i", &Mark1);
35. printf("Enter your second mark out of 100: ");
36. scanf("%i", &Mark2);
37. Average = (Mark1 + Mark2) / 2.0;
38. printf("Your average mark is %5.2f ",Average);
39. return 0;
40. }

Page 46
Exercises – Sequence C code

For each of the following programs provide the C code.

Exercise 2-1

POST1:A program outputs to the screen the postage charge for a parcel when the weight of the
parcel (in Kg) is entered from the keyboard. The rate of postage is set at $1.50 per kg.

Exercise 2-2

ANIM1:The consultation fee for a vet is obtained by multiplying the number of hours by the hourly
rate of $25. A program accepts the number of hours (whole number) from the keyboard
and outputs the consultation fee to the screen.

Exercise 2-3

BANK1:A loan officer requires a program to calculate the monthly repayment M on a customer
loan by entering from the keyboard the principal P, at an annual interest rate of R% pa.,
over a period of T years where M=P(1+RT/100.0)/(12T). All inputs and the result is
output to the screen. (Sample input P=$10000, R=10%, T=10 gives M=$166.67)

Exercise 2-4

TEMP1:Convert a temperature entered from the keyboard in degrees Fahrenheit to degrees


Celsius where degC=(degF-32)/1.8 and output the result to the screen.

Exercise 2-5

RECT1:A program accepts the height and width of a rectangle from the keyboard, calculates the
perimeter and area of the rectangle and outputs the results to the screen.

Exercise 2-6

DISC1: A program accepts the marked value of an item in $ and cents, and the discount rate as a
% from the keyboard and returns the discounted price to the screen.

Exercise 2-7

TIME1:A program allows a person to enter values for the number of days, hours, minutes and
seconds and outputs the total number of seconds to the screen. (Note this program will

Page 47
require the use of a long integer – use the help facility to find out how to declare a variable
as a long integer.)

Page 48
CASE STUDY
PFEECALC (PLACEMENT FEE CALCULATOR)
The Case Study below is presented as one large programming problem. It is too difficult to solve as
one large problem so it will be broken up into stages throughout the chapters in this book.

DO NOT attempt this problem now, it will be built up slowly throughout the chapters.

PROGRAM SPECIFICATION
Description
The firm, Admit Solutions, who are an IT contracting company, has made a request for a program
to produce a record of personnel placements made on a daily basis. Admit Solutions place
programmers, network administrators or office staff with a variety of customers. Admit Solutions
charge to place a professional and they are responsible for paying the salary of that professional. If
a customer has used Admit Solutions more than three times they are considered a regular customer
and receive 5% discount on the fee. The fee is calculated from both the type of person who is going
to be placed and the length of time for the placement. The following table shows the fees that are
charged:

Professional Charge per day for a


Casual Customer
A Network professional (N) $115.00
An Office professional (O) $120.00
A Programmer (P) $100.00

Admit Solutions require the program to output the number of individuals hired by a customer and to
calculate the amount of money that will be paid to admit Solutions, by that customer.

Admit Solutions also requires the program to give summaries for the day.

Each customer may contract as many people from each of the professions as they require. The end
of the Customer input is signalled by entering ‘X’ for the type of professional required.

Input
The inputs are:

For each customer:


• The Customer ID number - 4 digit integer
• Type of customer - regular or casual
• Any More? - Y to process next Customer, N to produce summary statistics

For each professional:


• Type of professional required (N/O/P/X)
• Number of days required for a given professional type (>=0)

Page 49
Page 50
Processing
1. Enter the customer ID

2. Enter the type of customer – Regular or Casual (R/C)

3. Enter the type of professional required (N/O/P) for Networking, Office or Programming.

4. Enter the number of days the professional is required.

5. Validate each of the inputs as they are entered. If an invalid value is entered an error message
should be displayed and a new value requested until a valid value is entered

6. If the type of professional is keyed in as ‘X’ terminate the input for this customer.

7. Calculate and display the cost for each group of professionals, and accumulated total cost for
a customer.

8. Update the array for Customer ID, Customer Type and Total Cost.

9. Ask if there is another customer and terminate when a value of ‘N’ is the answer. Allow the
user to enter the details of the next customer when the answer is ’Y’.

Statistics
1. Statistics to be maintained for each customer
• The number of days required for each professional type
• The total number of professionals hired
• The total cost to the customer

2. Statistics to be maintained for the day


• The total number of customers
• The number of regular and the number of casual customers
• The number of professionals hired that day
• The total cost for all personnel
• Use an array to update a transaction table of the Customer ID, Customer Type and Total
Cost for each customer

Page 51
Output
1. After each customer output the following details
• The number of days required for each professional type
• The total number of professionals hired
• The total charge to the customer

2. After all customer have been processed output


• The number of customers
• How many of the customers were regular and how many were casual
• Total number of professionals hired
• The total amount that will be charged to all the customers
• A transaction table of the Customer ID, Customer Type and Total Cost for each customer

All output must go to the screen.

Known Solutions:
CustID CustType ProfessionType NumDays OUTPUT
Total Cost
1234 C N 2
X $230.00
2211 R O 5
N 4
P 5
X $1482.00
3211 R P 1
X $95.00

Sample Output:

Day’s Statistics:

Total Customers 3
Total Regular Customers 2
Total Casual Customers 1
Total Professionals Hired 17
Total Amount to be charged $1807.00

Transaction Table

Customer ID Customer Type Total Cost


---------------------------------------------------------------------
1234 C $ 230.00
2211 R $ 1482.00

Page 52
3211 R $ 95.00

Page 53
REQUIREMENTS
For this case study you must present your work in a professional manner:

Your documentation will include

• Program Specification
• Pseudocode
• Data Dictionary
• Documented Source Code

For one major module of your code, produce the following:


• Known Results
• Desk Check

You must use a structured programming approach and use the most appropriate loops and
selection structures. You should use constants where appropriate. Modularise your code,
making sure to use some functions with return values. Arrays must be used where
appropriate. Do not use global variables.

Page 54
CASE STUDY - PFEECAL1

Write a program that will request the following information from a user:

An ID number (4 digit integer)


The number of required networker days.
The number of required programmer days.
The number of required office administrator days.

The following table shows the fees that are charged:


Professional Charge per day for a
Casual Customer
A Network professional (N) $115.00
An Office administrator (O) $120.00
A Programmer (P) $100.00

Your program should then calculate the total cost and output this cost to the screen.

Page 55
CHAPTER 2 REVIEW QUESTIONS
1. Variables can be initialise when declared. True or False?

2. When should the fflush(stdin) statement be used and why?

3. What is a syntax error, give an example?

4. When does a logic error occur?

5. Write the C code statements to


a. Input the length of a piece of timber in mm
b. Input a person’s height in metres
c. Input a person’s first initial

6. Write the C code statements to output the above inputs.

7. Write the C code statements to input a number, multiply it by 2 and output the result.

Page 56
CHAPTER 3 -
PROGRAM DEVELOPMENT

Upon successful completion of this chapter you will be able to:

• Understand the six stages of the program development cycle

• Write a program specification to clearly define a problem

• Write an algorithm to solve a simple sequential problem using pseudocode

• Desk check the algorithm to ensure the logic is correct

• Write structured, simple sequential programs in C code

• Use the known solutions to check the program works correctly

Summary of new terms:


Program development cycle – the stages in the program development process.
Program specification - a formal way of documenting what a computer program is to do.
Algorithm - set of logical steps that describe the actions to be carried out to solve the overall
problem.
Pseudocode - a method for writing the algorithm.
Data dictionary - an alphabetic list of the names of all the data items used by the program.
Desk check – a technique for testing the algorithm with test data.

Page 57
OVERVIEW
When you are writing a program to perform a particular task, you would rarely just run C and start
typing in code. Creating a program requires a considerable amount of thought about just exactly
what the program has to do, and how to write it so that it will perform as required. Usually a big
task needs to be broken up into smaller tasks.

This chapter describes some of the formal methods that are used for developing and describing the
structure and behaviour of a program. These methods are useful to help you in structuring the
development process and then producing documentation to assist the communication of the
development to others.

PROGRAM DEVELOPMENT
Program development involves much more than entering programming code into a computer and
executing the commands. Problem solving and program design should precede the use of the
computer to generate a program.

Humans cannot directly communicate with computers using English because computers only
understand one language, machine language. Machine language is very difficult to learn because it
consists only of the binary numbers 0 and 1.

We want to communicate to the computer in a language we know, and have some way of translating
it to machine language. It is difficult to translate English into machine language, so special
programming languages have been developed which are similar to English and therefore easier to
learn. These programming languages are used to develop computer programs that give the computer
a detailed set of instructions to execute.

It is very tempting to start entering your program into the computer as soon as you have some idea
of how to write it. Instead, analyse the problem and its solution before you write any program
instructions.

It has been clearly demonstrated that time spent defining the problem to be solved and then
designing the solution leads to more efficient programming and fewer errors in the program.

Program Development Cycle


The task of creating a program that meets the user's requirements and is adaptable is a complex and
difficult task unless it is organised. This is done using a cycle of well-defined steps to create simpler
parts to reduce the complexity.

A number of stages can be identified in the program development process. These stages are
referred to as the Program Development Cycle to emphasise the point that it may be necessary to
return to an earlier stage if errors or ambiguities are detected.

Six stages of program development can be identified:


1. Problem definition.
2. Development of a solution.
3. Testing of the solution.

Page 58
4. Coding of the solution.
5. Testing the program.
6. Maintenance and documenting the program.

1. Problem Definition
This stage is the most important because all subsequent stages are dependent on it. Problem
definition involves analysing the problem until a clear understanding is reached. Without a clear
understanding of the problem, time and effort spent on later stages can be wasted. It may be
necessary to have a discussion with the person who proposed the problem to clarify issues.

In a business environment the programming problem is generally presented as a program


specification, which sets out the input, processing and output requirements and other requirements
of the program. The problem definition stage should also include developing known results for given
inputs to the program. These known results can be used as a guide to the successful solution of the
problem.

2. Development of a Solution
The technique of top-down design in the development of a solution involves breaking the problem
down into a number of tasks to establish an outline of the solution, and then breaking these tasks
down into sub-tasks until the solution of each task is manageable.

The solution outline can be represented by a hierarchy or structure chart. Hierarchy charts show
the relationships between sections in a program.

The set of logical steps that describe the actions to be carried out in each task to solve the overall
problem is called an algorithm.

There are many different techniques used to represent an algorithm. Algorithms can be
diagrammatic or descriptive.

Diagrammatic algorithms include:


1. Flowcharts.
2. Nassi-Shneiderman diagrams.
3. Action diagrams.

Descriptive algorithms include:


1. Pseudocode.
2. Point form.
3. Structured English.

3. Testing of the solution


It is vital to check that the algorithm actually solves the problem and produces the expected results
for given inputs. In addition to the known results that may have been included in the program
specification, other test data should be designed to test the logic of the solution.

A technique for testing the algorithm with test data is the desk check. This is a step-by-step
walk-through of the logic of the algorithm to see how the input is transformed into output. This is a

Page 59
paper (or whiteboard) exercise that is carried out before the program code is entered on the
computer. If the results from the desk check do not match the expected results it is necessary to
return to stage 2 to modify the algorithm. The modified algorithm is then retested and modified until
the expected results are obtained for the test data. Since the conclusions derived from a desk check
are only as good as the test data, it is necessary to design comprehensive test data, which should
test all conceivable conditions.

4. Coding the Program


The commands of a programming language are used to transform the algorithm into a computer
program after the logic of the program has been planned. Any programming language can be used to
code the algorithm, however a particular language may be more suitable than others depending on
the type of problem.

During the coding of the program it is good practice to include comments that explain the logic of the
processing steps. These comments will make it easier to understand the program at a later date and
make the maintenance of the program easier.

A compiler or interpreter is used to convert the program code to machine language that the
computer can understand. When the compiler detects an error in the program, an error message is
displayed.

There are two basic categories of error messages: syntax and run-time.
The compiler detects and displays syntax errors as it attempts to translate the program. If the
program contains a syntax error, it cannot be translated and the program cannot be executed.

Syntax errors occur if the rules of the programming language (the syntax) are not adhered to. This
may occur when reserved words (words that have special meaning to that programming language)
are misused, misspelled or punctuated incorrectly. These syntax errors must be corrected before
the program can be run. The program code is stored in a text file, which can be printed from the
program editor, a text editor, or a word processing package. The program listing is the
documentation for this stage.

Run-time errors are detected and displayed during execution of the program. They occur when
the program instructs the computer to perform an illegal operation, such as subscript out of range,
dividing a number by zero, type mismatches or manipulating undefined or invalid data. When a run-
time error occurs, the computer stops program execution and displays an error message.

5. Testing the Program


This step involves running the program with the same test data used to test the algorithm. If the
output does not match the expected results it indicates that errors have been made in converting the
algorithm into program code. Debugging the program is the process that identifies these errors. A
number of techniques can be used to check the progress of the processing steps. Many program
editors have a debugger, which can be used for this purpose. When an error is identified, the
program is modified and then tested again. This cycle is repeated until the program gives the
required output.

Page 60
6. Maintenance of the Program and Documentation
Documentation consists of the written materials produced at each stage of the program
development process. It is a cumulative process that starts with the initial statement of the problem,
adds the details of the solution design, then the coding and details of the testing.

One document that is developed over several of the stages in the program development cycle is the
Data Dictionary. This is an alphabetic list of the names of all the data items used by the program. It
includes a description of the data item and the type of data. The initial data dictionary from the
problem definition stage is added to during algorithm development and during coding as extra data
items are used in the steps to convert the input to output.

The data dictionary is provided both as written documentation and as a series of comments in the
first part of the program. The written document is used as a reference for data items in the algorithm;
the data dictionary in the program provides the programmer, and other programmers, with a
reference section to ensure consistency in the use of data within the program.

Once the program has been thoroughly tested, the documentation should be reviewed to ensure
consistency between the materials produced at each stage.

Documentation for a program consists of:


1. Program specification.
2. Hierarchy or structure chart.
3. Algorithm in pseudocode or NS diagrams or flowcharts.
4. Test data and desk check.
5. Program listing.
6. Results of testing the program.

It is likely that the program will be changed at some time after it has been successfully designed and
tested. Errors may occur or modifications may be requested. As changes are made they should be
documented and the materials from each stage modified to reflect those changes.

PROBLEM DEFINITION AND PROGRAM SPECIFICATION


The problem definition step of the program development life cycle is often documented using a
program specification. A program specification is a formal way of documenting what a computer
program is to do after discussions with the customer. In reality a formal system analysis process
should be followed in order to develop an accurate definition of the problem. The program
specification is just one way of documenting that definition and we will be concentrating on
producing program specifications in this course. The format of a program specification should
contain the following:

1. A general DESCRIPTION of the program i.e. what it is required to do.

2. Program INPUTS - a list of data items which are to be provided as inputs to the program,
whether there are any restrictions on valid inputs, the data type and where these inputs are
coming from e.g. keyboard, file etc.,

Page 61
3. The PROCESSING requirements - a description of how the program inputs are to be
processed so that the required program outputs are produced. This section will include
details of any formulae that are needed, which inputs will need validation, statistics to be
collected, etc.

4. Program OUTPUTS - a list of those results which are to be produced by the program and
where the outputs are going e.g. screen, printer, file etc.

5. The OVERALL TASKS, i.e. the broad solution steps (the highest level of top-down
design) or an overall view of the tasks the program will have to perform.

The purposes of the program specification are:

1. It helps to clarify what the program is required to do.

2. Any problem ambiguities are removed.

3. It gives the programmer an excellent starting point for thinking about the details of the
algorithm.

Below is an example of a program specification. Do not attempt to code this at this time.

Example - CODISCO

PROGRAM SPECIFICATION

DESCRIPTION

The Computer Disk Supply Company has made a request for a


program to handle the ordering of their floppy disks. The diskettes are
supplied in boxes of 10 and prices vary according to size and density of
the diskettes. The program is to ask for the details of an order for one
type of disks then give the cost of that order entered. After an order is
entered the user is to be given the chance to continue to enter another
order (by pressing the enter key) or to terminate the input of orders by
entering the word END. Once the user enters END, some statistics on
all orders entered are to be provided. The user will identify themselves
with their name when they start the program.

INPUT

Name Description Legal Values Data Type Source


Size Diskette size representing 3, 5,8 Integer Keyboard
3.5, 5.25 or 8-inch
Density High or double density H, D Single character Keyboard
Boxes The number of boxes >0 and <=100 Integer Keyboard
Name The name of the person Any characters String Keyboard

Page 62
ordering accepted

Page 63
PROCESSING

1. Validate each of the inputs as they are entered. If an invalid value is entered an
error message should be printed and a new value requested until a valid value
is entered.

2. Calculate the order cost as follows:


• Calculate CostPerBox using
• 3.5" diskettes cost $20 per box for double density.
• 5.25" diskettes cost $10 per box for double density.
• 8" diskettes cost $15 per box for double density.
• For 3.5" and 5.25" diskettes add $3 per box for high density.
• OrderCost = CostPerBox *Boxes

3. Statistics include:
• The number of orders processed.
• The number of boxes of each size of diskette sold (all densities
combined).
• The cost of all orders.

OUTPUT

1. For each disk size ordered print the details of the order (Name, Size, Density,
Boxes and OrderCost) to the screen.
2. After all orders have been entered i.e. after the user enters END to finish the
session, the following are displayed on the screen:
• The total number of orders made.
• The total number of boxes of each size (double and high combined).
• The total cost of all orders.

OVERALL TASKS

1. Initialisations
2. Input and validate order details or END
3. Calculate order cost
4. Update statistics
5. Print details of order
6. Print statistics for all orders entered

Page 64
Exercises – Program Specifications

For each of the following exercises write a program specification.

Exercise 3-1

POST0:A program outputs to the screen the postage charge for a parcel when the weight of the
parcel (in Kg) is entered from the keyboard. The rate of postage is set at $1.50 per kg.

Exercise 3-2

ANIM0:The consultation fee for a vet is obtained by multiplying the number of hours by the hourly
rate of $25. A program accepts the number of hours (integer) from the keyboard and
outputs the consultation fee to the screen.

Exercise 3-3

BANK0:A loan officer requires a program to calculate the monthly repayment M on a customer
loan by entering from the keyboard the principal P, at an annual interest rate of R% p.a.,
over a period of T years where M=P*(1+R*T/100.0)/(12*T). All inputs and the result is
output to the screen.

Exercise 3-4

TEMP0:Convert a temperature entered from the keyboard in degrees Fahrenheit to degrees


Celsius where degC=(degF-32)/1.8 and output the result to the screen.

Exercise 3-5

RECT0:A program accepts the height and width of a rectangle from the keyboard, calculates the
perimeter and area of the rectangle and outputs the results to the screen.

Exercise 3-6

DISC0:A program accepts the marked value of an item in $ and cents, and the discount rate as a %
from the keyboard and returns the discounted price to the screen.

Exercise 3-7

TIME0:A program allows a person to enter values for the number of days, hours, minutes and
seconds and outputs the total number of seconds to the screen.

Page 65
STRUCTURED PROGRAMS
The concept of structured programming, the top-down approach to design and the use of design
techniques to depict logic, go hand in hand.

All programs can be written using all or any of the 3 main control structures:
• Sequence
• Selection
• Iteration.

There should always be only one entry point to any part of a logical structure that is from the part
immediately preceding (or above) it. There should always be only one exit point from any part of
the logical structure to the part immediately following (or below) it. This ensures that there is only
one entry and only one exit to each structure. The program logic flows step by step from the top to
the bottom. In this way there can be no “jumping around”, therefore the program written exactly
from the logic will also be structured.

The aim in this book is to use these techniques, in combination with a modular approach, to teach
you how to write good structured programs.

PSEUDOCODE
We now look at some techniques for refining the program specification, especially the “processing”
section, in the direction of a working program. We look at using pseudocode as a method for
writing the algorithm although there are other commonly used methods such as Nassi-Shneiderman
diagrams, shown in the appendix, and flowcharts.

Pseudocode means “as if” code. That is, a solution to a problem that is presented in pseudocode is
in a form that is very similar to program code but does not conform to the tight rules of any
particular programming language. Therefore, the solution could be programmed from the
pseudocode using whatever programming language is appropriate. Hence, before being burdened
with syntax, pseudocode can be used to design and present the logic of a solution to a problem in an
English-like manner.

Advantages
There are a number of ways to document the design of a program, so you may be wondering why
pseudocode? There are two main advantages in using pseudocode:

1. It is easy to write and modify. It is rare to find a programmer that will not want to modify in
some way the initial attempt at an algorithm. With pseudocode it is easy to make deletions and
additions. Furthermore pseudocode lends itself nicely to being manipulated by a word
processor or text editor.

2. Pseudocode is English-like and can be personalised. This last advantage can turn into a
disadvantage because pseudocode, which is too personalised, can be difficult for someone else
to read and follow. Some programmers, especially beginners, also find that the freedom offered
by pseudocode can be confusing and there is still the possibility that a design written using
pseudocode is unstructured (contrast this with Nassi-Shneiderman in the appendix).

Page 66
Guidelines
To guide you in writing algorithms using pseudocode, here are some conventions and guidelines:

• Use normal English words or obvious abbreviations.


• Do not use (programming) language-specific words.
• Write each phrase/statement/step on a separate line.
• Use indentation to indicate (logical) belonging. You should use at least two spaces of indentation
for clarity.
• Use brackets {} when including comments. You should include comments.
• Give each set of pseudocode a title (either the title Program or Module).
• Try to keep the pseudocode for any one module to under a page in length.
• Use CAPITALS for construct words and Upper/lower case mixture for variables.

Structure PseudoCode Use


Input INPUT Getting data into the program
Output OUTPUT Getting data out of the program
Assignment Variable = value Giving a variable a value. The value may be a
calculation.
Arithmetic operators + Addition
- Subtraction
* Multiplication
/ Division
^ Exponents
() Brackets

Example - TAX1

A simple tax problem reads in the GrossPay, calculates the Tax as 25% of GrossPay,
deducts this from GrossPay and prints out the NettPay.

An algorithm for this in pseudocode might be:

PROGRAM Tax1
DEFINE TAX_RATE = 0.25
INPUT GrossPay {Input phase}
Tax = GrossPay * TAX_RATE {Processing phase}
NettPay = GrossPay - Tax
OUTPUT NettPay {Output phase}
END Tax1

Page 67
Example - SWAP1

Another simple problem might be to enter two numbers and print them out in reverse
order. An algorithm for this in pseudocode might be:

PROGRAM Swap1
INPUT First {Input phase}
INPUT Second
Temp = First {Processing Phase}
First = Second {study this carefully!}
Second = Temp
OUTPUT First
OUTPUT Second {Output phase}
END Swap1

{Note the use of {...} for comments on the right}

Example - TAX1

A simple tax problem reads in the GrossPay, calculates the Tax as 25% of GrossPay,
deducts this from GrossPay and prints out the NettPay.

Pseudocode

PROGRAM Tax1
DEFINE TAX_RATE=0.25
INPUT GrossPay
Tax = GrossPay * TAX_RATE
NettPay = GrossPay - Tax
OUTPUT NettPay
END Tax1

AN ALTERNATIVE TO PSEUDOCODE -
NASSI-SHNEIDERMAN DIAGRAMS
Nassi-Shneiderman (NS) diagrams are an alternative way to write an algorithm. The logic and
geometry of a properly drawn Nassi-Shneiderman diagram ensures that the algorithm it represents is
structured. Thus NS diagrams were developed to force the rules of structured programming. See
the appendix for more information about NS diagrams.

Page 68
Exercises – Sequence Algorithms

For each of the following programs provide the algorithm using pseudocode.

Exercise 3-8

POST1: A program outputs to the screen the postage charge for a parcel when the weight of the
parcel (in Kg) is entered from the keyboard. The rate of postage is set at $1.50 per kg.

Exercise 3-9

ANIM1 The consultation fee for a vet is obtained by multiplying the number of hours by the hourly
rate of $25. A program accepts the number of hours (whole number) from the keyboard and
outputs the consultation fee to the screen.

Exercise 3-10

BANK1: A loan officer requires a program to calculate the monthly repayment M on a customer
loan by entering from the keyboard the principal P, at an annual interest rate of R% pa., over a
period of T years where
M=P*(1+R*T/100.0)/(12*T)
All inputs and the result are output to the screen.

Exercise 3-11

TEMP1: Convert a temperature entered from the keyboard in degrees Fahrenheit to degrees
Celsius where degC=(degF-32)/1.8 and output the result to the screen.

Exercise 3-12

RECT1: A program accepts the height and width of a rectangle from the keyboard, calculates the
perimeter and area of the rectangle and outputs the results to the screen.

Exercise 3-13

DISC1: A program accepts the marked value of an item in $ and cents, and the discount rate as a
% from the keyboard and returns the discounted price to the screen.

Exercise 3-14

TIME1: A program allows a person to enter values for the number of days, hours, minutes and
seconds and outputs the total number of seconds to the screen.

Page 69
Page 70
M ORE ON DOCUMENTATION
We have looked at the program specification as an important method for defining and documenting
what a program has to do, and how it should go about doing it.

In this section we look at three related techniques, the data dictionary, known results and desk
checking. Along with the program specification, these techniques are of great value in the initial
design of a program and also its subsequent documentation and testing.

Data Dictionary
A well-developed data dictionary defines the data types and is an aid to designing the algorithm and
program code that is done in the next step of the program development cycle. The data dictionary is
a useful summary of the items listed in the INPUT, PROCESSING and OUTPUT sections of the
Program Specification. The data dictionary should be in a table with headings:

Variable Description Legal Values Data type Source

The constant or variable names should be listed in alphabetical order with a brief description. The
source of the data item comes from either input (keyboard) or processing (i.e. derived). Legal
values show restrictions on the variables or the value of a constant. The type shows one of the four
data types: integer, real, character or string.

Known results
When you first test a program, it is important to know what behaviour you expect to get from it,
otherwise how will you know whether or not it is working?

Known results tell in advance the output that the program should produce for a given set of input
values. In the programs you have written so far, where the calculations are fairly simple, it is not too
difficult to provide some known results before the program is written.

See the documented examples below for some illustrations of known results.

Deskchecks
Deskchecks are a powerful technique for checking and debugging programs. During a deskcheck,
you play the part of the computer as it runs your program, step by step. You keep track of the
values of all the variables as the program runs, and of the input and output. The deskcheck will
predict the results of the program. If the program has logical errors, the deskcheck will allow you to
identify where they are.

Deskchecks are often used in cooperation with known results. If you work through a deskcheck
with input that gives known results, it should produce the correct output. During a deskcheck you
keep track of the variables using a table. Some examples are shown in the programs that follow.

Deskchecks are mainly done for the programmer’s own benefit when working on a difficult
algorithm or fixing a logical error. Desk checks would not be done on all algorithms.

Page 71
DOCUMENTED EXAMPLES
Below are two worked examples showing full documentation, namely:
1. Program specification.
2. Known results.
3. Data dictionary.
4. Design with pseudocode and Nassi-Shneiderman diagram.
5. Desk checks.

Example - SORT1

PROGRAM SPECIFICATION

DESCRIPTION
Design a program to accept three whole numbers from the keyboard and output them in
reverse order to the screen. (Actually swap the values in the variables.)
INPUTS
Name Description Legal Values Data type Source
Number1 First number entered No restriction Integer Keyboard
Number2 Second number entered No restriction Integer Keyboard
Number3 Third number entered No restriction Integer Keyboard

PROCESSING
Reverse the order
OUTPUTS
The three numbers to the screen
MAJOR TASK
Read numbers from keyboard
Reverse order
Output numbers

KNOWN RESULTS
input 2,6,3 output 3,6,2
input 9,14,7 output 7,14,9

DATA DICTIONARY

Variable Description Legal Values Data type Source


Number1 First number entered No restriction Integer Keyboard
Number2 Second number entered No restriction Integer Keyboard
Number3 Third number entered No restriction Integer Keyboard
Temp Temporary for swap No restriction Integer Internal

Page 72
PSEUDOCODE

PROGRAM Sort1
INPUT Number1, Number2, Number3 {input}
Temp = Number1 {process}
Number1 = Number3
Number3 = Temp
OUTPUT Number1, Number2, Number3 {output}
END Sort1

DESK CHECK
for Input 2, 6, 3 (known results 3,6,2)

Statement Number1 Number2 Number3 Temp


INPUT Number1, Number2, Number3 2 6 3
Temp = Number1 2
Number1 = Number3 3
Number3 = Temp 2
OUTPUT Number1, Number2, Number3 3 6 2

Conclusion: agrees with known solution

DESK CHECK
for Input 9, 14, 7 (known solution 7,14,9)

Statement Number1 Number2 Number3 Temp


INPUT Number1, Number2, Number3 9 14 7
Temp = Number1 9
Number1 = Number3 7
Number3 = Temp 9
OUTPUT Number1, Number2, Number3 7 14 9

Conclusion: agrees with known solution

Note: in both cases the first and third numbers are swapped.

Page 73
Example - Coin1

PROGRAM SPECIFICATION

DESCRIPTION
Design a program to calculate the number of cents in a group of $2, $1, 50 cent, 20 cent,
10 cent, and 5 cent pieces. The number of each type of coin is entered from the keyboard
and the result in cents returned to the screen.

INPUTS
Name Description Legal Values Data type Source
FiftyC Number of 50c coins entered Non-negative Integer Keyboard
FiveC Number of 5c coins entered Non-negative Integer Keyboard
OneD Number of $1 coins entered Non-negative Integer Keyboard
TenC Number of 10c coins entered Non-negative Integer Keyboard
TwentyC Number of 20c coins entered Non-negative Integer Keyboard
TwoD Number of $2 coins entered Non-negative Integer Keyboard

PROCESSING
calculate value in cents
OUTPUTS
value of coins
MAJOR TASKS
input number of each coin
calculate total value
output value

KNOWN RESULTS

2@$2, 2@$1, 4@50c, 3@20c, 1@10c, 5@5c = 895 cents


4@$2, 1@$1, 3@50c, 7@20c, 2@10c, 1@5c = 1215 cents

DATA DICTIONARY

Variable Description Legal Values Data type Source


Cents Total value of coins Non-negative Integer Internal
FiftyC Number of 50c coins entered Non-negative Integer Keyboard
FiveC Number of 5c coins entered Non-negative Integer Keyboard
OneD Number of $1 coins entered Non-negative Integer Keyboard
TenC Number of 10c coins entered Non-negative Integer Keyboard
TwentyC Number of 20c coins entered Non-negative Integer Keyboard
TwoD Number of $2 coins entered Non-negative Integer Keyboard

Page 74
PSEUDOCODE

PROGRAM Coin1
INPUT TwoD, OneD, FiftyC, TwentyC, TenC, FiveC
Cents = (TwoD * 200) + (OneD * 100) + (FiftyC * 50) + (TwentyC * 20) +
(TenC * 10) + (FiveC * 5)
OUTPUT Cents
END Coin1

DESK CHECK for INPUT 2, 2, 4, 3, 1, 5 (known solution 895)

Statement TwoD OneD FiftyC TwentyC TenC FiveC Cents


INPUT TwoD, OneD, 2 2 4 3 1 5
FiftyC, TwentyC,
TenC, FiveC
Cents = TwoD * 200 + 895
OneD * 100 + FiftyC *
50 + TwentyC * 20 +
TenC * 10 + FiveC * 5
OUTPUT Cents 895

Conclusion: agrees with known solution

DESK CHECK for INPUT 4, 1, 3, 7, 2, 1 (known solution 1215)

Statement TwoD OneD FiftyC TwentyC TenC FiveC Cents


INPUT TwoD, OneD, 4 1 3 7 2 1
FiftyC, TwentyC,
TenC, FiveC
Cents = TwoD * 200 + 1215
OneD * 100 + FiftyC *
50 + TwentyC * 20 +
TenC * 10 + FiveC * 5
OUTPUT Cents 1215

Conclusion: agrees with known solution

Page 75
Exercises – Sequence Documentation

For each of the following programs provide the data dictionary, known results and deskcheck:

Exercises 3-15

POST1: A program outputs to the screen the postage charge for a parcel when the weight of the
parcel (in Kg) is entered from the keyboard. The rate of postage is set at $1.50 per kg.

Exercises 3-16

ANIM1:The consultation fee for a vet is obtained by multiplying the number of hours by the hourly
rate of $25. A program accepts the number of hours (whole number) from the keyboard
and outputs the consultation fee to the screen.

Exercises 3-17

BANK1:A loan officer requires a program to calculate the monthly repayment M on a customer
loan by entering from the keyboard the principal P, at an annual interest rate of R% pa.,
over a period of T years where M=P(1+RT/100.0)/(12T). All inputs and the result is
output to the screen.
(Known Result P=1000, R=10 and T=10 : M=166.67)

Exercises 3-18

TEMP1:Convert a temperature entered from the keyboard in degrees Fahrenheit to degrees


Celsius where degC=(degF-32)/1.8 and output the result to the screen.
(Known Result degF=100 : degC=37.8)

Exercises 3-19

RECT1:A program accepts the height and width of a rectangle from the keyboard, calculates the
perimeter and area of the rectangle and outputs the results to the screen.

Exercises 3-20

DISC1:A program accepts the marked value of an item in $ and cents, and the discount rate as a %
from the keyboard and returns the discounted price to the screen.

Exercises 3-21

Page 76
TIME1:A program allows a person to enter values for the number of days, hours, minutes and
seconds and outputs the total number of seconds to the screen.

Page 77
CASE STUDY – PFEECAL2
Change the program PfeeCal1 so that the information keyed in by the user is laid out in tabular
form with the associated costs for Networkers, Programmers and Office workers (you will need 3
variables to store these costs) and the total cost. Write the pseudocode and C code.

Write a program that will request the following information from a user:
An ID number (4 digit integer)
The number of required networker days.
The number of required programmer days.
The number of required office administrator days.

The following table shows the fees that are charged:


Professional Charge per day for a
Casual Customer
A Network professional (N) $115.00
An Office administrator (O) $120.00
A Programmer (P) $100.00

Your program should then calculate the associated costs for Networkers, Programmers and Office
workers and total cost and output these costs in a table to the screen.

Example Output:

Cust ID 1234

Profession Days Cost


----------------------------------------------
Networker 1 $115.00
Office 1 $120.00
Programmer 2 $200.00
----------------------------------------------
Total Cost $435.00

Page 78
CHAPTER 3 REVIEW QUESTIONS
1. List the six stages in the program development cycle.

2. Why is a program specification important? What details are documented in a program


specification?

3. What is an algorithm, give 3 examples?

4. What is a data dictionary?

5. Why is a desk check used?

Page 79
CHAPTER 4 -
LOGIC AND EXPRESSIONS

Upon successful completion of this chapter you will be able to:

• Write and use logical expressions

• Use the logical operators NOT, AND, OR

• Use relational operators

Summary of new terms:


Logical expression - an expressions that can have only two possible values: true or false.
Logical operators – NOT, AND, OR.
Relational operators – used to make comparisons between data eg >, <, =.

Page 81
OVERVIEW
This chapter introduces the use of relational operators and logical expressions in C. Relational
operators are used to test the values of variables, and give a result that is either true or false. An
expression using relational operators is called a logical expression. Such expressions can be
combined together to allow more complex tests.

You have already met the basic arithmetic operators. This chapter presents some of the other
operators that can be used in C.

LOGICAL EXPRESSIONS
A logical expression is one that can have only two possible values - true or false. Logical
expressions are sometimes known as boolean expressions.

Some examples of logical expressions are:

tax to be paid equals zero


temperature hotter than 30 degrees Celsius
age older than 10
weekly pay greater than 100
car type equals Holden

Note that in all of the above examples there are only two possible “answers” to or values of the
expression:

true (yes) or false (no).

Relational Operators
The simplest logical expression you can have is when a comparison is made between two elements
of the same data type. The example “Weekly-Pay greater than 100” is such an expression because
we are comparing the value of the weekly pay with another value (100 - a literal constant). These
expressions are given a special name - relational expressions . A relational expression consists of
making comparisons using relational operators .

The following are the relational operators used in C:

== equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
!= not equal to

WARNING: a very common error in C is to confuse


the equals operator ==
with the assignment operator =

Page 82
Notice that the symbols used for greater than or equal to, for less than or equal to and for not equal
to are different to the ones used in mathematics (≥, ≤ and ≠). In most computer input devices the
maths symbols are not available.

Some examples of relational expressions using everyday notation are:

Tax ≠ 0
MenuChoice = 1
Temperature > Minimum
Age > 10
MyWeeklyPay < YourWeeklyPay
Tax ≤ 5
ParkingFine ≠ 0

This is now the same expressions would be written in C:

Tax != 0
MenuChoice == 1
Temperature > Minimum
Age > 10
MyWeeklyPay < YourWeeklyPay
Tax <= 5
ParkingFine != 0

A relational expression (sometimes called a simple logical expression) has the form:

Variable1/CONSTANT1 relational operator Variable2/CONSTANT2

NOTE that Variable1/CONSTANT1 and Variable2/CONSTANT2 must have the same data type.

Logical Operators
Complex logical expressions can be formed by combining simple logical (relational) expressions
using logical operators. The three logical operators in C are:

! NOT
&& AND
|| OR

For example the two simple relational expressions:


Temperature > 90
Humidity > 80
could be joined together to give the complex logical expression

(Temperature > 90) && (Humidity > 80)

Page 83
This statement will only be true if both the temperature is greater than 90 and the humidity is greater
than 80.

Thus complex logical expressions take the form:

(relational expression) logical operator (relational expression)


or
!(relational expression).

Logical Operator AND (&&)


Let’s assume that A and B represent any logical expression, so A has a true or false value and
similarly for B.

The evaluation of A AND B can be verbally explained as follows:


Whenever A and B are both true then the expression (A AND B) is true.
Whenever either (or both) of A and B is false then the expression (A AND B) is false.

For example, suppose that you can go on a holiday only if you have a certain number of frequent
flyer points AND a certain amount of spending money. The limiting amounts are defined as
constants MIN_FREQ_FLY_PTS and MIN_SPEND_MONEY. The following expression
evaluates to true or false depending on whether you can go or not:

(FrequentFlyerPoints >= MIN_FREQ_FLY_PTS) && (SpendingMoney >= MIN_SPEND_MONEY)

The variable FrequentFlyerPoints is checked to see if its value is greater than or equal to the value of
the constant MIN_FREQ_FLY_PTS AND the variable SpendingMoney is checked to see if its
value is greater than or equal to the value of the constant MIN_SPEND_MONEY. If both these
conditions are true the entire expression takes on the value TRUE, and therefore the person can
take the holiday.

Logical Operator OR (||)


If A and B are both logical expressions then the evaluation of A OR B can be verbally explained as
follows:

Whenever either or both of A and B is true then the expression (A OR B) is true.


Whenever A and B are both false then the expression (A OR B) is false.

For example, suppose that you can get a ticket to see the Adelaide Crows in the Grand Final only if
you are a Gold member of the club OR you have attended a certain number of games during the
year. The minimum required number of games is the constant MIN_GAMES_ATTENDED. The
following expression evaluates to true or false depending on whether you can get tickets or not:

(CrowsMember == ‘G’) || (GamesAttended >= MIN_GAMES_ATTENDED)

The CrowsMember variable is checked to see if its value is ‘G’ and the NumGamesAttended
variable is checked to see if its value is greater than or equal to the value of the constant

Page 84
MIN_GAMES_ATTENDED. Therefore if either or both of these conditions are true then the
entire Boolean expression is true. Therefore the person is eligible to get their grand final tickets.

Logical Operator NOT !


The logical operator ! reverses the result of an expression. If A is evaluated as TRUE then !A
evaluates as FALSE.

Truth Tables
Sometimes it is helpful to write a table of possible values for a logical expression. These tables are
called truth tables.

The following are truth tables which show all the possible values for the logical operators &&, || and
!.

A B A && B A || B !A !B
true true true true false false
true false false true false true
false true false true true false
false false false false true true

Operator Precedence
In the evaluation of logical expressions ! has highest precedence and && takes precedence over ||.
This means that if both an && and an || appear in the expression then the && will be considered
first.

Hence, the following two logical expressions are equivalent:

A == B || C == O && E != F
A == B || (C == O && E != F)

Brackets may be used to change this order of evaluation and the result is logically different:
(A == B || C == O) && E !=F

If you have any doubt about the order in which the parts of an expression will be evaluated, it is
safer to use brackets to force the order you want.

Using ! (NOT) In Relation Expressions


In this section we are required to use the concept !A where A is a relational expression.
There are 6 relational operators and their equivalent opposites:

Operator Opposite
== !=
< >=
> <=
<= >
>= <

Page 85
!= ==
eg. !(GrossPay < 0) is equivalent to GrossPay >= 0
!(GrossPay > 2000) is equivalent to GrossPay <= 2000

Using ! with && and ||


If we consider A and B to be any logical expressions then :

!(A && B) is equivalent to !A || !B


You can verify these results by looking at some truth tables :

A B A && B !(A && B) !A !B !A || !B


T T T F F F F
T F F T F T T
F T F T T F T
F F F T T T T

Notice that the 4th and 7th columns are identical, showing the equivalence of the two expressions.

We can also show that

!(A || B) is equivalent to !A && !B

You can verify these results by looking at some truth tables :


A B A || B !(A || B) !A !B !A && !B
T T T F F F F
T F T F F T F
F T T F T F F
F F F T T T T
Notice that the 4th and 7th columns are identical, showing the equivalence of the two expressions.

ADDITIONAL C OPERATORS
In your study of C so far, you have come across a number or operators, such as the arithmetic
operators + – * /, the assignment operator = , and, in this chapter, the relational and logical
operators.

C has more operators than these, but the ones you know already will be enough for most purposes.
There are just a few more that you may meet in the course of your work, or in later chapters.

Operators are classified by the number of operands they have, that is, by the number of quantities
they operate on. A unary operator works on only one value. The – in front of a negative number is a
unary operator, as is the logical operator ! (meaning not). A binary operator acts on two values. The
ordinary arithmetic operators (+ – etc) are binary operators.

• The remainder operator, %, is a binary operator which gives the remainder when one number
is divided by another. For example, the expression 6 % 4 would have the value 2.

Page 86
• The increment operator, ++ is a unary operator. It is sometimes used as shorthand in C. The
expression i++ is equivalent to the assignment statement i = i + 1.

• The address operator & and the dereferencing operator * are unary operators used for
handling pointers. In fact, you have already used the address operator every time you have
called the scanf function.

Operator precedence

Just as with logical operators, there is a precedence order among other operators. In general, unary
operators are evaluated before binary operators. In arithmetic expressions, multiply, divide and
remainder have precedence over addition and subtraction.

In the following table, the brackets in the right-hand expression show the order in which calculations
would be done in the corresponding left-hand expression.

a+b*c+d a + (b * c) + d
a+b<c (a + b) < c
a + b < -c (a + b) < (-c)
a + b * c != d (a + (b * c)) != d
p>q || a + b < c && i + j < k (p>q) || (((a + b) < c) && ((i + j) < k))

Note: it is not necessary to put in the brackets as shown in the right column, the computer would
calculate in the order shown.

Page 87
Exercises – Logical Expressions
Determine which of the following logical expressions are true and which are false for the following
sets of values:

Exercise 4-1

For Hours = 0, Mins = 30

(a) (Hours >= 0) && (Hours < 24)


(b) (Mins >= 0) && (Mins < 60)
(c) (Hours < 0) || (Hours >= 24)
(d) (Mins < 0) || (Mins >= 30)
(e) !((Hours < 0) || (Hours >= 24))
(f) !((Mins < 0) || (Mins >= 60))
(g) (Hours > 10) || (Mins <= 30)
(h) (Hours > 10) && (Mins <= 30)
(i) !(Hours > 10) && (Mins >= 20)

Exercise 4-2

Hours = 10, Mins = 60

(a) (Hours >= 0) && (Hours < 24)


(b) (Mins >= 0) && (Mins < 60)
(c) (Hours < 0) || (Hours >= 24)
(d) (Mins < 0) || (Mins >= 60)
(e) !((Hours < 0) || (Hours >= 24))
(f) !((Mins < 0) || (Mins >= 60))
(g) (Hours > 10) || (Mins <= 30)
(h) (Hours > 10) && (Mins <= 30)
(i) !(Hours > 10) || (Mins >= 20)

What do you notice about the results from questions (a) and (e) and the results from questions (b)
and (f)?

Page 88
CHAPTER 5 -
SELECTION: IF STRUCTURE

Upon successful completion of this chapter you will be able to:

• Write and use logical expressions in selection structured programs

• Write the pseudocode for selection structured programs

• Use the if - else statement in C code programs to solve a selection structured program

Summary of new terms:

Selection Structure – used to make a choice between tasks, where the choice can be either true
or false.

Page 89
OVERVIEW
You have previously learned about relational operators and logical expressions. We will now
examine how to use them to control program flow and make decisions involving program execution
within the program. Selection techniques allow you to write much more complex programs, so
program testing becomes more important.

SELECTION USING PSEUDOCODE


In an algorithm a choice may need to be made between tasks.
This choice may be:
Choose one task or do nothing.
Choose between two tasks.
Choose one of many tasks.
The choice is made by evaluating a logical expression, which has one of two values: TRUE or
FALSE.
Structure Pseudocode Use
Single Choice IF condition THEN When choosing to do
IF_THEN statement(s) something when the condition
ENDIF is TRUE or to do nothing when
it is FALSE.

Two Way Choice IF condition THEN When choosing to do


IF_THEN_ELSE statement(s) something when the condition
ELSE is TRUE or to do something
statement(s) else when it is FALSE.
ENDIF

Multiple Choice IF condition THEN IF_THEN_ELSE structures


Nested statement(s) can be nested inside one
IF_THEN_ELSE ELSE another.
IF condition THEN
statement(s)
ELSE
statement(s)
ENDIF
ENDIF

Multiple Choice CASE variable When a single variable takes


CASE value1: discrete (whole) values and an
statement(s) action is chosen from one of
value2: these values. If none of the
statement(s) values is present there is an
. ELSE option.
.
value n:
statement(s)
ELSE

Page 90
statement(s)
ENDCASE

Page 91
Example - Rain1

A simple example might be a decision you make each morning such as, if it looks like rain I will take
my umbrella.
(Note: otherwise do nothing)
Pseudocode

PROGRAM Rain1
IF Rain is likely THEN
Take umbrella
ENDIF

Or an extension of the example might be - if rain is likely then drive the car, otherwise walk to work:
Pseudocode
PROGRAM Rain1a
IF Rain is likely THEN
Drive car to work
ELSE
Walk to work
ENDIF

Example - Tax2

A further stage of the Tax1 problem may be to calculate tax on the GrossPay that exceeds a base of
$5,000.

PROGRAM Tax2 PROGRAM Tax1

DEFINE BASE=5000, TAX_RATE=0.25 DEFINE TAX_RATE=0.25


INPUT GrossPay INPUT GrossPay
IF GrossPay > BASE THEN Tax = GrossPay * TAX_RATE
Tax = (GrossPay - BASE) * TAX_RATE
ELSE
Tax = 0
ENDIF
NettPay = GrossPay - Tax NettPay = GrossPay - Tax
OUTPUT NettPay OUTPUT NettPay

Notice how the one calculation statement in example Tax1, Tax= (at right) has been replaced by
the IF_THEN_ELSE structure on the left.

Page 92
SELECTION - C CODE
If - else statement
The if - else statement controls the flow of the execution of statements by testing whether a
particular condition is true or false. If the condition is true then the statements between the word "if"
and the word "else" are executed. If the condition is false then the statements between the else and
the end of the if-else statement are executed. In fact, the "else" part isn't required; therefore if the if-
statement does not need an else part then it can be left off.

A simple if-else statement consists of:


1. The control statement "if".
2. The condition statement within brackets e.g. (A == 5).
3. Left bracket { to start statements to be executed when true.
4. The program statement(s) for the condition evaluated as true.
5. Right bracket } to end the block of statements executed when true.
6. The control statement "else".
7. Left bracket { to start statements to be executed when false.
8. The program statement for the condition evaluated as false.
9. Right bracket } to end the block of statements executed when false.

An example of a simple if-else statement is given below.

if (Num1 == Num2)
{
Answer = Num1 + 1;
}
else
{
Answer = Num2 + 10;
}

Note: The double equals (==) between the Num1 and the Num2 in the above Figure is an equality
operator and tests whether variable Num1 is equal to variable Num2.

Often we will want one branch of the if-else statement to execute more than one program statement.
To do this we must enclose the statement to be executed together within curly brackets (ie. { })
and separated by semi-colons. These brackets are not actually necessary when there is only one
statement to be executed. This situation is called a compound statement. An example is shown
below.

if (Counter > 0)
{
printf("You are positive");
Salary = 100.0;
Payments = 0.0;
}
else
{
printf("You are negative (or zero!)");
Salary = 0.0;

Page 93
Payments = 250.0;
}

Page 94
SELECTION EXAMPLES
Example Program Tax2

PseudoCode
Program Tax2
DEFINE CONSTANTS BASE=5000, RATE=0.25
INPUT GrossPay
IF GrossPay>BASE THEN
Tax=(GrossPay-BASE)*RATE
ELSE
Tax=0
ENDIF
NettPay=GrossPay-Tax
OUTPUT NettPay
END Tax2

C Code

/**********************************************************************
* Program | Tax2
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Calculates tax on the gross pay which exceeds a base
* | of $5000 and calculates the nett pay.
*/

#include <stdio.h>
#include <conio.h>

#define BASE 5000


#define TAX_RATE 0.25

int main(void)
{
float GrossPay = 0;
float NettPay = 0;
float Tax = 0;

clrscr();

printf("Enter the Gross Pay: ");


scanf("%f",&GrossPay);

if (GrossPay > BASE)


{
Tax=(GrossPay - BASE) * TAX_RATE;
}
else
{
Tax = 0;
}
NettPay = GrossPay - Tax;

printf("\nThe Nett Pay is $%.2f",NettPay);

Page 95
printf("\nPress Enter to continue");
getch();
return 0;
}

Page 96
DOCUMENTED EXAMPLES
Below are two worked examples showing full documentation, namely:

1. Program specification.
2. Known results.
3. Data dictionary.
4. Design with pseudocode.
5. Desk checks.

Example - Sort2

PROGRAM SPECIFICATION

DESCRIPTION
Design a program to accept three whole numbers from the keyboard and output them in
ascending order to the screen.

INPUTS
Name Description Legal Values Data type Source
Number1 First number entered No restriction Integer Keyboard
Number2 Second number entered No restriction Integer Keyboard
Number3 Third number entered No restriction Integer Keyboard
PROCESSING
Sort into ascending order
OUTPUTS
The three numbers to the screen
OVERALL TASKS
Input numbers
Sort order
Output numbers

KNOWN SOLUTIONS

INPUT = 2, 6, 3 OUTPUT = 2, 3, 6
INPUT = 14, 9, 7 OUTPUT = 7, 9, 14

DATA DICTIONARY

Variable Description Legal Values Data type Source


Number1 First number entered No restriction Integer Keyboard
Number2 Second number entered No restriction Integer Keyboard
Number3 Third number entered No restriction Integer Keyboard
Temp Temporary for swap No restriction Integer Internal

Page 97
Page 98
PSEUDOCODE
PROGRAM Sort2
INPUT Number1, Number2, Number3
IF Number1 > Number2 THEN
Temp = Number1
Number1 = Number2
Number2 = Temp
ENDIF
IF Number2 > Number3 THEN
Temp = Number2
Number2 = Number3
Number3 = Temp
ENDIF
IF Number1 > Number2 THEN
Temp = Number1
Number1 = Number2
Number2 = Temp
ENDIF
OUTPUT Number1, Number2, Number3
END Sort2

DESK CHECK for Input 2, 6, 3 (known solution 2, 3, 6)

Statement Logical Number1 Number2 Number3 Temp


INPUT Number1, 2 6 3
Number2, Number3
Number1 > Number2 F
Number2 > Number3 T
Temp = Number2 6
Number2 = Number3 3
Number3 = Temp 6
Number1 > Number2 F
OUTPUT Number1, 2 3 6
Number2, Number3
Conclusion: results correct.

DESK CHECK for Input 14, 9, 7 (known solution 7, 9, 14)

Statement Logical Number1 Number2 Number3 Temp


INPUT Number1, 14 9 7
Number2, Number3
Number1 > Number2 T
Temp = Number1 14
Number1 = Number2 9
Number2 = Temp 14
Number2 > Number3 T
Temp = Number2 14
Number2 = Number3 7
Number3 = Temp 14
Number1 > Number2 T

Page 99
Temp = Number1 9
Number1 = Number2 7
Number2 = Temp 9
OUTPUT Number1, 7 9 14
Number2, Number3
Conclusion: results correct.

C Code
/**********************************************************************
* Program | Sort2
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Functions | Sorts three integers into ascending order.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
int Number1 = 0;
int Number2 = 0;
int Number3 = 0;
int Temp = 0;

clrscr();
printf("Enter the first integer: ");
scanf("%i",&Number1);
printf("Enter the second integer: ");
scanf("%i",&Number2);
printf("Enter the third integer: ");
scanf("%i",&Number3);

if (Number1 > Number2)


{
Temp = Number1;
Number1 = Number2;
Number2 = Temp;
}
if (Number2 > Number3)
{
Temp = Number2;
Number2 = Number3;
Number3 = Temp;
}

/*
* Number3 is NOW the largest number, just need to get Number1
* and Number2 in the right order
*/
if (Number1 > Number2)
{
Temp = Number1;
Number1 = Number2;
Number2 = Temp;

Page 100
}

printf("The numbers in ascending order ");


printf("are %i %i %i",Number1,Number2,Number3);
printf("\nPress Enter to continue");
getch();
return 0;
}

Page 101
Example - Coin2

PROGRAM SPECIFICATION

DESCRIPTION

Design a program to calculate the value of a group of $2, $1, 50 cent, 20 cent, 10 cent and
5 cent pieces. The number of each type of coin is entered at the keyboard and the result is
displayed on the screen in cents or dollars depending if a C or a D is entered.

INPUTS
Name Description Legal Values Data type Source
FiftyC Number of 50c coins entered Non-negative Integer Keyboard
FiveC Number of 5c coins entered Non-negative Integer Keyboard
OneD Number of $1 coins entered Non-negative Integer Keyboard
TenC Number of 10c coins entered Non-negative Integer Keyboard
TwentyC Number of 20c coins entered Non-negative Integer Keyboard
TwoD Number of $2 coins entered Non-negative Integer Keyboard
Choice C or D for answer in cents or dollars C or D Char keyboard

PROCESSING
Calculate value in cents for C entered, dollars for D

OUTPUTS
Value of coins in cents or dollars

MAJOR TASKS
Input number of each coin
Calculate total value in cents, adjust to dollars if D is entered
Output value

KNOWN RESULTS

Choice ‘C’ : 2@$2, 2@$1, 4@50c, 3@20c, 1@10c, 5@5c = 895 cents
Choice ‘D’ : 4@$2, 1@$1, 3@50c, 7@20c, 2@10c, 1@5c = $12.15

Page 102
DATA DICTIONARY

Variable Description Legal Values Data type Source


Cents Total value of all coins in cents Non-negative Integer Internal
Choice C or D for answer in cents or dollars C or D Char Keyboard
Dollars Total value of all coins in dollars Non-negative Real Internal
FiftyC Number of 50c coins entered Non-negative Integer Keyboard
FiveC Number of 5c coins entered Non-negative Integer Keyboard
OneD Number of $1 coins entered Non-negative Integer Keyboard
TenC Number of 10c coins entered Non-negative Integer Keyboard
TwentyC Number of 20c coins entered Non-negative Integer Keyboard
TwoD Number of $2 coins entered Non-negative Integer Keyboard

PSEUDOCODE
PROGRAM Coin2

INPUT TwoD, OneD, FiftyC, TwentyC, TenC, FiveC


INPUT Choice
Cents = (TwoD * 200) + (OneD * 100) + (FiftyC * 50 ) + (TwentyC * 20) +
(TenC * 10) + (FiveC * 5)
IF Choice = ‘C’ THEN
OUTPUT Cents
ELSE
Dollars = Cents / 100
OUTPUT Dollars
ENDIF
END Coin2

DESK CHECK for INPUT 2, 2, 4, 3, 1, 5, C (known result 895)

Statement Logical TwoD OneD FiftyC TwentyC TenC FiveC Choice Cents Dollars
INPUT TwoD, 2 2 4 3 1 5
OneD, FiftyC,
TwentyC, TenC,
FiveC
INPUT Choice C
Cents = TwoD * 895
200 + OneD *
100 + FiftyC *
50 + TwentyC *
20 + TenC * 10
+ FiveC * 5
IF Choice = ‘C’ T
OUTPUT Cents 895

Conclusion – results correct

DESK CHECK for INPUT 4, 1, 3, 7, 2, 1, D (known result 12.15)

Statement Logical TwoD OneD FiftyC TwentyC TenC FiveC Choice Cents Dollars
INPUT TwoD, 4 1 3 7 2 1
OneD, FiftyC,
TwentyC, TenC,

Page 103
FiveC
INPUT Choice D
Cents = TwoD * 1215
200 + OneD *
100 + FiftyC *
50 + TwentyC *
20 + TenC * 10
+ FiveC * 5
IF Choice = ‘C’ F
Dollars= 12.15
Cents/100
OUTPUT 12.15
Dollars

Conclusion – results correct

Page 104
C Code

/**********************************************************************
* Program | Coin2
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Functions | Calculates the total number of coins from the
* | number of each type of coin entered and displays
* | either total cents or dollars depending on
* | the choice.
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

int main(void)
{
int Cents = 0;
int TwoD = 0;
int OneD = 0;
int FiftyC = 0;
int TwentyC = 0;
int TenC = 0;
int FiveC = 0;
char Choice = 0;
float Dollars = 0;

clrscr();
printf("Enter the number of two dollar coins: ");
scanf("%i",&TwoD);
printf("\nEnter the number of one dollar coins: ");
scanf("%i",&OneD);
printf("\nEnter the number of fifty cent coins: ");
scanf("%i",&FiftyC);
printf("\nEnter the number of twenty cent coins: ");
scanf("%i",&TwentyC);
printf("\nEnter the number of ten cent coins: ");
scanf("%i",&TenC);
printf("\nEnter the number of five cent coins: ");
scanf("%i",&FiveC);
printf("\nEnter your choice of conversion");
printf("\nC for cents or D for dollars: ");
fflush(stdin);
scanf("%c", &Choice);
Choice = toupper(Choice); /* Convert to uppercase */
Cents = (TwoD * 200) + (OneD * 100) + (FiftyC * 50) + (TwentyC * 20)
+ (TenC * 10) + (FiveC * 5);

if (Choice == 'C')
{
printf("The total number of cents is: %i",Cents);
}
else
{
Dollars = Cents / 100.0;
/* Note: Use 100.0 to convert result to float*/

Page 105
printf("The total dollar value of the coins is: ");
printf("%.2f",Dollars);
}
printf("\nPress Enter to continue");
getch();
return 0;
}

Page 106
Exercises – using If
For each of the following programs:
1. provide the Algorithm using pseudocode.
2. provide the C code
(each question is a continuation of previous sequence exercises of the same name eg POST2 is a
modification to previous sequence exercise POST1):

Exercise 5-1

POST2: Modify the design of POST1 to calculate the postage charge for a parcel when the weight
of the parcel (in Kg) is entered from the keyboard but to allow for a maximum charge of
$10.00 no matter what weight in kg is entered. The postage rate is set at $1.50 per kg.

Exercise 5-2

ANIM2: Modify the program developed in ANIM1 to accept 4 types of animals (B,C,D,O), the
consultation in hours(whole number) and sundry medicine charge. Echo the input and
display the consultation fee for the visit. Calculate the charge for the consultation as
follows:
Rate for Birds $20, Cats $25, Dogs $40, Other $55 per hour where Charge = Rate *
Hours + Sundry.

Exercise 5-3

BANK2: Modify the design developed in BANK1 to accept a customer’s monthly income as well
as the loan details: principal P, at an annual interest rate of R% pa., over a period of T
years. Calculate the monthly repayment M=P(1+RT/100.0)/(12T). Output the details
entered together with the monthly repayment and a message to indicate "NO LOAN"
when the repayment is greater then 25% of the monthly income otherwise "LOAN OK".

Exercise 5-4

TEMP2: Modify the design developed for TEMP1 to allow the user to choose conversion from
degF to degC or degC to degF ie. if the choice is 1 then a temperature in degrees F is
entered and converted to degrees C where degC=(degF-32)/1.8 otherwise it can be
assumed that a temperature in degrees C is entered and converted to degrees F where
degF=1.8*degC+32.

Exercise 5-5

RECT2: Modify the design of RECT1 to calculate and output the perimeter and area of a
rectangle only if the width is less than or equal to the height, if not output a suitable error
message.

Page 107
Exercise 5-6

DISC2: Modify the design of DISC1 to accept a request for Markup (M) or Discount (D) and
input either the markup percentage or discount percentage. Output to the screen the new
price marked up or discounted by the % entered.

Exercise 5-7

TIME2: Modify the design of TIME1 to calculate and output the total number of seconds when
days >=0, hours>=0, minutes>=0 and seconds>=0. Output an error message if any input
is wrong.

Extra Exercises - If

Exercise 5-8

Write a program that determines whether or not you have to pay for your delivered pizza and then
displays the answer. You are required to enter the number of pizzas ordered and delivery time in
minutes. Each pizza costs $5.50. If the delivery takes more than 30 minutes then you don't have to
pay.

Exercise 5-9

Write a program that inputs the number of “sickies” an employee has taken and outputs a message
whether or not the employee has to give a medical certificate to the employer for taking a "sickie".
An employee can have five "sickies" a year before producing a medical certificate.

Exercise 5-10

Write a program, which determines whether you can afford a deposit on a car you want to buy.
Enter the price of the car and the amount of deposit you can afford. If you can give a deposit of a
least 10% of the car’s price then output a message you have a deal otherwise output a message you
cannot afford the car.

Page 108
CASE STUDY - PFEECAL3
Edit the program from PFeeCal2 so that the program asks for the type of customer (‘R’ for regular
or ‘C’ for casual) before asking for the number of days. A regular customer will receive 5%
discount on the fee. Change the algorithm calculating the cost to include the discount.

PfeeCal#3:
Write a program that will request the following information from a user:
An ID number (4 digit integer)
The type of customer (‘R’ regular or ‘C’ casual)
The number of required networker days.
The number of required programmer days.
The number of required office administrator days.

The following table shows the fees that are charged:


Professional Charge per day for a
Casual Customer
A Network professional (N) $115.00
An Office administrator (O) $120.00
A Programmer (P) $100.00

A regular customer will receive 5% discount on the fee. Your program should calculate the
associated costs for Networkers, Programmers and Office workers and total cost and output these
costs in a table to the screen.

Page 109
CHAPTER 6 -
SELECTION: NESTED IF STRUCTURE

Upon successful completion of this chapter you will be able to:

• Write and use logical expressions in nested-if structured programs

• Write the pseudocode for nested-if structured programs

• Use the nested if - else statement in C code programs

Summary of new terms:

Nested-if Structure – used to make a multiple choice selection between tasks.

Page 111
OVERVIEW
In this section we shall discuss the use of the nested if structures in programming. We shall examine
the syntax for coding nested if statements and develop programs that can use these structures.

NESTED IF STRUCTURES
Previously we dealt with single level IF-THEN and IF-THEN-ELSE statements. Here we will look
at 2 examples to illustrate more complex structures by nesting IF-THEN-ELSE statements.

In the first example the inner IF-THEN-ELSE is nested inside the true part of the outer IF-THEN-
ELSE In the second the inner part is nested in the else part.

NOTE carefully the use of brackets {} in these structures.

Example Nested If

PseudoCode C Code
IF (logicalexpr1) THEN if (logicalexpr1)
{
IF (logicalexpr2) THEN if (logicalexpr2)
{
statement(s)_1 statement(s)_1;
}
ELSE else
{
statement(s)_2 statement(s)_2;
ENDIF }
}
ELSE else
{
statement(s)_3 statement(s)_3;
ENDIF }

In this first example


Statement(s)_1 is executed if LogicalExpr1 is True and LogicalExpr2 is True.
Statement(s)_2 is executed if Logical Expr1 is True and LogicalExpr2 is False.
Statement(s)_3 is executed if LogicalExpr1 is False.

Page 112
Example Pseudocode – Nested If

PseudoCode C Code
IF (logicalexpr1) THEN if (logicalexpr1)
{
statement(s)_1 statement(s)_1;
}
ELSE else
{
IF (logicalexpr2) THEN if (logicalexpr2)
{
statement(s)_2 statement(s)_2. . .;
}
ELSE else
IF (logicalexpr3) THEN if (logicalexpr3)
{
statement(s)_3 statement(s)_3;
}
ELSE else
{
statement(s)_4 statement(s)_4;
ENDIF }
ENDIF }
ENDIF

In this second example


Statement(s)_1 is executed if LogicalExpr1 is True.
Statement(s)_2 is executed if LogicalExpr1 is False and LogicalExpr2 is True.
Statement(s)_3 is executed if LogicalExpr1 is False and LogicalExpr2 is False and LogicalExpr3 is
True.
Statement(s)_4 is executed if LogicalExpr1 is False and LogicalExpr2 is False and LogicalExpr3 is
False.

Page 113
Example Program Tax3NEST

Consider the following tax scale


GrossPay TaxRate
0 - 5000 0
5001-20000 25%on excess over 5000
> 20000 tax on first 20,000+40% on excess over 20000
Calculate and output the Nett pay given a Gross pay.

PseudoCode:
PROGRAM Tax3Nest
DEFINE BASE1=5000, BASE2=20000, RATE1=0.25, RATE2=0.4
INPUT GrossPay
IF GrossPay <= BASE1 THEN
Tax = 0
ELSE
IF GrossPay <= BASE2 THEN
Tax = RATE1*(GrossPay - BASE1)
ELSE
Tax = RATE2*(GrossPay - BASE2) + RATE1*(BASE2-BASE1)
ENDIF
ENDIF
NettPay = GrossPay - Tax
OUTPUT NettPay
END Tax3Nest

This first logical structure in the Calculation of Tax tests for GrossPay <= BASE1 (0-5000) and if
this is true, Tax is calculated as:
Tax=0

If this is not true, then we assume GrossPay is greater than BASE1 (>5000), so we only need to
test for the BASE2 (20000) breakpoint with (GrossPay <=BASE2). If this is true, we calculate
Tax as:
Tax = RATE1*(GrossPay - BASE1)

If the second test is false, then we assume GrossPay must be greater than BASE2(>20000), so we
calculate Tax as :
Tax = RATE2*(GrossPay - BASE2) + RATE1*(BASE2-BASE1)

In this first case we consider we are working up the scale.

Page 114
We could replace the Calculation of Tax with another recommended solution:
(In this second solution we are working down the scale.)

IF GrossPay > BASE2 THEN


Tax = RATE2*(GrossPay - BASE2) + RATE1*(BASE2-BASE1)
ELSE
IF GrossPay > BASE1 THEN
Tax = RATE1*(GrossPay - BASE1)
ELSE
Tax = 0
ENDIF
ENDIF
This second logical structure tests for GrossPay > BASE2. If this is true, Tax is calculated with:
Tax = RATE2*(GrossPay - BATE2) + RATE1*(BASE2-BASE1).
If this is not true then the GrossPay must be <= to BASE2, so we only need to test for the
breakpoint at BASE1 with (GrossPay> BASE1). If this is true we calculate with:
Tax = RATE1*(GrossPay - BASE1).
If the second test is not true, then GrossPay must be less than or equal to BASE1 so :
Tax=0.

We could also replace the Calculation of Tax with a series of linear IF-THEN statements (which is
NOT recommended):

IF GrossPay <= BASE1 THEN


Tax =0
ENDIF
IF (GrossPay > BASE1) AND (GrossPay <= BASE2) THEN
Tax = RATE1*(GrossPay - BASE1)
ENDIF
If GrossPay > BASE2
Tax = RATE2*(GrossPay - BASE2) + RATE1*(BASE2-BASE1)
ENDIF

This third logical structure tests for each subrange separately. If GrossPay is less than BASE1 then
Tax=0 is calculated and the program then tests for each other subrange even though they are false.
If the GrossPay is actually between BASE1 and BASE2 the first Test will fail, and we then retest
whether GrossPay is >=BASE1 and GrossPay is < BASE2. This is REDUNDANT TESTING.
Similarly if the first two tests both fail we retest again to check for greater than BASE2. The third
version is very inefficient, so either of the first two solutions is preferable.

Page 115
Example C Code Tax3Nest

/**********************************************************************
* Program | Tax3Nest
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Calculates the tax on a gross pay according to a
* | 3-level tax bracket:
. | 0 – $5,000, $5,001 – $20,000 and > $20,000.
*/

#include <stdio.h>
#include <conio.h>

#define BASE1 5000


#define BASE2 20000
#define RATE1 0.25
#define RATE2 0.40

int main (void)


{
float NettPay = 0.0;
float GrossPay = 0.0;
float Tax = 0.0;

/* input Gross Pay */


clrscr();
printf("Enter the Gross Pay $");
scanf("%f",&GrossPay);

/* calculate tax and Nett Pay */


if (GrossPay <= BASE1)
{
Tax=0;
}
else
{
if (GrossPay <= BASE2)
{
Tax = RATE1 * (GrossPay - BASE1);
}
else
{
Tax = RATE2 * (GrossPay - BASE2) + RATE1 * (BASE2 - BASE1);
}
}

NettPay = GrossPay-Tax;

/* output tax and Nett Pay */


printf("The Tax payable is $ %.2f\n",Tax);
printf("The Nett Pay is $ %.2f\n",NettPay);

/* pause */
printf("Press enter to continue");

Page 116
getch();

return 0;
}

Page 117
Example Program GradNest:
This program inputs a student mark and calculates a grade according to the following scale:
Mark Grade
90-100 A
80-89 B
70-79 C
60-69 D
<=59 F

PseudoCode:
PROGRAM GradNest
DEFINE CONST BREAKPT_A=90, BREAKPT_B=80, BREAKPT_C=70, BREAKPT_D=60
INPUT Mark
IF Mark>=BREAKPT_A THEN
Grade = 'A'
ELSE
IF Mark>=BREAKPT_B THEN
Grade = 'B'
ELSE
IF Mark>=BREAKPT_C THEN
Grade = 'C'
ELSE
IF Mark>=BREAKPT_D THEN
Grade = 'D'
ELSE
Grade = 'F'
ENDIF
ENDIF
ENDIF
ENDIF
OUTPUT Grade
END GradNest.

Page 118
Example C Code - GradNest
/**********************************************************************
* Program | GradNest
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Calculates students’ grades according to a
* | 5-level bracket on the mark.
*/
#include <stdio.h>
#include <conio.h>

#define BREAKPT_A 90
#define BREAKPT_B 80
#define BREAKPT_C 70
#define BREAKPT_D 60

int main (void)


{
int Mark = 0;
char Grade = ‘ ‘;
/* input Student mark */
clrscr();
printf("Enter the mark: ");
scanf("%i",&Mark);

if (Mark >= BREAKPT_A)


{
Grade = 'A';
}
else
{
if (Mark >= BREAKPT_B)
{
Grade = 'B';
}
else
{
if (Mark >= BREAKPT_C)
{
Grade = 'C';
}
else
{
if (Mark >= BREAKPT_D)
{
Grade = 'D';
}
else
{
Grade = 'F';
}
}
}
}
/* output Grade */

Page 119
printf("The student grade is : %c\n",Grade);
/* pause */
printf("Press enter to continue");
getch();
return 0;
}

Page 120
Exercises - Nested If

For each of the following programs use a nested-if structure where appropriate:
1. provide the algorithm using pseudocode.
2. provide the C code
(each question is a continuation of previous exercises of the same name eg ANIM3N is a
modification to previous exercises ANIM2):

Exercise 6-1

POST3N:A program requires the weight of a parcel in Kg and the parcel type(S-surface, C-courier
or E-Express) to be entered from the keyboard. The charge is set at $1.50 per kg. There
is a maximum charge of $10 for surface parcels and a maximum charge of $20 for
courier and express parcels. There is also an additional surcharge of $8 for courier
parcels and a surcharge of $5 for express parcels. The parcel type and charge is to be
output to the screen.

Exercise 6-2

ANIM3N:A program accepts the number of hours of the consultation, the animal type (B-bird, C-
cat, D-dog, O-other) and the type of owner (N-normal or F-farmer) from the keyboard.
The consultation fee for a vet is obtained by multiplying the number of hours by the hourly
rate. The hourly rate is set at $20 for birds, $25 for cats, $30 for dogs and $40 for other
animals. There is a 20% discount on the consultation fee for farmers. Output all the inputs
and the consultation fee to the screen.

Exercise 6-3

BANK3N:A loan officer requires a program to calculate the monthly repayment M on a customer
loan by entering from the keyboard the principal P, the term T of the loan(in years) and
the loan type (C-car, I-investment or S-staff). The monthly repayment is calculated as
M=P(1+RT/100.0)/(12T).
The annual interest rate of R% pa. is set at 10% for car loans, 13% for investment loans
and 8% for staff loans. All inputs and the result is output to the screen.

Page 121
Extra Exercises - Nested If

Exercise 6-4

Using a nested-if structure write a program which inputs a Distance and outputs a Cost according to
the following table:

Distance Cost
0 to 99 5.00
100 to 299 8.00
300 to 599 10.00
600 to 999 12.00

Exercise 6-5

Write a program to input the WeeklySalary of a person and output NetSalary and Tax. Use the
following table to compute the Tax.

NetSalary = WeeklySalary - Tax

Weekly Wage ($) Tax Rate (%)


0.00 to 89.99 0
90.00 to 149.99 15
150.00 to 349.99 25
350.00 to 499.99 32
500.00 to 749.99 39
750.00 and over 52

Page 122
CHAPTER 7 -
SELECTION: CASE STRUCTURE

Upon successful completion of this chapter you will be able to:

• Write and use logical expressions in case structured programs

• Write the pseudocode for case structured programs

• Use the switch statement in C code programs

• Use a desk check to determine logic errors

Summary of new terms:

Case Structure – used to make a multiple choice selection between tasks.

Page 123
OVERVIEW
In this section we shall discuss the use of the case structures in programming. We shall examine the
syntax for coding case statements and develop programs that can use these structures.

CASE STRUCTURES
In terms of Structured Programming the case structure is not necessary (because the same result can
always be achieved by lots of nested IF-THEN-ELSE statements) but it is a very useful structure,
particularly when a program requires multiple choice selection and to make some fairly complex
logic much clearer. The compiler actually simply turns a CASE into nested IF-THEN-ELSE’s.

Pseudocode C Code
CASE Variable switch (Variable)
{
case 1: statement(s) case 1: statement(s);
break;
case 2: statement(s) case 2: statement(s);
break;
case 3: statement(s) case 3: statement(s);
break;
...
case n: statement(s) case n: statement(s);
break;
ELSE default: statement(s);
statement(s)
ENDCASE }

In the C Code above

• The reserve words switch (Variable) { begins the case structure and } finishes it.
• Variable must be an integer or character expression
• A constant expression must follow the word case (no ranges)
• statement may be a single statement or a compound statement
• Each case statement must finish with the word break
• The default part is optional.

Page 124
Example - Program CalcCase

Write a program to input a choice to calculate the +, -, x, / of 2 numbers and output the result.
When division is chosen print an error message if the second number is zero otherwise perform the
calculation.

PseudoCode
PROGRAM CalcCase
INPUT Choice
INPUT Num1, Num2
CASE Choice
1: Result = Num1 + Num2
OUTPUT Result
2: Result = Num1 - Num2
OUTPUT Result
3: Result = Num1 * Num2
OUTPUT Result
4: IF Num2 = 0 THEN
OUTPUT error message
ELSE
Result = Num1 / Num2
OUTPUT Result
ENDIF
ENDCASE
END CalcCase

Page 125
Example C Code Program CalcCase

/**********************************************************************
* Program | CalcCase
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Inputs a choice to calculate the + - * or / of
* | two numbers.
*/

#include <stdio.h>
#include <conio.h>

int main (void)


{
int Choice = 0;
float Num1 = 0.0;
float Num2 = 0.0;
float Result = 0.0;

clrscr();
printf("Calculator Program\n");
printf("\t1. Add\n\t2. Subtract\n\t3. Multiply\n\t4. Divide\n");
printf("Enter your choice: ");
scanf("%i",&Choice);
printf("Enter your first number : ");
scanf("%f",&Num1);
printf("Enter your second number : ");
scanf("%f",&Num2);
switch(Choice)
{
case 1: Result = Num1 + Num2;
printf("\n%.2f + %.2f = %.2f\n",Num1,Num2,Result);
break;
case 2: Result = Num1 - Num2;
printf("\n%.2f - %.2f = %.2f\n",Num1,Num2,Result);
break;
case 3: Result = Num1 * Num2;
printf("\n%.2f * %.2f = %.2f\n",Num1,Num2,Result);
break;
case 4: if (Num2 == 0)
printf("\nYou cannot divide by zero!\n");
else
{
Result = Num1 / Num2;
printf("\n%.2f / %.2f = %.2f\n",Num1,Num2,Result);
}
break;
} /* end of case */
printf("\nPress enter to continue");
getch();
return 0;
}

Page 126
Example Program GradCase:
This program inputs a student mark and calculates a grade according to the following scale:
Mark Grade
90-100 A
80-89 B
70-79 C
60-69 D
<=59 F

PseudoCode:
PROGRAM GradCase
INPUT Mark
CASE (Mark/10)
9,10: Grade = 'A'
8: Grade = 'B'
7: Grade = 'C'
6: Grade = 'D'
else: Grade = 'F'
OUTPUT Grade
END GradCase.

Note: The case structure in C cannot have ranges. The integer datatype mark can be divided by 10
to give the various breaks for the grades. If it is not possible to get single values for the case
structure, the nested if structure must be used with ranges in C code.

Page 127
Example C Code GradCase:

/**********************************************************************
* Program | GradCase
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Uses a case structure to calculate a student’s
* | grade using a 5-level bracket on the mark.
*/

#include <stdio.h>
#include <conio.h>

int main (void)


{
int Mark = 0;
int MarkDivTen = 0;
char Grade = 0;

clrscr();
printf(“Enter student mark: “);
scanf("%i",&Mark);
MarkDivTen = Mark / 10; /* no rounding occurs in integer division
*/
switch (MarkDivTen)
{
case 10:
case 9: Grade = 'A';
break;
case 8: Grade = 'B';
break;
case 7: Grade = 'C';
break;
case 6: Grade = 'D';
break;
default: Grade = 'F';
break;
}
printf("The student grade is : %c\n",Grade);

printf("\nPress enter to continue");


getch();
return 0;
}

Page 128
Exercises - Case

For each of the following programs use a case structure where appropriate:
1. provide the Algorithm using pseudocode.
2. provide the C code
(each question is a continuation of previous exercises of the same name eg ANIM3C is a
modification to previous exercises ANIM2):

Exercise 7-1

POST3C:
A program requires the weight of a parcel in Kg and the parcel type(S-surface, C-
courier or E-express) to be entered from the keyboard. The charge is set at $1.50 per
kg. There is a maximum charge of $10 for surface parcels and a maximum charge of $20
for courier and express parcels. There is also an additional surcharge of $8 for courier
parcels and a surcharge of $5 for express parcels. The parcel type and charge is to be
output to the screen.

Exercise 7-2

ANIM3C:
A program accepts the number of hours of the consultation, the animal type (B-bird, C-
cat, D-dog, O-other) and the type of owner (N-normal or F-farmer) from the keyboard.
The consultation fee for a vet is obtained by multiplying the number of hours by the hourly
rate. The hourly rate is set at $20 for birds, $25 for cats, $30 for dogs and $40 for other
animals. There is a 20% discount on the consultation fee for farmers. Output all the inputs
and the consultation fee to the screen.

Exercise 7-3

BANK3C:
A loan officer requires a program to calculate the monthly repayment M on a customer
loan by entering from the keyboard the principal P, the term T of the loan(in years) and
the loan type (C-car, I-investment or S-staff). The monthly repayment is calculated as

M=P(1+RT/100.0)/(12T).
The annual interest rate of R% pa. is set at 10% for car loans, 13% for investment loans
and 8% for staff loans. All inputs and the result is output to the screen.

Page 129
Extra Exercises - Case

Exercise 7-4

Using a case structure write a program which inputs a Distance and outputs a Cost according to the
following table:

Distance Cost
0 to 99 5.00
100 to 299 8.00
300 to 599 10.00
600 to 999 12.00

(Hint: calculate Distance/100 and use this in the switch statement)

Exercise 7-5

Using a case structure write a program which inputs a number and a choice ('A','B','C') where a
choice of

'A' calculates the result of multiplying the number by 10


'B' calculates the result of multiplying the number by 100
'C' calculates the result of multiplying the number by 1000

Output the result to the screen.

Page 130
PROGRAM TESTING
Desk Checking Reviewed

You have already seen the technique of desk checking. Desk checking is extremely important when
it comes to programming. Programmers should check their algorithms and programs before any
programs go into production.

The six stages of program development identified previously are:

1. Problem definition.
2. Development of a solution.
3. Testing of the solution.
4. Coding of the solution.
5. Testing the program.
6. Maintenance and documenting the program.

Two of the stages involve testing: testing of the solution and testing the program. It is generally the
case that logical errors are easier to detect in algorithms than in programs. The two stages of testing
are complementary not alternatives.

It is important to check that the algorithm actually solves the problem and produces the expected
results for given inputs. In addition to the known results that may have been included in the program
specification other test data should be designed to test the logic of the solution.

The steps involved in desk checking an algorithm are:

1. Select several simple sets of valid input data.


2. Record the expected results for each set of test data.
3. Construct the desk check table.
4. Trace each step in the algorithm following the logical program flow through selection and
loop structures.
5. Record the value of any variable as it is changed by a processing step.
6. Repeat the desk check for each set of test data.
7. Compare the results from the desk check with the expected results.
8. If these results do not match, identify the logic error(s) and modify the algorithm. Desk
check the modified algorithm.

By following these steps, the logic of the algorithm becomes clearer to the programmer and helps
with the detection of any logic errors. Ideally, someone other than the programmer should do the
desk checks. The whole idea of a desk check is to find your mistakes and it is amazing how blind
we are to our own mistakes. The author of the algorithm may make the same mistaken assumptions
in the desk check as she/he made when designing the program.

Page 131
Test Data
Since the conclusions derived from a desk check are only as good as the test data, it is necessary to
design comprehensive test data, which will test all possible paths in the algorithm. NS diagrams are
particularly useful for identifying the alternative pathways through an algorithm.

Known Solutions Reviewed

When the problem is specified and the program specification is written, known solutions to the
problem must be developed manually.
This serves several purposes:
1. The person specifying the problem will be clearer in defining the problem if some solutions
must be supplied.
2. Before an algorithm is developed the programmer has a known target to aim for to aid in
clearly understanding the problem.
3. There is some prepared test data to check the algorithm before coding.

Example – Tax 2
Problem:
Find the nett pay for an employee given a tax rate of 10% and the gross pay. For gross pay
in excess of $5,000, the tax is calculated as 10% of the gross pay, which exceeds $5,000
otherwise, the tax is zero.

Pseudocode:
PROGRAM Tax2
DEFINE TAX_RATE = 0.25, BASE=5000
INPUT GrossPay
IF GrossPay > BASE THEN
Tax = TAX_RATE * (GrossPay - BASE)
ELSE
Tax = 0
ENDIF
NettPay = GrossPay - Tax
OUTPUT NettPay
END Tax2

Known Solutions:
From the problem specification we need to develop some known solutions and to desk-test
the algorithm. The analyst or user may have produced the following table:

GrossPay NettPay
$0.00 $0.00
$5000.00 $5000.00
$5001.00 $5000.90
$5500.00 $5450.00
$8685.00 $8316.95
$10000.00 $8500.00

Page 132
Data Driven Testing
Data driven testing assumes that the program is a 'black-box' and ensures that correct OUTPUT
results from all inputs provided. This method ignores the algorithm, and treats it as unimportant.

Advantages:
1. Empirical testing of an algorithm with real data rather than assuming the algorithm is OK
because it 'looks' OK.
2. It can be undertaken by the user of the program.
3. It provides documentary evidence of displayed output that the algorithm is valid.

Disadvantages:
1. The test data used may not be comprehensive enough to detect all the flaws.
2. Correct results can often occur from self-compensating errors.

Logic Driven Testing


Logic driven testing depends on examining the algorithm, or modules of it, to detect flaws in
procedure.

Advantages:
1. A thorough walkthrough using desk checking will often uncover procedural flaws or
weaknesses.
2. Testing by another (independent) programmer can uncover inefficiencies and structural
flaws.

Disadvantages:
1. Test data compiled by the author of the program may avoid an error.
2. The author often carries the same false assumptions or interpretations to the testing phase.

Page 133
Desk Check Table
The desk check table contains:
1. A column for the algorithm statements being traced.
2. A LOGIC / TEST column to record the result of evaluating logical expressions (true or
false).
3. A column for each variable in the algorithm.
4. An OUTPUT column to record values of variables used in PRINT, DISPLAY or WRITE
statements.
Each row of the desk check table shows the result of the algorithm statement on that row.

Example - WageCalc

Problem:

A program is required to calculate a salesperson's weekly wage. The weekly wage is made
up of a base wage of $300 and a 10% bonus for sales of $5000 and over. Sales less than $5000
do not attract a bonus. The user is to enter the salesperson's name and the sales amount; the
program is to display the salesperson's name, bonus and wage.

Pseudocode:
PROGRAM WageCalc
DEFINE CONSTANTS BASIC_WAGE = 300, BONUS_RATE = 0.1,
BONUS_SALES = 5000
INPUT SalespersonID
INPUT SalesAmount
IF SalesAmount >= BONUS_SALES THEN
Bonus = SalesAmount * BONUS_RATE
ELSE
Bonus = 0
ENDIF
WeeklyWage = BASIC_WAGE + Bonus
OUTPUT SalespersonID, Bonus, WeeklyWage
END WageCalc

Page 134
DESK CHECK using test data SalespersonID=1111, SalesAmount = 7000

WageCalc Logical BASIC BONUS Sales Sales Bonus Weekly OUTPUT


WAGE RATE personID Amount Wage
BASIC_WAGE 300
BONUS_RATE 0.1
INPUT SalespersonID 1111
INPUT SalesAmount 7000
IF SalesAmount >= 5000 True
Bonus = SalesAmount * 700
BONUS_RATE
WeeklyWage = 1000
BASIC_WAGE + Bonus

OUTPUT SalespersonID, 1111


Bonus 700
WeeklyWage 1000

Logic Errors detected by Desk Check


Testing is only successful when errors are detected. Sufficient sets of test data should be designed to
test all possible pathways through the program. A series of desk checks that do not detect logic
errors do not mean that logic errors do not exist, only that they have not been detected.

Common Logic Errors detected in Desk Check


The common logic errors that are detected using a desk check include:
1. Instructions that are coded out of sequence.
2. Un-terminated (infinite) loops.
3. Missing code or modules.
4. Misspelled variable names.
5. Incorrect evaluation of the precedence of arithmetic operators.
6. Failure to initialise counters and accumulators.

Page 135
Exercises – If Desk Check

Exercise 7-6

Using the following algorithm (Example Tax2) produce 2 sets of test data to test both Tax
calculations. Produce 2 desk check tables using these 2 sets of test data.

Pseudocode :

PROGRAM Tax2
DEFINE TAX_RATE= 0.1, BASE = 5000
INPUT GrossPay
IF GrossPay > BASE THEN
Tax = TAX_RATE * (GrossPay - BASE)
ELSE
Tax = 0
ENDIF
NettPay = GrossPay - Tax
OUTPUT NettPay
END Tax2

Exercise 7-7
Given the following algorithm, produce 2 sets of test data and 2 desk checks using this test data.
Pseudocode:
PROGRAM Average
INPUT Num1, Num2
Sum=Num1+Num2
Average=Sum
OUTPUT Sum, Average
END Average

You should find that your test data and desk checks do not give the same results. There is an error
in the algorithm. Correct the error in the algorithm and repeat the desk checks.

CHAPTER 7 – SELCTION STRUCTURE REVIEW QUESTIONS


1. List the three relational operators in order of precedence.

2. An if statement always needs an else. True or false?

3. Can an if statement contain another if statement? True or false?

4. Which structures can be used for multiple choices?

5. What structure may be used as an alternative to a nested if structure? What are the restrictions?

Page 136
CHAPTER 8 -
MODULAR PROGRAM DESIGN

Upon successful completion of this chapter you will be able to:

• Write the modular design for a program using pseudocode.

• Draw a structure chart to show the modules used in a program.

Summary of new terms:

Modular design - the solution to a program is broken up into smaller tasks called modules.
Structure chart – diagram that shows each of the modules in a box and the hierarchy of the
modules called.
Scope of a variable - is the part of the program where a variable can be used.
Local variables - are defined inside a function and are accessible only within that function.

Page 137
OVERVIEW
As programs become larger and more complex, it becomes more difficult to keep the whole
program in mind at the same time. Long programs, extending over several screens or printed pages,
are difficult for readers to grasp.

The solution to this problem is to use modular program design, where the program is broken up into
modules. Each module performs a sub-task of the overall problem, and is simple enough to
understand easily. The overall work of the program is then done by calling on the modules
appropriately. This is shown graphically by using a Structure Chart.

In C, modular programming is achieved by using the function facility. Each module is implemented
as a function. Each function is relatively self-contained, and communication between the modules is
strictly defined. This prevents any unseen interference between the behaviour of the modules.
Modules communicate by means of parameters, which are values passed from the calling module
to the called module.

WHY USE M ODULAR DESIGN?


Problems with program complexity
The difficulty of designing, debugging and maintaining a program increases with its size and
complexity. The more lines of code, the more variables there are, the more these is to go wrong,
and the harder it is to keep a picture of the program in your mind.

The solution to this program is to break larger programs up into smaller modules, so that each
module can be grasped. In really large programs, there may be a hierarchy of modules as the first
group of modules is further broken up.

Consider, for example, a really large application, such as Microsoft Word. The program for this
contains millions of lines of code. If it was written as a single mass without any structure, then its
development maintenance would be very difficult. But a modular approach makes the task more
digestible. For example, the tasks performed by Word consist mainly of responding to the user’s
menu selections. So the task is naturally modular. We could show it as something like this:

Microsoft Word (overall program)


Respond to File>New menu selection
Respond to File>Open menu selection
Respond to File>Close menu selection

Dealing with the individual modules is easier than dealing with the task as a whole. The modules are
self-contained, and can be written largely independently of one another. The modules, being smaller,
are simpler and easier to deal with. But they may not be small enough.

Page 138
For example, we could further subdivide the File>Open module in the Word scheme:

Microsoft Word (overall program)


Respond to File>New menu selection
Respond to File>Open menu selection
Display Open File dialog box
Read the selected document
Open a document window
Display the document in the new window
Respond to File>Close menu selection

In some cases, still further breaking down will be required.

For our present purposes, it will be enough to consider only one level of modules. We shall consider
breaking relatively short programs into modules.

Module design
Breaking a program up into modules is not just a matter of cutting it up randomly. You do not, for
example, break the program at every tenth line, and package the sections up into modules. The
process needs to be done logically, so that it enhances the structure of the program and makes it
easier to write and to follow.

Designing the modules for a program should have the following objectives:

• Each module should perform a distinct and easily defined task.

• The communication needed between the modules should be minimised.

• Processing that is often repeated should be put in a module.

The first two are related. If each module has a definite task to do, then the modules will be naturally
self-contained, and there will not be a need for much communication between them.

The reasons for the third objective may not be obvious at first. If you are performing the same
process at various points in the program, it makes sense to code the process just once in a module,
and call the module as required. That way, you only need to get the code right once, and the
process is guaranteed to work consistently. Another advantage is that, if the process ever needs to
change, you only need to find and change one piece of code, rather than search for all the places in
the program where you coded that process. It’s a bit like the reasons you use symbolic constants
rather than literals.

Look again at the module proposals for the Word example above. Do they achieve the stated
objectives for modules?

You should try to use this modular approach, that is, functions, in all of the programming you do
from now on. Of course until some larger projects are tackled, such as your major assignment,

Page 139
some of the functions you write may be small and trivial (as is the CalcTaxAmount function in the
previous examples). Nevertheless the benefits of a modular approach are enormous so it is good to
get into the practice of using modules as much as possible as soon as possible.

USING M ODULES
Modules in Pseudocode
Calling a module:
DO ModuleName

Labelling a module:
MODULE ModuleName
statements
...
...
END ModuleName

Naming a Module
Some useful guidelines to help in naming modules:
• Use a verb and a noun to describe what task is being done
• Use a combination of upper and lower case characters to highlight keywords.

Generally a problem can be broken up into the input, processing and output tasks, for example:

PROGRAM Mainline
DO GetInputs
DO ProcessResults
DO OutputDetails
END Mainline.

Modular Design Desk Check


Desk checking in a modular design becomes easier since you only need to check one module at a
time. The variables that change due to the processing within the module are the only variables that
need to be traced. The variables that are to be used in the calculation may have been obtained from
previous modules and can be assumed to carry on the value used within the desk check of that
previous module. The mainline module only needs to be traced through to test that each module is
called correctly and if there is a looping structure it must also test the loop is correctly executed.

Page 140
Example – Modular Design
Consider the Tax3Nest problem presented previously.

Given the following tax scale


GrossPay TaxRate
0 - 5000 0
5001-20000 25%on excess over 5000
> 20000 tax on first 20,000+40% on excess over 20000
calculate and output the Nett pay given a Gross pay.

The PseudoCode presented previously:


PROGRAM Tax3Nest
DEFINE BASE1=5000, BASE2=20000, RATE1=0.25, RATE2=0.4
INPUT GrossPay
IF GrossPay <= BASE1 THEN
Tax = 0
ELSE
IF GrossPay <= BASE2 THEN
Tax = RATE1*(GrossPay - BASE1)
ELSE
Tax = RATE2*(GrossPay - BASE2) + RATE1*(BASE2-BASE1)
ENDIF
ENDIF
NettPay = GrossPay - Tax
OUTPUT NettPay
END Tax3Nest

This program is not really long or complex enough to need modularisation, but let’s see how it
would work anyway.

The program specification already gives some clues about how the modules could be set up. In the
“major tasks” section, the operation of the program has already been broken down, basically into
input, processing and output. These could each be planned as a module. Thus there would be three
modules:

1. Get the data from the user


2. Calculate the result
3. Display the result

Page 141
Structure Charts
Once the modules have been defined they are represented graphically in a diagram called a structure
chart (or hierarchy chart). The structure chart shows each of the modules in a box and the hierarchy
of the modules called. The main module, or mainline, appears at the top of the structure. The
Structure Chart for the Tax3M problem would look as follows:

Calculate NettPay

Input Gross Pay Calc Nett Pay Output NettPay

The mainline of the pseudocode would appear as module calls for each of the above tasks that need
to be done.

The PseudoCode for the main program:


PROGRAM Tax3M
DEFINE BASE1=5000, BASE2=20000, RATE1=0.25, RATE2=0.4
DO InputGrossPay
DO CalculateNettPay
DO OutputNettPay
END Tax3M

The pseudocode for each module needs to be written as follows:

MODULE InputGrossPay
INPUT GrossPay
END InputGrossPay

MODULE CalcNettPay
IF GrossPay <= BASE1 THEN
Tax = 0
ELSE
IF GrossPay <= BASE2 THEN
Tax = RATE1*(GrossPay - BASE1)
ELSE
Tax = RATE2*(GrossPay - BASE2) + RATE1*(BASE2-BASE1)
ENDIF
ENDIF
NettPay = GrossPay - Tax
END CalcNettPay

MODULE OutputNettPay
OUTPUT NettPay
END OutputNettPay

Page 142
C Code
/********************************************************************
* Program | Tax3Mod
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Calculates tax from gross pay, using three tax
* | brackets: <$5,000, $5,001 to $20,000 and >$20,000.
********************************************************************
*/

#include <stdio.h>
#include <conio.h>

#define BASE1 5000


#define BASE2 20000
#define RATE1 0.25
#define RATE2 0.40

/* prototypes */
float InputGrossPay(void);
float CalcNettPay(float TaxableIncome);
void OutputNettPay(float NettPay);

int main (void)


{
float NettPay=0;
float GrossPay=0;

GrossPay = InputGrossPay();
NettPay = CalcNettPay(GrossPay);
OutputNettPay(NettPay);
return 0;
}

/*********** Functions ************/


/********************************************************************
float InputGrossPay(void)
{
float GrossPay = 0.0;
clrscr();
printf("Enter the Gross Pay $");
scanf("%f",&GrossPay);
return GrossPay;
}
/* end of InputGrossPay */
/********************************************************************
float CalcNettPay(float TaxableIncome)
{
float Tax = 0.0;
float NettPay = 0.0;

if (TaxableIncome <= BASE1)


Tax = 0;
else
if (TaxableIncome <= BASE2)
Tax=RATE1*(TaxableIncome - BASE1);
else

Page 143
Tax=RATE2*(TaxableIncome-BASE2) + RATE1*(BASE2-BASE1);
NettPay = TaxableIncome - Tax;
return NettPay;
}
/* End of CalcNettPay */
/********************************************************************
void OutputNettPay(float NettPay)
{
printf("The Nett Pay is $ %.2f\n",NettPay);
printf("Press enter to continue");
getch();
return;
}
/* End of OutputNettPay */
/********************************************************************

Libraries of modules
Modular programming not only helps you to program in a more systematic and less error-prone
way. It also allows the use of libraries of modules that have already been written and compiled, and
made available for your use. This can save a great deal of work, and the modules provided can
reasonably be expected to be error-free.

All the modules used by a program need not be used within that program. Programs can use
separately compiled modules. The compiler needs to know enough about the modules to check that
you are using them properly. After compilation, the linker will link the previously compiled modules
to your newly compiled program.

In C programs, the #include directives you have used give the compiler access to information about
the library modules you want to use. The stdio library, for example, contains modules for doing
basic input and output. You have already used several of these: printf, scanf and readch.

ANSI C comes with a large library of modules that perform many useful functions. You can use any
of these in your programs. All you need to know is what modules exist, and how to use them. The
necessary information is usually provided through the on-line help system of your C IDE.

The use of other people’s modules is also an important aspect of large team programming projects.

SCOPE AND LIFE OF VARIABLES


Scope of variables
The scope of a variable is the part of the program where it can be used.

All the variables you have seen so far are local variables. They are defined inside a function
(usually function main) and they are accessible only within that function. They are not accessible
from other functions that may be defined in the program.

In the program immediately above, for example, the variable answer is defined in the function
Querty, and it is accessible only from there. Statements in function main would not be allowed to use
this variable. Similarly, the Query procedure cannot access any of the variables defined in main.

Page 144
It is possible to have variables with the same name declared in two different functions. They will be
completely separate variables that have nothing to do with each other. When the name is used, can
be no confusion about which variable it refers to – it is always the variable declared in the current
(local) function.

There is a good reason for this restriction on the scope of local variables. If a variable is “private” to
a function, that is, accessible only to the function, then if the variable misbehaves, we need look only
in one function for the cause. We do not have to worry about undue interference from somewhere
else in the program.

Sometimes it is convenient to have variables that can be accessed from anywhere in the program,
just as symbolic constants can be. Such variables are called global variables, and they are
declared outside the functions, usually just before the beginning of function main.

Using global variables is not a good idea if you want to take full advantage of modular programming.
The idea of modular programming is to have all communication between modules explicitly defined
in the heading of each module. Global variables can bypass this useful discipline.

Life of variables
Remember that a variable is just a name given to an area of memory. The life of a variable refers to
when this memory needs to exist. If a local variable can only be used within its function is executing,
then the space used by that variable need only be allocated when the function is called, and it can be
released when the function returns.

For variables declared in main, memory is allocated when main is called (when the program starts
running) and is released only when main finished (when the program finishes). In effect, they are
there all the time. Global variables behave in a similar way.

For local variables declared in other functions, space is allocated whenever the function is called,
and released when the function returns. Because of this, local variables do not necessarily retain their
values between one call to a function and the next. A different area of memory may be allocated,
with different initial contents. For this reason, it is good practice always to initialise the values of local
variables in your functions.

Scope of functions
Access to functions is also restricted within a program. Functions can only be used if their
prototypes have been seen by the compiler. The prototype of a function is a line of code giving the
name and type of the function, and the name and type of its parameters. Without this information,
the C compiler cannot check that you are calling the function correctly.

It is good practice to list, somewhere near the top of your program, prototypes of all the functions
that are defined in it (except for main, which has a pre-defined prototype). You can then use any of
your functions from anywhere in the program.

The header files that you include at the top of your program (for example, stdio.h and conio.h)
consist mainly of prototypes of system functions such as printf and scanf. With the header files

Page 145
included, you can use the functions. It’s difficult to write a useful C program without including these
header files.

Page 146
Exercises – Modular Design
Write the modular pseudocode solution for the following exercises.
Provide a structure chart for each program.

Exercise 8-1

POST4M: Write modules to input the weight, input the parcel type, calculate the postage charge
and output the postage details from POST3C:
A program requires the weight of a parcel in Kg and the parcel type(S-surface, C-
courier or E-express) to be entered from the keyboard. The charge is set at $1.50 per
kg. There is a maximum charge of $10 for surface parcels and a maximum charge of
$20 for courier and express parcels. There is also an additional surcharge of $8 for
courier parcels and a surcharge of $5 for express parcels. The parcel type and charge
is to be output to the screen.

Exercise 8-2

ANIM4M: Write modules to input hours, input animal type, input owner type, set hourly rate,
calculate the consultation fee and output the consultation fee from ANIM3C:
A program accepts the number of hours of the consultation, the animal type (B-bird, C-
cat, D-dog, O-other) and the type of owner (N-normal or F-farmer) from the
keyboard. The consultation fee for a vet is obtained by multiplying the number of hours
by the hourly rate. The hourly rate is set at $20 for birds, $25 for cats, $30 for dogs
and $40 for other animals. There is a 20% discount on the consultation fee for farmers.
Output all the inputs and the consultation fee to the screen.

Exercise 8-3

BANK4M: Write modules to input P, T and loan type, set the interest rate calculate M and output
the inputs and monthly repayment from BANK3C:
A loan officer requires a program to calculate the monthly repayment M on a customer
loan by entering from the keyboard the principal P, the term T of the loan(in years) and
the loan type (C-car, I-investment or S-staff). The monthly repayment is calculated as
M=P(1+RT/100.0)/(12T).
The annual interest rate of R% pa. is set at 10% for car loans, 13% for investment
loans and 8% for staff loans. All inputs and the result is output to the screen.

Page 147
CHAPTER 9 -
FUNCTIONS

Upon successful completion of this chapter you will be able to:

• Declare a function in C

• Write a function in C using parameters and a return type

• Prototype a function in C code

Summary of new terms:

Parameter - the data that is passed to a function.


Return Type – the data type of the value that is being returned from the function.
Prototype - before a function can be used in a program, the compiler needs to know about the
name, the data type of each parameter and return type of the function.
Void – used when there are no parameters to be passed to a function or when there is no return
type.
Global variable – a variable that is defined outside a function and can be shared by all the functions
in the program.

Page 148
OVERVIEW
As we saw in the last chapter, when writing a computer program to solve a problem it is helpful to
take a step-wise refinement, modular approach. In C we implement this approach by using
functions. Functions are modules of code. Their use fits in well with structured programming. Each
function can be separately coded and tested. Once a function is written, (and tested), it can be used
over and over again.

By using and creating functions that are specific to a task, you can program good modular designed
software. This enhances the readability and maintainability of software.

In order to use functions in your C programming, you will need to learn how to declare, write and
use them. You will need to know how functions use parameters and return values to communicate
with each other. You will also need to learn about function prototyping.

USING FUNCTIONS IN C
As problems start to become larger it is helpful to take a step-wise refinement, modular approach to
solve them. It is often difficult to solve a large problem as one huge problem. The problem should
be broken down into smaller, easier to solve tasks or modules. In C code these modules of code
are called functions. Their use fits in well with structured programming. Each function can be
separately coded and tested. Once a function is written it can be used over and over again. By using
and creating functions that are specific to a task, you can program good modular designed software.
This enhances the readability and maintainability of software.

To begin, it is useful to consider how functions communicate. Remember that the variables declared
inside a function are private to that function; they cannot be accessed or changed from anywhere
outside the function. Such local variables, therefore, are no use for communication. We need other
mechanisms to pass variables between functions. There are two important ones:

• Parameters (also called arguments)

• Return value (only one value can be returned in C)

Functions and Parameters

Functions usually require some data to work with. This information is passed to the function via
parameters (also called arguments). All functions must be declared with a parameters list. Where no
information is passed, the parameters list is empty. The parameters list must specify the data type of
each parameter. For now, we shall regard parameters as a way providing information to the function
when it is called.

Return value

What if a function needs to return information to the calling function? This is a common situation, but
in general, a function can return only one value, and it must be the same datatype as the function.
The returned value can be any expression of this type.

Page 149
Declaring a Function

Declaring functions is very similar to declaring variables, but they require 3 parts:

ReturnDataType FunctionName( formal argument list )

1. ReturnDataType:
Functions are typed in much the same way as normal variables. The return type dictates what
data can be returned by the function. A function can only ever return one value. These can be of
the data types we have covered so far: int, char or float.

2. FunctionName:
The function name can be anything you like. The function name must abide by the same rules
normal variables follow. It should be descriptive of the task the function performs. We suggest
using a verb and a noun to describe the task. For example, if you are writing a function to
calculate the sum of two numbers you could name the function CalcSum, or if you were writing
a function to output customer details you could name the function OutputCustDetails.

3. Formal parameter(argument) list:


The parameter list describes what type of variables is accepted as input to the function. Each
parameter must define the variable data type and its name, if more than one parameter is used,
each must be separated by a comma. Only variables that are needed for the processing within
the function need to be passed into the function.

Example CubeNum – return datatype and parameter list

Write an integer function called CubeNum that accepts an integer Number as an argument and
returns the cube of that argument.

int CubeNum(int Number)


{
int Answer = 0;
Answer = Number * Number * Number;
return Answer;
}

This example has both a return type and parameter list. An integer variable (Answer) is being
returned, so the function is defined with the int datatype as int CubeNum(int Number) and the last
line in the function is return Answer where Answer is an integer variable. The datatype of the
function must match the datatype of the return variable.

Example Output Function – parameter list and no return datatype

If the function does not return a value the void keyword should be used as the return data type and
the last line in the function will be return (without any variable). This is particularly done in the case
of outputting details. Since this type of function, which is purely for output, would mainly consist of

Page 150
printf statements and there would be no calculation to be returned. The word return must be used.
For example, write a function to output the number of items sold and the cost:

void OutputCustomerDetails(float Cost, int NumSold)


{
printf(“\n%i items were sold costing $%.2f”,Cost,NumSold);
return;
}

Example Input Function – return datatype and no parameter list

If the function does not need any arguments the void keyword should be used in the formal
parameter list. This is common for input functions that have the task of asking for input, not sending
any variables into the function and returning the value that was input. For example

int InputNumber(void)
{
int Number = 0;
printf(“Enter a whole number: “);
scanf(“%i”,&Number);
return Number;
}

Calling a Function

When you call the function you have written, you use the function name and the variables you want
to pass to the function.

Assume that Number and NumCubed are variables of type int.

NumCubed = CubeNum(Number);

The function CubeNum is passed a copy of the argument value (value of Number which has
probably been input into the program prior to calling the function). It uses this as the value of the
variable Number in the function.

After calculating the cube, the answer is returned to the calling function. The value that is returned is
saved in the calling function in the variable NumCubed in the above example. If you do not assign
the returned value to a variable, it will be lost.

Examples of function calls

• NumCubed = CubeNum(Number);
(The function CubeNum is called and is passed the value of Number which is cubed and
returned to be stored in NumCubed)

• NumCubed = CubeNum(10);
(The function CubeNum is called and is passed the value 10 which is cubed and returned to
be stored in NumCubed The value of NumCubed will be 1000.)

Page 151
• printf("The cube of 10 is %i", CubeNum(10));
(This statement contains two function calls. One of the parameters of the printf function is a
call to the CubeNum function which returns the integer 1000.) The output will be:

The cube of 10 is 1000

• Ans = Total + CubeNum(Num);


(Here the function call is part of an expression. The value of Ans will be calculated as Total
plus the cube of Num.)

• CubeNum(Num);
(Here the function call is a statement in its own right. This is legal but useless, because the
result is not used by the calling function, it is not stored as a variable and is just discarded.)

Writing Functions.

A function is a block of code. Information is passed to the function via its arguments. Each argument
has a data type, and is given a name that it is known by in the function. You can declare more
variables in the function. These are known only to the function they are declared in. If you wish to
return a value to the calling function, you use the return statement. You can only return one value to
the calling function in this way. The data type of the returned value must match the data type
specified in the function declaration.

The function CubeNum is passed an integer variable, and returns an integer variable.

int CubeNum(int Number)


{
int Answer = 0;
Answer = Number * Number * Number;
return Answer;
}

To save creating an extra variable to store the answer, this could have been coded as

int CubeNum(int Number)


{
return Number * Number * Number;
}

Function Prototypes

Before you can use a function in a program, the compiler needs to know about the function.
Specifically, it needs to know the name and return type of the function, and the data type of each
parameter.

This information is, of course, provided by the function declaration. You can therefore use a function
anywhere in a program after its declaration. But this means that you need to order your function
declarations very carefully, so that every function is declared before it is used. This may not always

Page 152
be possible. You may quite legitimately have a program where two functions call each other, and
then a suitable ordering is not possible.

This ordering requirement is usually overcome by declaring a prototype for all functions before any
coding in the program.

To prototype a function, you copy the function definition line to the top part of your source file
(usually after your #include and #define's), and place a semicolon ; at the end of it. You may leave
the variable names, (or you may remove the variable names and just leave the variable types). This
declares to the compiler, the type of the arguments and the return value from your function. When
your program is compiled, your function calls are checked against the prototype, and if the types do
not match, a compiler error is generated. You should prototype every function you write.

Once you have prototypes, it is usual to have the coding for main first in your source code.

In the above CubeNum example, the prototype of the function would be:

int CubeNum(int Number);

Local Variables.

All variables declared within a function are considered local variables and cannot be used by any
other function. They are allocated memory when the function is called. The area of memory used to
handle local variables and all other details of functions is called the run-time stack. This means, each
time the function is called, all variables are regenerated and it is not possible to access the previously
assigned values.

Example – Local Variables

/******************************************************
* using local variables *
* Count is local to the function Counter *
* Increment is local to the function main *
******************************************************/
#include <stdio.h>

/*** Declare function prototype here ***/


void Counter(void);

int main(void)
{
int Increment = 0;
while (Increment < 100)
{
Counter();
Increment = Increment + 1;
}
getch();
return 0;
}

void Counter(void)

Page 153
{
int Count = 0;
Count = Count + 1;
printf("count = %i\n", Count);
return;
}

This program will display, count = 1, 100 times.

Page 154
PARAMETER PASSING
When a function is declared, all the valid arguments are defined and given names. Because the
arguments are treated in exactly the same way as local variables, the names chosen may be any valid
variable name. Further, they may be the same name as a variable in another function.

The variables defined in a function, including the formal arguments, are only visible by that function
and so will not alter the value of any other variable in the program.

When the function is called, a copy of the actual arguments is passed to the function.

Example – parameter passing

/******************************************************
* a formal argument is local to the function it is *
* declared in *
******************************************************/
#include <stdio.h>

void Temp(int Num); /* prototype */

int main(void)
{
int Num = 20;
printf("\n\nIn main, num = %i\n", Num);
Temp(Num);
printf("In main, num = %i\n", Num);
getch();
return 0;
}

void Temp(int Num)


{
Num = Num + 10;
printf("In temp, num = %i\n", Num);
return;
}

The output from these functions would be

In main, num = 20
In temp, num = 30
In main, num = 20

An actual argument is the value actually passed to a function.


For example, if the call to Temp, Temp(1*3 + 3*4), was made the actual argument would be, 15 ,
ie 1*3 + 3*4.
The formal argument would be Num, as defined in the function header.

Page 155
Returning A Value

To correct the program in Example – parameter passing, you must return the value of Num to the
function main.

This will give the following results

In main, num = 20
In temp, num = 30
In main, num = 30

Example – return values

/********************************************************
* a formal argument is local to the function it is *
* declared in one value can be returned with a return *
* statement *
********************************************************/
#include <stdio.h>

int Temp(int Num); /* prototype */

int main(void)
{
int Num = 20;
printf("\n\nIn main, num = %i\n", Num);
Num = Temp(Num);
printf("In main, num = %i\n", Num);
getch();
return 0;
}

int Temp(int Num)


{
Num = Num + 10;
printf("In temp, num = %i\n", Num);
return Num;
}

Global Variables

All the variables you have seen so far have been local variables. They are defined inside a function,
and are private to that function. They cannot be used or altered by any other function.

It is also possible to define variables in C outside a function. Such variables are called global
variables, and are shared by all the functions in the program following their definition.

Page 156
Here is an example of a program using global variables.

Example – Global Variables

/******************************************************/
* using global variables *
* Num1 is visible in all functions, *
* Num2 is visible in Func2 and main only *
******************************************************/
#include <stdio.h>

int Num1 = 10;


int Num2 = 18;

void Function1(void); /* prototype */


void Function2(void);

int main(void)
{
printf("\n\nAt start of program, num1 = %i, num2 = %i\n",Num1, Num2);
while (Num2 < 20)
{
Function1();
Function2();
}
getch();
return 0;
}

void Function1(void)
{
printf("In function1, num1 = %i\n",Num1);
Num1 = Num1 + 1;
return;
}

void Function2(void)
{
printf("In function2, num1 = %i\n",Num1);
printf("In function2, num2 = %i\n",Num2);
Num1 = Num1 + 1;
Num2 = Num2 + 1;
return;
}

The results obtained are


At start of program, num1 = 10, num2 = 18
In function1, num1 = 10
In function2, num1 = 11
In function2, num2 = 18
In function1, num1 = 12
In function2, num1 = 13
In function2, num2 = 19

Page 157
Why shouldn’t we use global variables?

Global variables can be used to share variables between functions. Using global variables is easier
than passing parameters. However C programmers seldom use global variables because of possible
conflict with variable names causing difficult to find errors. This is particularly true when developing
software in programming teams. Here is an example.

Example – global problems

/******************************************************
* using local and global variables *
* function2 uses local version of Num1, *
* rather than the global variable Num1 *
******************************************************/
#include <stdio.h>

int Num1 = 10;


int Num2 = 18;

void Function1(void);
void Function2(void);

int main(void)
{
printf("\n\nAt start of program, num1 = %i, num2 = %i \n", Num1,
Num2);
while (Num2 < 20)
{
Function1();
Function2();
}
getch();
return 0;
}

void Function1(void)
{
printf("In function1, num1 = %i\n",Num1);
Num1 = Num1 + 1;
return;
}
void Function2(void)
{
int Num1 = 999;

printf("In function2, num1 = %i\n",Num1);


printf("In function2, num2 = %i\n",Num2);
Num1 = Num1 + 1;
Num2 = Num2 + 1;
return;
}

The results obtained are


At start of program, num1 = 10, num2 = 18

Page 158
In function1, num1 = 10
In function2, num1 = 999
In function2, num2 = 18
In function1, num1 = 11
In function2, num1 = 999
In function2, num2 = 19

Unless specifically stated otherwise, global variables are NOT used in this book !!!!!

Page 159
Exercise 9-1

Use the on-line help system of your C IDE to look up functions to perform the following tasks.

• Calculate the square root of a number.

• Generate a random number.

• Get today’s date.

You do not need to understand the details of the information just yet.
Do you need to add any extra #include directives to your program to use these facilities?

Exercise 9-2

What is the output for the following C code:

#include <stdio.h>
#include <conio.h>

void DoSomething(int Num2);

int main(void)
{
int Num1 = 0;
int Num2 = 0;
printf("\nInside main: Num1 = %i Num2 = %i", Num1, Num2);
DoSomething(Num2);
printf("\nInside main: Num1 = %i Num2 = %i", Num1, Num2);
return 0;
}

void DoSomething(int Num2)


{ int Num1 = 11;
Num2 = Num2 + 5;
printf("\nInside DoSomething: Num1 = %i Num2 = %i", Num1, Num2);
return;
}

Page 160
Exercise 9-3

What is the output for the following C code:

#include <stdio.h>
#include <conio.h>

int DoSomething(int Num1);

int main(void)
{
int Num1 = 1;
int Num2 = 1;

printf("\nInside main: Num1 = %i Num2 = %i", Num1, Num2);


Num1 = DoSomething(Num1);
printf("\nInside main: Num1 = %i Num2 = %i", Num1, Num2);
return 0;
}

int DoSomething(int Num1)


{ int Num2 = 0;
Num1 = Num1 + 2;
printf("\nInside DoSomething: Num1 = %i Num2 = %i", Num1, Num2);
return Num1;
}

Page 161
Exercises - Functions
Modify the C code to include a function to perform the inputs, calculations and outputs in the
following exercises.

Exercise 9-4

POST4M:
Write functions to input the weight, input the parcel type, calculate the postage charge and output
the postage details from POST3C

POST3C: A program requires the weight of a parcel in Kg and the parcel type(S-surface, C-
courier or E-express) to be entered from the keyboard. The charge is set at $1.50 per kg. There is
a maximum charge of $10 for surface parcels and a maximum charge of $20 for courier and express
parcels. There is also an additional surcharge of $8 for courier parcels and a surcharge of $5 for
express parcels. The parcel type and charge is to be output to the screen.

Exercise 9-5

ANIM4M:
Write functions to input hours, input animal type, input owner type, set hourly rate, calculate the
consultation fee and output the consultation fee from ANIM3C.

ANIM3C:A program accepts the number of hours of the consultation, the animal type (B-bird, C-
cat, D-dog, O-other) and the type of owner (N-normal or F-farmer) from the keyboard. The
consultation fee for a vet is obtained by multiplying the number of hours by the hourly rate. The
hourly rate is set at $20 for birds, $25 for cats, $30 for dogs and $40 for other animals. There is a
20% discount on the consultation fee for farmers. Output all the inputs and the consultation fee to
the screen.

Exercise 9-6

BANK4M:
Write functions to input P, T and loan type, set the interest rate calculate M and output the inputs
and monthly repayment from BANK3C.

BANK3C:A loan officer requires a program to calculate the monthly repayment M on a customer
loan by entering from the keyboard the principal P, the term T of the loan(in years) and the loan type
(C-car, I-investment or S-staff). The monthly repayment is calculated as
M=P(1+RT/100.0)/(12T).
The annual interest rate of R% pa. is set at 10% for car loans, 13% for investment loans and 8% for
staff loans. All inputs and the result is output to the screen.

Page 162
CASE STUDY - PFEECAL4
Modularise the program from PFeeCal3 by taking some of the code out of main(void) and putting it
into separate modules. The modules should do the following:
• Get the customer ID (just a very small module at this stage)
• Get the customer type (another small module)
• Get the number of days required for a given professional type.
• Output the details for the customer

PFeeCal3:
Write a program that will request the following information from a user:
An ID number (4 digit integer)
The type of customer (‘R’ regular or ‘C’ casual)
The number of required networker days.
The number of required programmer days.
The number of required office administrator days.

The following table shows the fees that are charged:


Professional Charge per day for a
Casual Customer
A Network professional (N) $115.00
An Office administrator (O) $120.00
A Programmer (P) $100.00

A regular customer will receive 5% discount on the fee. Your program should calculate the
associated costs for Networkers, Programmers and Office workers and total cost and output these
costs in a table to the screen.

CHAPTER 9 – REVIEW QUESTIONS


1. Give two reasons why modular design should be used when designing a program?

2. What is the name of the chart that shows the modules used in a program?

3. The datatype of the function must be the same as the datatype of the variable being returned
from the function. True or false?

4. A function can return how many values?

Page 163
CHAPTER 10 –
ITERATION: THE WHILE LOOP

Upon successful completion of this chapter you will be able to:

• Write the pseudocode for the while loop structure

• Use the while statement in C code programs to solve an iteration structured program

• Use while loops for data validation

• Use while loops for sentinel controlled processing

• Use nested loops

• Debug common logic errors in while loops

Summary of new terms:

WHILE loop - a pre-test loop where the condition for terminating the loop is tested at the
beginning of the set of tasks to be repeated.
Data validation – continually prompting the user for data until a valid data is entered.
Sentinel – a value chosen to end loop processing.
Sentinel controlled while loop - where processing a program consists of continually entering
values until a sentinel is reached.
Nested loops - to have one loop inside another.

Page 164
OVERVIEW
A specific task in a program often needs to be performed a number of times. There are control
structures available which allow the repeated execution of a group of statements without the
necessity to repeat the statements themselves in the program. The control structure that allows the
same process to be executed over and over again is called looping, repetition or iteration.

There are three control structures for iteration; the WHILE loop, the REPEAT...UNTIL loop and
the FOR loop. These three structures are also referred to as the pre-test loop, the post-test loop
and the fixed loop respectively.

This chapter looks at iteration with pre-test loops, using the while statement.

TYPES OF ITERATION
C provides three types of iteration, which can be described as pre-test loop, the post-test loop, and
the counted loop. More commonly, programmers refer to them as while, repeat and for loops, after
the statements used for them in most programming languages.

The basic operation of these types of iteration is described in the following pseudocode section.

Iteration in Pseudocode

Structure Pseudocode Use


Pre-test Loop WHILE condition A series of task(s) is to be
(or WHILE loop) statement(s) repeated while a condition
ENDWHILE is true. The loop terminates
when the condition is false.
The loop will execute none
or more times.

Post-test Loop REPEAT A series of task(s) is to be


(or REPEAT loop) statement(s) repeated while a condition
UNTIL condition is false. The loop terminates
when the condition is true.
The loop will execute one
or more times.

Fixed Loop FOR variable = val1 TO val2 A series of task(s) is to be


(or FOR loop) repeated a fixed number of
statement(s) times. The loop terminates
ENDFOR when the variable reaches
val2. The loop should
execute one or more times
(val1 <=val2)

Page 165
THE WHILE LOOP
The WHILE loop is referred to as a pre-test loop because the condition for terminating the loop is
tested at the beginning of the set of tasks to be repeated. If the condition evaluates to TRUE the
tasks are executed; if the condition evaluates to FALSE the loop is terminated. If the condition is
false to begin with, the loop is not executed at all.

Pseudocode
The general format for a WHILE loop in pseudocode is:

WHILE condition
statement(s)
ENDWHILE

C Code

The while statement is used to repeat one or more statements while the condition in the while
statement is true. The compound while statement consists of:-

1. The control statement "while".


2. The condition statement in brackets eg. (Hours <= 12).
3. An open curly bracket, {
4. The program statement(s) each followed by a semi-colon.
5. A closed curly bracket, }

An example is shown below:-

while (DaysCount < 30)


{
DaysCount = DaysCount + 1;
Hours = Hours + 8;
}

NOTE: DO NOT place a semicolon at the end of the while statement


while (DaysCount < 30);
This may result in an infinite loop!

Page 166
DATA VALIDATION
A typical use of the while loop is to get valid data. Usually data that the program uses in its
processing has restrictions and needs to be validated before continuing on with the program. For
example a person’s age should be greater than zero. A while loop can be used to enforce such rules:

Example Age – data validation

int Age;
printf("Enter your age (in years) : ");
scanf("%i",&Age);
while (Age < 0)
{
printf("You have entered a negative number.\n");
printf("Please re-enter your age (in years) : ");
scanf("%i",&Age);
}

If an acceptable age is entered immediately, the body of the loop is never executed. If the initial age
is negative, the loop will go on executing until a positive age is entered.

Example Age2 – data validation

An extension of this problem is to include an upper limit on the age, for example the age must be
<130. The age should not be accepted when it is less than zero or when it is greater than 130. The
code above will be rewritten as:

int Age;
printf("Enter your age (in years 0-130) : ");
scanf("%i",&Age);
while (Age < 0 || Age >130)
{
printf("You have entered an invalid age.\n");
printf("Please re-enter your age (in years 0-130) : ");
scanf("%i",&Age);
}

In summary data validation steps can be summarised as:


INPUT Data
WHILE Data incorrect
OUTPUT error message
INPUT Data
ENDWHILE

The testing condition of the while loop can also be written another way:
WHILE NOT(Data correct)
This logical expression will give the same result as
WHILE Data incorrect

Consider the above extension of validating the age. The logical expression to get “Data incorrect”
will give the same result as the logical expression to get “NOT(Data correct)”.

Page 167
The logical expression for Data incorrect was used above:
while (Age < 0 || Age >130)

This is equivalent to
while !(Age >= 0 && Age <= 130)

Use a desk check to confirm the results are correct in both cases:

Desk Check1 for input 1, 150, 25.


Statement Logical Age
INPUT Age -1
WHILE (Age < 0 || Age >130) True
INPUT Age 150
WHILE (Age < 0 || Age >130) True
INPUT Age 25
WHILE (Age < 0 || Age >130) False
Conclusion: This has resulted in obtaining a valid age.

Desk Check2 for input 1, 150, 25.


Statement Logical Age
INPUT Age -1
WHILE NOT(Age>=0 AND Age<=30) True
INPUT Age 150
WHILE NOT(Age>=0 AND Age<=30) True
INPUT Age 25
WHILE NOT(Age>=0 AND Age<=30) False
Conclusion: This has resulted in obtaining a valid age.

Example Continue – data validation


Another common example of data validation is to input and validate a user request whether to
continue processing or not. The code to input and validate a variable Continue (‘Y’ or ‘N’) is as
follows:

char Continue = ‘ ‘;
printf("Do you want to continue (enter Y or N) : ");
fflush(stdin);
scanf("%c",&Continue);
Continue = toupper(Continue);
while (Continue != ‘Y’ && Continue != ‘N’)
{
printf("You have entered an invalid entry.\n");
printf("Do you want to continue (enter Y or N) : ");
fflush(stdin);
scanf("%c",&Continue);
Continue = toupper(Continue);
}

Page 168
The while statement
while (Continue != ‘Y’ && Continue != ‘N’)
can also be written as
while ( !(Continue == ‘Y’ || Continue == ‘N’)

Page 169
Exercises - Validation
In the following exercises, try using the logical expressions for NOT(Data correct) and Data
incorrect.

Exercises 10-1

Write the design and C code to data validate the mark (0-100 inclusive) for program GradNest.
GradNest: This program inputs a student mark and calculates a grade according to the following
scale:
Mark Grade
90-100 A
80-89 B
70-79 C
60-69 D
<=59 F

Exercises 10-2

Write a program to input a person’s height (in centimetres), validate the height to be >0 but <=200
and output the height to the screen.

Exercises 10-3
Write a program to input and validate a Choice A, B or C and output the choice to the screen.

SENTINEL CONTROLLED PROCESSING


A typical processing program consists of continually entering values until a sentinel is reached. A
typical layout of a sentinel controlled loop may look like this:

INPUT Variable
WHILE Variable <> SENTINEL DO
Further input
Processing of transaction
Output result of transaction
INPUT Variable
ENDWHILE

Note the two input statements for Variable, one before the loop and one inside the loop. The first
input before the while loop is to get the first value of Variable. The while loop is tested on this first
input value. If the while loop test is false the loop is not executed at all. If the while loop test is true
then the body of the loop is executed and the user will be prompted for the next input of Variable.
The while loop is then tested on this second input value. If the while loop test is false the loop is not
executed at all. If the while loop test is true then the body of the loop is executed and the user will
be prompted for the next input of Variable. The process continues.

Page 170
Example Count – Sentinel Controlled While loop

Write a program that accepts positive numbers from the keyboard, accumulates them until a zero
number (or negative) is entered and outputs the total entered.

Pseudocode
PROGRAM Count
Total = 0
INPUT Number
WHILE Number > 0
Total = Total + Number
INPUT Number
ENDWHILE
OUTPUT Total
END Count

C Code
/*
* Program Count
* This program accumulates the total of positive numbers
* until zero is entered.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
float Number = 0.0;
float Total = 0.0;
printf("Enter a number (zero stops processing)");
scanf("%f",&Number);
while (Number > 0)
{
Total = Total + Number;
printf("Enter a number (zero stops processing)");
scanf("%f",&Number);
}
printf("Total of all numbers entered is : %.2f", Total);
printf("\nPress Enter to continue");
getch();
return 0;
}

Page 171
Example - Addition

The addition process for a calculator program is to be repeated as many times as the user requires.
The condition for terminating the loop will be the input of zero.

An algorithm for the addition of two numbers for as many times as the user requires is:

Pseudocode
PROGRAM Addition
INPUT FirstNum
WHILE FirstNum <> 0
INPUT SecondNum
Total = FirstNum + SecondNum
OUTPUT Total
INPUT FirstNum
ENDWHILE
END Addition

This example requires the use of a WHILE loop because the user may decide not to carry out the
addition operation at all and can terminate the process by entering zero as the very first number.

The condition (FirstNum <> 0) is evaluated to determine whether or not the loop is repeated:

If the condition is TRUE, the statements in the body of the loop (in bold) are executed.

If the condition is FALSE, the statements in the body of the loop are skipped and the program
passes to the next statement after the ENDWHILE.

Note that the variable FirstNum, is assigned a value in two places:

1. Outside the loop. This provides a value to determine if the WHILE loop will be executed.
Failure to provide this assignment may result in the loop never executing. This step is
sometimes referred to as “priming” the loop.

2. The last statement inside the WHILE loop which provides a value to determine if the loop is
to be repeated or terminated. Failure to provide this assignment will result in an unterminated
loop, which will continuously carry out the set of tasks inside the loop until the program is
interrupted.

Page 172
The execution of the WHILE loop is illustrated in the desk check below which shows the values of
variables as each statement is executed.

DESK CHECK for INPUT 3, 7, 5, 2, 0

Statement Logical FirstNum SecondNum Total


INPUT FirstNum 3
WHILE FirstNum <> 0 True
INPUT SecondNum 7
Total = FirstNum + SecondNum 10
OUTPUT Total 10
INPUT FirstNum 5
WHILE FirstNum <> 0 True
INPUT SecondNum 2
Total = FirstNum + SecondNum 7
OUTPUT Total 7
INPUT FirstNum 0
WHILE FirstNum <> 0 False

Example Sort3 – Sentinel Controlled While loop

PROGRAM SPECIFICATION
DESCRIPTION
Design a program to accept an unknown number (at least one) of whole numbers from the
keyboard until a sentinel is entered. Output the largest number and the smallest number entered to
the screen (use a sentinel by assuming -999 will never occur in practice).
INPUTS
Whole numbers until -999
PROCESSING
Set smallest. largest to data
If incoming number < smallest, reset smallest
If incoming number > largest, reset largest
Continue processing until sentinel entered
OUTPUTS
The largest and smallest entered
OVERALL TASKS
Set largest and smallest
Input numbers
If incoming number < smallest, reset smallest
If incoming number > largest, reset largest
Continue processing until sentinel
Output largest and smallest

Page 173
DATA DICTIONARY
Variable Description Source Legal Values Data Type
Largest Largest number entered Internal Whole number Integer
Number Number entered Keyboard Whole number Integer
Smallest Smallest number entered Internal Whole number Integer
Pseudocode
PROGRAM Sort3
DEFINE SENTINEL = -999
INPUT Number
Smallest = Number
Largest = Number
WHILE Number <> SENTINEL
IF Number < Smallest THEN
Smallest = Number
ENDIF
IF Number > Largest THEN
Largest = Number
ENDIF
INPUT Number
ENDWHILE
OUTPUT Smallest, Largest
END Sort3

DESK CHECK for INPUT 2, 6, 1, 5, -999


Statement Logical SENTINEL Number Smallest Largest
DEFINE SENTINEL = -999 -999
INPUT Number 2
Smallest = Number 2
Largest = Number 2
WHILE Number <> SENTINEL True
IF Number < Smallest THEN False
IF Number > Largest THEN False
INPUT Number 6
WHILE Number <> SENTINEL True
IF Number < Smallest THEN False
IF Number > Largest THEN True
Largest = Number 6
INPUT Number 1
WHILE Number <> SENTINEL True
IF Number < Smallest THEN True
Smallest = Number 1
IF Number > Largest THEN False
INPUT Number 5
WHILE Number <> SENTINEL True
IF Number < Smallest THEN False
IF Number > Largest THEN False
INPUT Number -999
WHILE Number <> SENTINEL False

Page 174
OUTPUT Smallest, Largest 1 6

Page 175
C Code

/* Program Sort3
* This program finds the largest and smallest number from an
* unknown number of numbers
*/

#include <stdio.h>
#include <conio.h>

#define SENTINEL -999

int main(void)
{
int Number = 0;
int Largest = 0;
int Smallest = 0;

clrscr();
printf("Enter a number: ");
scanf("%i", &Number);
Smallest = Number;
Largest = Number;

while (Number != SENTINEL)


{
if (Number < Smallest)
{
Smallest = Number;
}
if (Number > Largest)
{
Largest = Number;
}
printf("Enter a number: ");
scanf("%i", &Number);
}

printf("The largest number entered is: %i", Largest);


printf("\nThe smallest number entered is: %i", Smallest);
printf("\nPress Enter to continue");
getch();
return 0;
}

Page 176
Example GradeW – Sentinel Controlled While loop
Consider a modification of an earlier example GradNest:
A program inputs a student mark (0-100) and calculates a grade of Pass for 50 or more otherwise a
Fail.

This program can perform only a single calculation:


INPUT Mark
Perform calculation of grade
OUTPUT Grade
and then it stops.

Modify the program so it can perform any number of calculations, one after the other, stopping
when a negative mark is entered.
PseudoCode:
PROGRAM GradW
INPUT Mark
WHILE Mark < 0
IF Mark >= 50 THEN
OUTPUT Pass
ELSE
OUTPUT Fail
INPUT Mark
ENDWHILE
END GradW.

C Code GradW:

/**********************************************************************
* Program | GradeW
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Calculate a student’s grade as Pass or Fail
*/

#include <stdio.h>
#include <conio.h>

int main (void)


{
int Mark = 0;

clrscr();
printf(“Enter student mark: “);
scanf("%i",&Mark);
while (Mark <0 )
{
if (Mark >=50)
{
printf("The student mark %i is a PASS\n",Mark);
}
else

Page 177
{
printf("The student mark %i is a FAIL\n",Mark);
}
printf(“Enter student mark: “);
scanf("%i",&Mark);
}
printf("\nPress enter to continue");
getch();
return 0;
}

NESTED WHILE LOOPS IN C


It is very common, both in real life and in programming, to have one loop inside another. Such loops
are called nested loops.

There are no restrictions in C on the use of loops within loops (just as there is no restriction on if
statements within if statements or if statements within loops or loops within if statements). Typically
in processing we get variables from the keyboard and validate them (content or range validation)
and demand input until they are valid.

You have already seen the use of while loops for data validation (where the program loops while
incorrect values are entered). You have also seen the use of while loops for processing, which is
terminated by a sentinel. If these techniques are combined, we get one while loop inside another.

Example – sentinel controlled loop


A typical layout of a sentinel controlled loop may look like this:

Initialise statistic variables


INPUT and VALIDATE Variable
WHILE Variable <> Sentinel DO
Further input and validation
Processing of transaction
Output result of transaction
Update statistics
INPUT and VALIDATE Variable
ENDWHILE
Output Statistics

Both the Sentinel controlled loop and validation tasks are generally WHILE Loops, so we have
while loops within while loops.

NOTE:
This model is a sentinel controlled loop allowing for zero or more passes through the main loop
body. When using a sentinel, the validation part of the variable (which is used for the termination of
the loop) may be more easily done as a separate task from the input within the main loop body.

Page 178
Example Count2 – nested while loop

Consider the previous example – programming with sentinels, Program Count. In this example,
positive numbers are entered and totalled. The program should stop when zero is entered, but it will
in fact stop when a negative number is entered. The program should validate the number to be 0 or
positive. The program should continue to demand input until valid, giving an error message when
invalid input is entered (negative numbers).

The input of the number is done in two places, before the sentinel controlled while loop and inside
the loop. Therefore the validation must also be done in these two places.

Pseudocode
PROGRAM Count2
Total = 0
INPUT Number
WHILE Number < 0
OUTPUT error message
INPUT Number
ENDWHILE
WHILE Number > 0
Total = Total + Number
INPUT Number
WHILE Number < 0
OUTPUT error message
INPUT Number
ENDWHILE
ENDWHILE
OUTPUT Total
END Count2

C Code
/*
* Program Count2
* This program accumulates the total of positive numbers
* until zero is entered.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
float Number = 0.0;
float Total = 0.0;
printf("Enter a number (zero stops processing)");
scanf("%f",&Number);
while (Number < 0)
{
printf(“\nYou have entered a negative number\n”);
printf("Enter a number (zero stops processing)");
scanf("%f",&Number);
}

Page 179
while (Number > 0)
{
Total = Total + Number;
printf("Enter a number (zero stops processing)");
scanf("%f",&Number);
while (Number < 0)
{
printf(“\nYou have entered a negative number\n”);
printf("Enter a number (zero stops processing)");
scanf("%f",&Number);
}
}
printf("Total of all numbers entered is : %.2f", Total);
printf("\nPress Enter to continue");
getch();
return 0;
}

This is also a good example of why a modular approach should be used. The code to input and
validate the number is used twice. The code for this function can be written once but called twice as
shown below:

Example Count2M – Modular nested while loop


Pseudocode
PROGRAM Count2M
Total = 0
DO InputNumber
WHILE Number > 0
Total = Total + Number
DO InputNumber
ENDWHILE
DO OutputTotal
END Count2M

MODULE InputNumber
INPUT Number
WHILE Number < 0
OUTPUT error message
INPUT Number
ENDWHILE
END InputNumber

MODULE OutputTotal
OUTPUT Total
END OutputTotal

C Code
/*
* Program Count2M
* This program accumulates the total of positive numbers
* until zero is entered.
*/

#include <stdio.h>
#include <conio.h>

Page 180
/* prototypes */
float InputNumber(void);
void OutputTotal(float Total);

int main(void)
{
float Number = 0.0;
float Total = 0.0;
clrscr();
Number = InputNumber();
while (Number > 0)
{
Total = Total + Number;
Number = InputNumber();
}
OutputTotal(Total);
return 0;
}

/* Functions */

/***********************************************************/

float InputNumber(void)
{
float Number = 0.0;
printf("Enter a number (zero stops processing)");
scanf("%f",&Number);
while (Number < 0)
{
printf("\nYou have entered a negative number\n");
printf("Enter a number (zero stops processing)");
scanf("%f",&Number);
}
return Number;
} /* end function InputNumber */

/***********************************************************/

void OutputTotal(float Total)


{
printf("\n\nTotal of all numbers entered is : %.2f", Total);
printf("\n\nPress Enter to continue");
getch();
return;
} /* end function OutputTotal */

/***********************************************************/

Example Program Tax4 – nested while loop


Write a program to repeatedly determine the Nett pay when a Gross pay (>0 and <=50000) is
input and validated. Processing is to stop when a Gross pay of zero is entered. Use the following tax
scale to calculate the Nett pay:
GrossPay TaxRate
0 - 5000 0

Page 181
5001 - 20000 25%on excess over 5000
20000 - 50000 tax on first 20,000+40% on excess over 20000
Calculate and output the Nett pay for each entry. After processing stops, output of Average Nett
pay and Average tax are required.
PseudoCode:
PROGRAM Tax4
DEFINE BASE1=5000, BASE2=20000, RATE1=0.25, RATE2=0.4,
MAX_GROSS_PAY=50000
TotalNettPay=0
TotalTax=0
Count=0
INPUT GrossPay
WHILE (GrossPay < 0) OR (GrossPay > MAX_GROSS_PAY)
OUTPUT error message
INPUT GrossPay
ENDWHILE
WHILE GrossPay <> 0
IF GrossPay <= BASE1 THEN
Tax = 0
ELSE
IF GrossPay <= BASE2 THEN
Tax = RATE1*(GrossPay - BASE1)
ELSE
Tax = RATE2*(GrossPay - BASE2) + RATE1*(BASE2-BASE1)
ENDIF
ENDIF
NettPay = GrossPay - Tax
OUTPUT NettPay
TotalNettPay = TotalNettPay + NettPay
TotalTax = TotalTax + Tax
Count = Count + 1
INPUT GrossPay
WHILE (GrossPay < 0) OR (GrossPay >= MAX_GROSS_PAY)
OUTPUT error message
INPUT GrossPay
ENDWHILE
ENDWHILE
IF Count > 0 THEN
AverageNettPay = TotalNettPay/Count
AverageTax = TotalTax/Count
OUTPUT AverageNettPay, AverageTax
ELSE
OUTPUT zero entries entered
ENDIF
END Tax4

C Code Tax4
/* Program Tax4 continuously calculates the tax on a gross pay
* according to a 3 level tax bracket 0-5000, 5001-20000 and >20000.
*/

#include <stdio.h>
#include <conio.h>

#define BASE1 5000


#define BASE2 20000
#define RATE1 0.25

Page 182
#define RATE2 0.40
#define MAX_GROSS_PAY 50000

int main (void)


{
float NettPay = 0.0;
float GrossPay = 0.0;
float Tax . = 0.0;
float TotalNettPay = 0.0;
float TotalTax = 0.0;
float AverageNettPay = 0.0;
float AverageTax = 0.0;
int Count = 0;

clrscr();
printf(“Enter the Gross Pay $”);
scanf(“%f”,&GrossPay);
while ((GrossPay < 0) || (GrossPay > MAX_GROSS_PAY))
{
printf(“The gross pay must be between 0 and 50000(0 to exit)”);
printf(“\nEnter the Gross Pay $”);
scanf(“%f”,&GrossPay);
}
while (GrossPay != 0)
{
if (GrossPay <= BASE1)
Tax=0;
else
if (GrossPay <= BASE2)
Tax = RATE1 * (GrossPay - BASE1);
else
Tax = RATE2 * (GrossPay - BASE2) + RATE1 * (BASE2 -BASE1);
NettPay = GrossPay - Tax;
printf(“The Tax payable is $ %.2f\n”,Tax);
printf(“The Nett Pay is $ %.2f\n”,NettPay);
printf(“\n\nPress enter to continue”);
getch();
TotalNettPay = TotalNettPay + NettPay;
TotalTax = TotalTax + Tax;
Count = Count + 1;
clrscr();
printf(“Enter the Gross Pay $”);
scanf(“%f”,&GrossPay);
while ((GrossPay < 0) || (GrossPay > MAX_GROSS_PAY))
{
printf(“Gross pay must be between 0 and 50000(0 to exit)”);
printf(“\nEnter the Gross Pay $”);
scanf(“%f”,&GrossPay);
}
}
if (Count > 0)
{
clrscr();
AverageNettPay = TotalNettPay/Count;
AverageTax = TotalTax/Count;
printf(“\n\nThe average Nett Pay is \t$ %.2f”,AverageNettPay);
printf(“\n\nThe average Tax is \t\t$ %.2f”,AverageTax);
}
else
printf(“\nThere were NO entries”);

Page 183
printf(“\n\nPress enter to continue”);
getch();
return 0;
}

Note the instances of nested ifs (which you have seen before) and nested whiles in this program.

Page 184
Example Tax4 - with functions

This program is presented to illustrate nested loops. In practice, the program could be written better
with the use of functions. The process of reading and validating the gross income could be made a
function, eliminating the need for an explicit nested loop in the program.

If this idea is combined with the previous idea (Chapter Functions) of a function for calculating the
tax, the program looks like this:

/* Program Tax4 continuously calculates the tax on a gross pay


according to a 3 level tax bracket 0-5000, 5001-20000 and >20000.*/

#include <stdio.h>
#include <conio.h>

#define BASE1 5000


#define BASE2 20000
#define RATE1 0.25
#define RATE2 0.40
#define MAX_GROSS_PAY 50000

float CalculateTax(float Income);


float GetValidatedPay(void);

int main (void)


{
float NettPay = 0.0;
float GrossPay = 0.0;
float Tax . = 0.0;
float TotalNettPay = 0.0;
float TotalTax = 0.0;
float AverageNettPay = 0.0;
float AverageTax = 0.0;
int Count = 0;

clrscr();
GrossPay = GetValidatedPay();
while (GrossPay != 0)
{
Tax = CalculateTax(GrossPay);
NettPay = GrossPay - Tax;
printf("The Tax payable is $ %.2f\n",Tax);
printf("The Nett Pay is $ %.2f\n",NettPay);
TotalNettPay = TotalNettPay + NettPay;
TotalTax = TotalTax + Tax;
Count = Count + 1;
GrossPay = GetValidatedPay();
}
if (Count>0)
{
clrscr();
AverageNettPay = TotalNettPay / Count;
AverageTax = TotalTax / Count;
printf("\n\nThe average Nett Pay is \t$ %.2f",AverageNettPay);
printf("\n\nThe average Tax is \t\t$ %.2f",AverageTax);

Page 185
}
else
printf("\nThere were NO entries");
printf("\n\nPress enter to continue");
getch();
return 0;
}

/******************************************************
* function CalculateTax computes tax from income
* PRE Income is taxable income in dollars
* POST Return value is corresponding tax
*/
float CalculateTax(float Income)
{
float Tax = 0.0;

if (Income <= BASE1)


Tax=0;
else
if (Income <= BASE2)
Tax=RATE1 * (Income - BASE1);
else
Tax = RATE2*(Income - BASE2) + RATE1 * (BASE2 - BASE1);
return Tax;
}

/******************************************************
* function GetValidatedPay inputs and validates GrossPay
* PRE MAX_GROSS_PAY is maximum allowable pay
* POST Return value is between 0 and MAX_GROSS_PAY
*/
float GetValidatedPay(void)
{
float Pay = 0.0;

printf("Enter the Gross Pay $");


scanf("%f",&Pay);
while ((Pay < 0) || (Pay > MAX_GROSS_PAY))
{
printf("Gross pay must be between 0 and 50000(0 to exit)");
printf("\nEnter the Gross Pay $");
scanf("%f",&Pay);
}
return Pay;
}

The nested loops have been eliminated from this program, because the validation loop has been put
in the GetValidatedPay function. Although the program no longer contains an explicit nested loop,
the loop-within-a-loop will still be executed, because main calls GetValidatedPay within its loop,
and GetValidatedPay itself contains a loop. Using modules has separated the two loops, and
simplified the program.

Page 186
DEBUGGING LOOPS
Almost all useful programs contain loops, and programs containing loops are particularly prone to
errors, and it is a good idea to know what the dangers are, how to avoid them and how to correct
problems that do occur.

Common logic error


A common solution using a pretest loop, which is incorrectly structured as explained further, is as
follows:

1. Choice = -1;
2. while (Choice != 0)
3. {
4. Choice = GetChoice();
5. if (Choice != 0)
6. ProcessChoice(Choice);
7. }

Line 1 has been added solely for the purpose of forcing the while loop test to be false the first time
through. This is so the GetChoice statement (line 4) in the body of the loop is executed at least once,
ie the user enters at least one Choice.. Notice how this has caused the need for an if statement (line
5) with another test for the sentinel value 0. This is so the ProcessChoice (line 6) does not occur
when the sentinel is entered. We are now executing the same test twice in lines 2 and 5 for each
iteration of the loop. This is an unnecessary overhead during program execution.

The correct loop structure should be:

1. Choice = GetChoice();
2. while (Choice != 0)
3. {
4. ProcessChoice(Choice);
5. Choice = GetChoice();
6. }

Although lines 1 and 5 are the same, it will have no effect on execution speed and is of no concern.

Infinite loops

The worst sort of looping error is an infinite loop, where the condition that stops the loop never
happens, and the loop just goes on for ever. The computer will seem to have stalled. Not so many
years ago, the only way out of this situation was to reboot the computer.

Such drastic action is not usually required these days. Before you start running programs with loops,
be sure to know the key combination that will interrupt a looping program. This is usually Ctrl/Break
or Ctrl/C. If your program is stuck (or even if it is not), pressing this key will stop it and return
control to DOS.

In Windows-based IDEs, there will usually be a button or menu item to stop the running program.

Page 187
It is incredibly easy to set up an infinite loop by accident in C. Consider one of the while statements
we had earlier in the chapter:

while (DaysCount < 30)


{
DaysCount = DaysCount + 1;
Hours = Hours + 8;
}

You should already know how this statement works. Suppose it had been written like this:

while (DaysCount < 30);


{
DaysCount = DaysCount + 1;
Hours = Hours + 8;
}

Note the extra semicolon. This statement will go into an infinite loop whenever DaysCount is less
than 30. Why? The body of the loop is not the code between the condition of the while and the
semicolon, which is nothing. What we are telling the computer to do is, while DaysCount<1, do
nothing. But doing nothing is never going to change the value of DaysCount, so it will continue to be
<30, and the loop will go on executing.

This brings us to an important rule about while loops: The body of the loop must contain code
that will eventually make the loop condition false.

In the original program above, we can see that this is true. The statement to increase DaysCount by
1 will eventually make it 30 and the loop will stop

In the altered program, the intention was the same, but a quirk of C syntax frustrated the intention.

The best way of avoiding infinite loops is by careful design of your program. Careful desk checking
is a particularly powerful way to identify potential problems of this kind. If you have a complete
program with an infinite loop, then desk-checking (of the program code) is still the most effective
way to track it down.

Uninitiated loops
A common problem with while loops is not to set up the loop condition to begin with. The loop must
be primed. This usually consists of repeating code before the loop, which is also contained inside the
loop. You have already seen some examples of this. In the sentinel examples above, the program
had to read a value before the loop could be entered. The body of the loop finished by reading the
next item. This is a very common structure.

There are some instances where a while loop does not need to be explicitly primed. If you are
processing data from a file, for example, the process of opening the file will automatically tell the
program if there is initially any data on it. So the following structure is acceptable:

Page 188
Pseudocode
Open file
WHILE not at end-of-file
Read next data item
Process next data item
ENDWHILE

Processing of data will continue as long as there is data to read. The loop is primed (though not
explicitly) by the “open file” operation. This will determine if we are initially at the end of the file or
not. Note that this program also follows out previous rule. The reading of an item each time around
the loop ensures that we will eventually get to the end of the file, and stop the loop (so long as you
are reading from the same file as you are testing!).

Out-by-1 errors
Another common logic error in loops is to execute the loop once more or once less than intended.
Consider the following example:
Pseudocode
Count = 1;
WHILE Count < 10
Display "Hello!"
Count = Count + 1
ENDWHILE

How many times will this loop display “Hello!”? By casually inspecting the programs, you might
think it was ten times, but is this correct? Check more carefully.

Again, a good understanding of how the loop structures work, and careful desk-checking, can
prevent out-by-1 problems occurring.

Page 189
Exercise 10-4 Sentinel Controlled While loop

A program is to read a collection of exam scores ranging in value from 1 to 100. The program
should count and print the number of outstanding scores (90-100), the number of high average
scores (70-89), the number of satisfactory scores (50-69), and the number of unsatisfactory scores
(0-50). Assume that when a negative number is entered, the results are displayed.

Tasks:
1. Develop a program specification.
2. Known results.
3. Pseudocode.
4. C code

Additional:
Modify the tasks in Exercise so that the program will display the average exam score at the end of
the run.

Exercises – While Loops


For each of the following problems develop:

1. Program specification.
2. Two known results.
3. Data dictionary
4. Structure Chart
5. Algorithm using pseudocode
6. Desk check using known results

Exercise 10-5

POST4W: Validation of inputs.


Modify the design of POST4M to validate input for Weight of a parcel (0-20Kg) and ParcelType
(S, C, E). Continue to demand input until valid, giving an error message when invalid input is
entered.

POST4M: (write functions to input weight and parcel type, calculate the postage charge and output
the parcel type and charge.). A program requires the weight of a parcel (0-25 Kg) and the parcel
type (S-surface, C-courier or E-express) to be entered from the keyboard. The charge is set at
$1.50 per kg. There is a maximum charge of $10 for surface parcels and a maximum charge of $20
for courier and express parcels. There is also an additional surcharge of $8 for courier parcels and a
surcharge of $5 for express parcels. The parcel type and charge is to be output to the screen.

Page 190
Exercise 10-6

POST4S: Sentinel controlled loop.


Modify the design of POST4W to add a while loop to continue processing postage charges until a
sentinel value of 0 is entered for the parcel weight. On exit of the program, output the total of all
parcel charges to the screen.

Exercise 10-7

ANIM4W: Validation of inputs.


Modify the design ANIM4M to validate input for the Animal type (B,C,D,O), number of hours of
the consultation(>0), and the type of owner (N-normal or F-farmer). Continue to demand input until
valid, giving an error message when invalid input is entered.

ANIM4M: (write functions to input hours, input animal type, input owner type, set hourly rate,
calculate the consultation fee and output the consultation fee.)
Input the number of hours of the consultation(>0), and the type of owner (N-normal or F-farmer)
from the keyboard. The consultation fee for a vet is obtained by multiplying the number of hours by
the hourly rate. The hourly rate is set at $20 for birds, $25 for cats, $30 for dogs and $40 for other
animals. There is a 20% discount on the consultation fee for farmers. For each consultation, output
all the inputs and the consultation fee to the screen.

Exercise 10-8

ANIM4S: Sentinel controlled loop.


Modify the design ANIM4W to input the Animal type (B,C,D,O or X to exit). The program is to
continue processing consultation fees and exit once an Animal Type of X is entered.

Exercise 10-9

BANK4W: Validation of inputs.


Modify the design of BANK4M to validate input for Principal (1000 – 500000), Term (5-40 years)
and LoanType (C, I, S). Continue to demand input until valid, giving an error message when invalid
input is entered.

BANK4M: (write functions to input principal, input term, input loan type, set interest rate, calculate
the monthly repayment and output the details.)A loan officer requires a program to calculate the
monthly repayment M on a customer loan by entering from the keyboard the principal P (1000 –
500000) , the term T of the loan (5-40 years) and the loan type (C-car, I-investment or S-staff).
The monthly repayment is calculated as
M=P(1+RT/100.0)/(12T).
The annual interest rate of R% pa. is set at 10% for car loans, 13% for investment loans and 8% for
staff loans. All inputs and the result is output to the screen.

Page 191
Exercise 10-10

BANK4S: Sentinel controlled loop.


Modify the design of BANK4W so that the program continually calculates monthly repayments.
Once a principal of zero is entered, the program should output the total money borrowed (total
principal).

Exercise 10-11

PARK: A program is required to calculate the cost of parking in a car park. The program is to
accept the input of the number of hours parked in the car park (rounded up) and display the cost
based on the following rates:
1 to 4 hours RATE1=$3 per hr
5 to 7 hours RATE2=$1.50 per hr>=5 hrs + 4 hrs*RATE1
8 to 24 hours FLATRATE=$18
The program is to repeatedly prompt for the input of hours until a value of 0 is entered. When a
value of 0 is entered for the number of hours, the program should display the following statistics:

• The total number of cars for each time period.


• The total number of hours for all cars processed.
• The total of all car-parking fees collected.
• The average number of hours a car stayed in the car park.
• The average cost of a stay in the car park.

The program should operate correctly for a bad day when no cars use the car park.

Exercise 10-12

RECT4W: Modify the design for RECT2 to input and validate the height>=0 and width<=height.
Continue to demand input until valid, giving an error message when invalid input is entered.

Exercise 10-13

TIME4W: Modify the design developed in TIME2 to demand input until all variables have been
input as requested.

Page 192
Extra Exercises – While Loop

Exercise 10-14

Write a program to calculate a salesperson's weekly wage. The person’s wage is made up of a base
wage and an additional bonus dependent on the sales they make. The base wage is $200 and the
additional bonus is calculated using the following:
Sales less than $1000 do not attract a bonus.
Sales of $1000 - $10000 attract a bonus of 10% of sales.
Sales over $10,000 attract a bonus of 20% of sales.
The user is to enter the sales amount; this is to be validated between 0-50,000. The program is to
display the salesperson's bonus and wage.

Exercise 10-15

Write a program that determines whether or not you have to pay for your delivered pizza. Pizzas are
a set cost of $5.95 each. You are required to enter in the number of pizzas and the delivery time in
minutes. The number of pizzas must be validated to be between 1 and 20 and delivery time must be
validated to be between 10 and 60 minutes. If the delivery takes more than 30 minutes then you
don't have to pay, otherwise you pay the normal price. Output the price to the screen.

Exercise 10-16

Write a program that determines whether you can afford to buy a car. You are required to input the
amount of deposit you can afford towards buying a car and the price of a car you want to buy. The
program should allow for different car prices to be entered, 0 to end. The program is to calculate
the required deposit for the car as 10% of the car’s price. If you can afford the required deposit, the
program should output a message to indicate that you can afford the car with the amount of deposit
and car price, otherwise output a message to say you cannot afford the car.

Page 193
CASE STUDY - PFEECAL5
Edit the program from PFeeCal4 to include data validation. Check that
• The customer ID must have a value between 1000 and 9999 (inclusive).
• The customer type must be ‘R’ or ‘C’.
• The number of days must be non-negative.

PfeeCal5:
Write a program that will request the following information from a user and validate the input:
An ID number (4 digit integer between 1000 and 9999 inclusive.)
The type of customer (‘R’ regular or ‘C’ casual)
The number of required networker days (>0).
The number of required programmer days (>0).
The number of required office administrator days (>0).

The following table shows the fees that are charged:


Professional Charge per day for a
Casual Customer
A Network professional (N) $115.00
An Office administrator (O) $120.00
A Programmer (P) $100.00

A regular customer will receive 5% discount on the fee. Your program should calculate the
associated costs for Networkers, Programmers and Office workers and total cost and output these
costs in a table to the screen.

Page 194
CHAPTER 11 -
ITERATION: THE REPEAT UNTIL LOOP

Upon successful completion of this chapter you will be able to:

• Write the pseudocode for the repeat loop structure

• Use the do-while statement in C code programs to solve a repeat loop problem

• Use a flag to continue processing

• Use repeat loops for menu structured programs

• Use nested loops

Summary of new terms:

REPEAT_UNTIL loop - is referred to as a post-test loop because the condition for terminating
the loop is tested at the end of the set of tasks to be repeated.

Page 195
OVERVIEW
The REPEAT_UNTIL loop is referred to as a post-test loop because the condition for terminating
the loop is tested at the end of the set of tasks to be repeated.

If the condition evaluates to TRUE the loop is terminated; if the condition evaluates to FALSE the
tasks are executed again. The structure of this loop means that the statements in the body of the
loop will always be executed at least once. Post-test loops generally do not have to be primed as
pre-test loops do.

POST -TEST LOOPS


Pseudocode

The general format for a post-test loop in pseudocode is:

REPEAT
statement(s)
UNTIL condition

The statements in the body of the loop are repeated until the condition becomes true. The loop is
always executed at least once, with the test occurring at the end.

C Code
Most programming languages use the reserved words repeat and until to specify post-test loops,
making the code look very much like the pseudocode. Unfortunately C does not. It uses a do-while
construction.

The do-while statement is much like the while statement although the do-while statement always
executes at least once. This is because the condition is at the end of the do-while statement so the
statements within are executed once before the condition is tested. Another difference between the
while and do-while statements is that the do-while statement executes while the condition is false
whereas the while statement executes while the condition is true. A simple do-while statement
consists of -

1. The control statement "do".


2. An open curly bracket {
3. The program statements to be executed separated by a semi-colon.
4. A closed curly bracket }
5. The control statement "while".
6. The condition statement within brackets followed by a semi-colon.

An example is shown below:-

do
{
printf("This line will print 10 times");
Count = Count+1;
} while (Count < 10);

Page 196
Example - Average

Consider a problem to calculate the average given a series of input numbers. In this algorithm the
number of inputs must be at least one. Hence there is no need to test for zero division in the second
last line. Assume -999 is the terminating number.
PseudoCode
PROGRAM Average
Total = 0
NumInputs = 0
INPUT Num
REPEAT
Total = Total + Num
NumInputs = NumInputs + 1
INPUT Num
UNTIL Num = -999
Average = Total / NumInputs
OUTPUT Average
END Average

DESK CHECK for INPUTS 2, 6, 7, -999 (known result 15)


Statement Logical NumInputs Total Num Average
Total = 0 0
NumInputs = 0 0
INPUT Num 2
Total = Total+Num 2
NumInputs=NumInputs+1 1
INPUT Num 6
UNTIL Num=-999 False
Total = Total+Num 8
NumInputs=NumInputs+1 2
INPUT Num 7
UNTIL Num=-999 False
Total = Total+Num 15
NumInputs=NumInputs+1 3
INPUT Num -999
UNTIL Num=-999 True
Average=Total/NumInputs 5
OUTPUT Average 5
Conclusion: correct

Page 197
C Code

/* Program Average
* This program calculates the average of a series of numbers
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
int NumInputs = 0;
float Num = 0.0;
float Total = 0.0;
float Average = 0.0;

printf("Enter a number (-999 to end) : ");


scanf("%f", &Num);
do
{
Total = Total + Num;
NumInputs = NumInputs + 1;
printf("Enter a number (-999 to end) : ");
scanf("%f", &Num);
}
while (Num != -999);
Average = Total / NumInputs;
printf("The average is : %.2f", Average);
printf("\nPress Enter to continue");
getch();
return 0;
}

APPLICATIONS OF REPEAT LOOPS


Using Flags

Another technique of looping is to use a flag to control processing. Unlike a sentinel controlled loop
where the sentinel value is related to a variable, which is used in the processing, the flag is usually a
variable independent of the processing phase. It is usually a character variable, which asks the user
whether they wish to continue Y or N.

A typical layout of a flag controlled loop may look like this:

Initialise
REPEAT
Input and Validation of variables
Processing
Output transaction
Update statistics
INPUT and VALIDATE Continue
UNTIL Continue = ‘N’

Page 198
Output Statistics

NOTE:
The Repeat loop allows at least one pass through the main loop body. The validation tasks are
generally While loops, so we have while loops within repeat loops.

Using Menus
Another typical use of the Repeat loop is for a menu driven problem. The program will display a
menu and ask the user to choose one of the items. Processing for the appropriate item will then be
done. One of the menu choices will be to stop the program. The loop will repeat until this “quit”
option is selected.

Example - Menu
Write a program to repeatedly display a menu, input a choice from it and perform an appropriate
action depending on the choice. The menu is:
1. Display “This”
2. Display “That”
3. Quit
The menu is to be repeated until the user enters a choice of 3 to quit.
PseudoCode
PROGRAM Menu
REPEAT
OUTPUT Menu list
INPUT Choice
WHILE Choice<1 OR Choice>3
OUTPUT error message
INPUT Choice
ENDWHILE
CASE Choice
1: OUTPUT “This”
2: OUTPUT “That”
3: OUTPUT Quit message
ENDCASE
UNTIL Choice = 3
END Menu

Example - C Code menu

/* Program Menu uses a menu to choose an action.


*/

#include <stdio.h>
#include <conio.h>

int main (void)


{

int Choice = 0;

Page 199
do
{
/* input menu choice */
clrscr();
printf("Menu demonstration\n");
printf("\t1. This\n\t2. That\n\t3. Quit\n");
printf("Enter your choice: ");
scanf("%i",&Choice);
while ((Choice < 1) || (Choice > 3))
{
clrscr();
printf("Menu demonstration\n");
printf("\t1. This\n\t2. That\n\t3. Quit\n");
printf("Enter your choice: ");
scanf("%i",&Choice);
}

/* Perform chosen action */

switch(Choice)
{
case 1:
printf("You chose This");
break;

case 2:
printf("You chose That");
break;

case 3:
printf("\n\nGoodbye\n\n”);
break;
} /* end of case */

printf(“\nPress enter to continue”);


getch();
} while (Choice != 3);

return 0;
}

Example - Bonus3

PROGRAM SPECIFICATION
Employees at a local business receive an end of year bonus, which is calculated as one and
a half week’s pay and an additional bonus of $100 for more than 10 years experience. The
program accepts the employee ID (4 digit integer 1000-9999), year’s experience (0-50)
and the weekly pay(0-2000), calculates the bonus and outputs the ID and bonus to the
screen. The program continues to process with a Y/N prompt and displays the total number
of employees and the total bonuses on exit.

INPUTS
Employee ID
Experience
WeeklyPay

Page 200
Continue (Y/N)

PROCESSING
Initialise totals
Calculate Bonus
Adjust for additional bonus
Update counters
Continue if Y

OUTPUTS
Employee ID and bonus for each transaction
Total Employees and total bonus on exit

OVERALL TASKS
Initialise counters
repeat
Input Employee ID, experience, weekly pay
Calculate bonus and adjust for extra
Output employee details
Input Continue
until Continue=N
Output totals

DATA DICTIONARY

Variable Description Source Legal Values Data Type


Bonus Annual bonus awarded Derived >=0 Real
Continue Response to continue Keyboard Y or N Char
processing
EmpID 4 digit employee ID Keyboard >=1000 and Integer
<=9999
Experience Years of experience Keyboard >0 and <=50 Integer
TotalBonus Accumulated bonus Derived >=0 Float
TotalEmp Counter for number of Derived >0 Integer
employees
WeeklyPay Employee’s weekly pay Keyboard >0 and <= 2000 float

PseudoCode
PROGRAM Bonus3 MAIN
DEFINE CONSTANTS RATE=1.5,MINEXP=10,EXTRABONUS=100
TotalEmp=0, TotalBonus=0
REPEAT
DO GetEmpId
DO GetExperience
DO GetWeeklyPay
DO CalculateBonus
DO OutputEmpDetails
TotalEmp=TotalEmp+1

Page 201
TotalBonus=TotalBonus+Bonus
DO GetContinue
UNTIL Continue=N
DO OutputStats
END MAIN

MODULE GetEmpId
INPUT EmpId
WHILE EmpId < 1000 OR EmpId >9999
OUTPUT error message
INPUT EmpId
ENDWHILE
END MODULE GetEmpId

MODULE GetExperience
INPUT Experience
WHILE Experience<0 OR Experience>50
OUTPUT error message
INPUT Experience
ENDWHILE
END MODULE GetExperience

MODULE GetWeeklyPay
INPUT WeeklyPay
WHILE WeeklyPay <0 OR WeeklyPay >2000
OUTPUT error message
INPUT WeeklyPay
ENDWHILE
END MODULE GetWeeklyPay

MODULE CalculateBonus
Bonus=WeeklyPay*RATE
IF Experience>MINEXP THEN
Bonus=Bonus+EXTRABONUS
ENDIF
END MODULE CalculateBonus

MODULE OutputEmp Details


OUTPUT EmpId
OUTPUT Bonus
END MODULE OutputEmpDetails

MODULE GetContinue
INPUT Continue
WHILE Continue<>’Y’ AND Continue<>’N’
OUTPUT error message
INPUT Continue
ENDWHILE
END MODULE GetContinue

MODULE OutputStats
OUTPUT TotalBonus, TotalEmp
END MODULE OutputStats

C Code

/* Bonus3
* This program calculates an end of year bonus for employees *

Page 202
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define RATE 1.5


#define MINEXP 10
#define EXTRA_BONUS 100

/* prototypes */
int GetEmpID(void);
int GetExperience(void);
float GetWeeklyPay(void);
float CalculateBonus(float WeeklyPay, int Experience);
void OutputEmpDetails(int EmpID, float Bonus);
char GetContinue(void);
void OutputStats(int TotalEmp, float TotalBonus);

int main(void)
{
int TotalEmp = 0;
float Bonus = 0.0;
float TotalBonus = 0.0;
int EmpID = 0;
int Experience = 0;
float WeeklyPay = 0.0;
char Continue = ‘ ‘;

do
{
EmpID = GetEmpID();
Experience = GetExperience();
WeeklyPay = GetWeeklyPay();
Bonus = CalculateBonus(WeeklyPay, Experience);
OutputEmpDetails(EmpID, Bonus);
TotalEmp = TotalEmp + 1;
TotalBonus = TotalBonus + Bonus;
Continue = GetContinue();
}
while (Continue == 'Y');

OutputStats(TotalEmp, TotalBonus);
return 0;
}

/************************************************************/
int GetEmpID(void)
{
int EmpID = 0;
clrscr();
printf("Enter the Employee ID (1000-9999): ");
scanf("%i", &EmpID);
while (EmpID <1000 || EmpID > 9999)
{
printf("Error in ID. ID must be between 1000 - 9999 :");
scanf("%i", &EmpID);
}
return EmpID;
}

Page 203
/************************************************************/

int GetExperience(void)
{
int Experience = 0;
printf("Enter the Employee's years experience(0-50): ");
scanf("%i", &Experience);
while (Experience < 0 || Experience >50)
{
printf("Enter the Employee's years experience(0-50): ");
scanf("%i", &Experience);
}
return Experience;
}
/************************************************************/

float GetWeeklyPay(void)
{
float WeeklyPay = 0.0;
printf("Enter the weekly pay($0-$2000): ");
scanf("%f", &WeeklyPay);
while (WeeklyPay <0 || WeeklyPay > 2000)
{
printf("Enter the weekly pay($0-$2000): ");
scanf("%f", &WeeklyPay);
}
return WeeklyPay;
}
/************************************************************/

float CalculateBonus(float WeeklyPay, int Experience)


{
float Bonus = 0.0;
Bonus = WeeklyPay * RATE;
if (Experience > MINEXP)
Bonus = Bonus + EXTRA_BONUS;
return Bonus;
}
/************************************************************/

void OutputEmpDetails(int EmpID, float Bonus)


{
clrscr();
printf("\n\nEmployee %i earned a bonus ", EmpID);
printf("of $%.2f\n", Bonus);
return;
}
/************************************************************/

char GetContinue(void)
{
char Continue = ‘ ‘;
printf("\nDo you wish to continue Y or N ");
fflush(stdin);
scanf("%c", &Continue);
Continue = toupper(Continue);
while (Continue != 'Y' && Continue != 'N')
{
printf("\nDo you wish to continue? Enter Y or N ");
fflush(stdin);

Page 204
scanf("%c", &Continue);
Continue = toupper(Continue);
}
return Continue;
}
/************************************************************/

void OutputStats(int TotalEmp, float TotalBonus)


{
clrscr();
printf("\nThe total number of employees is %i",TotalEmp);
printf("\n\nThe total bonus is $%.2f", TotalBonus);
printf("\n\nPress Enter to continue");
getch();
return;
}
/************************************************************/

Common logic error


A common solution using a post-test loop for data validation of a Choice (Choice can be 1,2,3 or
4), which is incorrectly structured as explained further, is as follows:

1. do
2. {
3. Choice = GetChoice();
4. if (Choice < 1 || Choice > 4)
5. OutputErrorMessage();
6. } while (Choice < 1 || Choice > 4);

Line 4 has been added for the purpose of outputting an error message if the Choice is incorrect. We
are executing the same test twice in lines 4 and 6 for each iteration of the loop. This is an
unnecessary overhead during program execution.

An alternative solution using a post-test loop could be as follows, but this solution does not output
an error message. If this is required a pretest loop (while) would be the better loop to use.

The correct post-loop structure should be:


1. do
2. {
3. Choice = GetChoice();
4. } while (Choice < 1 || Choice > 4);

Exercise – Repeat Loops


For each of the following problems develop:
1) Algorithm using pseudocode
2) Desk check using known results
3) C code

Exercise 11-1
POST4R:

Page 205
Modify the design developed for POST4W to allow continued use of the design until a Y/N option
is given. When N is selected display the total charge of postage.

POST4W: A program requires the weight of a parcel (0-25 Kg) and the parcel type(S-surface, C-
courier or E-express) to be entered from the keyboard. The charge is set at $1.50 per kg. There is
a maximum charge of $10 for surface parcels and a maximum charge of $20 for courier and express
parcels. There is also an additional surcharge of $8 for courier parcels and a surcharge of $5 for
express parcels. For each parcel, output the parcel type and charge to the screen.

Exercise 11-2
ANIM4R: Modify the design of ANIM4W to display a menu to perform the following:
3. Process Customer
4. Output Current Customer Details
5. Quit

ANIM4W: A program inputs and validates the number of hours of the consultation, the animal type
(B-bird, C-cat, D-dog, O-other) and the type of owner (N-normal or F-farmer) from the
keyboard. The consultation fee for a vet is obtained by multiplying the number of hours by the hourly
rate. The hourly rate is set at $20 for birds, $25 for cats, $30 for dogs and $40 for other animals.
There is a 20% discount on the consultation fee for farmers. Output all the inputs and the
consultation fee to the screen.

Exercise 11-3
BANK4R: Modify the design developed for BANK4W to allow continued use of the design until a
Y/N option is given. When N is selected display the total principal of all the loans.

BANK4W: A loan officer requires a program to calculate the monthly repayment M on a customer
loan by entering and validating from the keyboard the principal P (1000 – 500000), the term T of
the loan(5 - 40 years) and the loan type (C-car, I-investment or S-staff). The monthly repayment is
calculated as
M=P(1+RT/100.0)/(12T).
The annual interest rate of R% pa. is set at 10% for car loans, 13% for investment loans and 8% for
staff loans. All inputs and the result is output to the screen.

Exercises – Extra Repeat loops

Exercise 11-4

DISC4: Modify the design for DISC2 to accept input, process at least one calculation and output
the charge and then prompt for more with a Y/N option.
DISC2: A program accepts the marked value of an item in $ and cents and a request for Markup
(M) or Discount (D) and input either the markup percentage or discount percentage. Output to the
screen the new price marked up or discounted by the % entered.

Page 206
Exercise 11-5

INDEX: A program is to read a collection of integer data items and find and print the index of the
first occurrence and the last occurrence of the number 24. The program will print index value of 0 if
the number 24 is not found. The index is the sequence number of the data item 24. For example, if
the fifth data item is the only 24, then the index value 5 should be printed for the first and last
occurrence. The program should prompt the user whether they want to continue processing or not.
If the answer is ‘N’ then the result will be displayed. If ‘Y’ then continue processing. Relevant data
validation and error messages should be considered in the program.

Exercise 11-6

AVERAGE: A program is to find the largest, smallest, and average value in a collection of numbers
entered from the keyboard. The program should prompt the user whether they want to continue
processing or not. If the answer is ‘N’ then the largest, smallest, and average will be displayed. If
‘Y’ then continue processing.

Page 207
CASE STUDY - PFEECAL6
Add a loop to the program from PFeeCal5 so that, after processing one customer, it asks if the
user wishes to process another customer (Y or N). Each customer should be processed until the
user choses ‘N’.

You will need to accumulate the following information, which should be displayed after the last
customer has been processed:
• The total number of customers.
• The number of regular and casual customers.
• The total cost for all personnel

This will require more variables. The program must now keep all the information about “this
customer” - the one being dealt with, along with information about running totals. Use a module to
output the daily statistics.

CASE STUDY – PFEECAL7


Now change PFeeCal6 to make the user input more visually appealing. Include a second loop on
the type of professional required. Let the user choose from a list of ‘N’, ‘O’, ‘P’ or ‘X’. The user
can then key in the number of days. choosing ‘X’ – along with ‘N’ ‘O’ or ‘P’. ‘X’ being used as
the sentinel to terminate the loop.

Page 208
CHAPTER 12 -
ITERATION: THE FOR LOOP

Upon successful completion of this chapter you will be able to:

• Write the pseudocode for the for loop structure

• Use the for statement in C code programs to solve a problem using a fixed looping structure

• Use nested for loops

• Determine which is the appropriate loop to use

Summary of new terms:

FOR loop - is also known as the fixed loop since it executes a known (or fixed) number of times.

Page 209
OVERVIEW
The FOR loop is a counted repetition loop or fixed loop because the set of tasks are repeated a
predetermined number of times. The loop is monitored by a counter variable, which is part of the
control structure. This chapter covers many uses of the for loop.

FOR LOOPS
The FOR loop is also known as the fixed loop since it executes a known (fixed) number of times. A
for loop is introduced by a FOR statement, which sets up the counter variable and specifies the
values it takes on as the loop executes.

FOR loops using pseudocode


The general format for the FOR loop in pseudocode is:

FOR Variable = Value1 TO Value2


statement(s)
ENDFOR

This structure is considered to be equivalent to:

Variable = Value1
WHILE Variable <= Value2
statement(s)
Variable = Variable + 1
ENDWHILE

The number of repetitions is determined by the difference between Value1 and Value2 + 1
eg. FOR Counter = 1 to 10 will repeat the loop ten times.

FOR loops in C Code


The compound For statement consists of:
1. The control statement "for".
2. Three expressions enclosed in brackets to control the loop, which consists of:
a. an initialisation of the index counter(which must be an integer).
b. determining whether or not to continue looping by stating the index counter <=the
counter limit.
c. a counter modifier, which changes the counter increment after each loop.
3. An open curly bracket {
4. The statements to be repeated separated by a semi-colon.
5. A closed curly bracket }

Page 210
An example is shown below:-

/*
* This will loop NumInputs times (assuming this has
* been input before the loop)and calculate the sum of
* numbers entered
*/
Sum = 0;
for (Count = 1; Count <= NumInputs; Count = Count + 1)
{
printf("Enter number: ");
scanf("%f", &Number);
Sum = Sum + Number;
}

Note in line 8, the increment is written as


Count = Count + 1
This is usually written in C code as
Count++

Example - Prices
The algorithm below displays the cost of 1 to 6 items priced at $1.23 each.

Pseudocode
PROGRAM Prices
OUT PUT 'Items', 'Price'
FOR NumItems = 1 TO 6
OUTPUT NumItems, NumItems * 1.23
ENDFOR
END Prices

C Code
/*
* Program Prices
* This program displays the cost of 1 to 6 items priced
* at $1.23 each.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
int NumItem = 0;

clrscr();
printf("\tItems\tPrice");

for (NumItem = 1; NumItem <= 6; NumItem ++)


{
printf("\t%i\t$%.2f", NumItem, NumItem * 1.23);
}

Page 211
printf("\nPress Enter to continue");
getch();
return 0;
}

Page 212
The output for this program is:

Items Price
1 1.23
2 2.46
3 3.69
4 4.92
5 6.15
6 7.58

The task which makes up the body of the loop and which is repeated each time the loop is
executed is:
OUTPUT NumItems, NumItems * 1.23

The condition (which is evaluated to determine whether or not the loop is repeated) tests whether
or not the value of NumItems is less than 6.
If the condition is TRUE, the statements in the body of the loop are executed. If the condition is
FALSE, the statements in the body of the loop are not executed and the program control passes to
the next statement after the ENDFOR statement.

The variable in the loop condition (NumItems) is assigned an initial value of 1 and each time the
body of the loop is executed, NumItems is incremented by 1.

Any statement inside the loop that changes the value of NumItems so that it never reaches 6 will
result in an unterminated loop (sometimes called an infinite loop). The program will then
continuously carry out the set of tasks inside the loop until the program is interrupted.

In order to prevent such interference with the control of the loop, you should not alter the value of
the loop control variable (NumItems in example above) within a FOR loop. Many programming
languages expressly forbid this.

The value of the loop counter cannot be assumed to have a particular value when the loop is
terminated, as different programming languages handle the counter in different ways.
The for statement like the while statement is used to perform repetitions, however the for statement
is more efficient than the while statement for incrementing and decrementing counters. The for loop
is more efficient with counters because it does evaluate the upper and lower limits of the counter
after each repetition. The for loop also has the added feature of avoiding infinite loops by not
executing the loop at all if it is not possible for the counter to move from the upper to lower limit or
vice versa e.g. counting from 1 down to 10 is not possible therefore the loop would not execute.

Page 213
CHOOSING THE APPROPRIATE LOOP
The three types of loops suit different situations depending on whether the number of repetitions is
known beforehand or whether the tasks need to be executed at least once.

Type of loop Number of Repetitions Set of tasks to be repeated


known beforehand at least once
FOR YES
REPEAT…UNTIL NO YES
WHILE NO NO

NESTED FOR LOOPS


There are no restrictions on the use of for loops within for loops. Likewise we can have a for loop
inside of a while loop or any other combination!

So we can (and often do) have constructions like:

for (i = 1 ; i <= 20 ; i++)


for (j = 1 ; j <= 5 ; j++)
printf("i = %i , j = %i",i,j);

Examine this program and see if you can understand how it works.
/* program ShowTime;
* Prints a multiplication table to a given limit.
*/

int main(void)
{
int Limit = 0;
int Row = 0;
int Column = 0;
int Answer = 0;

printf(‘Enter the upper limit for this times table: \n ‘);


scanf("%i", &Limit);

for (Column = 1; Column <= Limit; Column ++)


{
printf("%i", Column);
printf(‘| ‘); /* Print the bar and space. */
}
printf("\n——"); /* Leading dashes on the second line. */

for (Column = 1; Column <= Limit; Column ++)


{
printf(‘—’);
}
for (Row = 1; Row <= Limit ;Row ++)
{
printf("\n%i", Row); /* Label every row. */
printf(‘| ‘);
for (Column = 1; Column <= Row; Column ++)
{

Page 214
Answer = Row * Column;
printf("%i", Answer);
} /* end for loop for each column */
} /* end for loop for each row */
}

OUTPUT when Limit = 9

1| 2| 3| 4| 5| 6| 7| 8| 9|
————————————
1| 1
2| 2 4
3| 3 6 9
4| 4 8 12 16
5| 5 10 15 20 25
6| 6 12 18 24 30 36
7| 7 14 21 28 35 42 49
8| 8 16 24 32 40 48 56 64
9| 9 18 27 36 45 54 63 72 81

Exercise 12-1

1. Use a desk check to determine the output of the following PseudoCode.

(a) Counter = 0
FOR Loop = 5 to 8
Sum = 0
WHILE Sum < 30
Sum = Sum + Loop
Counter = Counter + 1
ENDWHILE
OUTPUT Sum, Loop, Counter
NEXT

(b) Write the C code for the above exercise.

Exercise 12-2

Write a C program to produce a 12x12 times table

1 2 3 4 5 6 7 8 9 10 11 12
--------------------------------------
1 | 1 2 3 4 5 6 7 8 9 10 11 12
2 | 2 4 6 8 10 12 14 16 18 20 22 24
3 | 3 6 9 12 15 18 21 24 27 30 33 36
..|

Page 215
...
12 | 2 24 36 48 60 72 84 96 108 120 132 144

Page 216
Exercise 12-3
What is the output for the following PseudoCode?

FOR Counter = 1 TO 3
FOR Loop = 1 TO 3
OUTPUT ‘A’
NEXT
FOR Fred = 100 TO 103
OUTPUT ‘B’
NEXT
OUTPUT NEWLINE
NEXT

Exercises – For Loops


For each of the following problems develop:

1. Algorithm using pseudocode


2. Desk check using known results
3. C code

Exercise 12-4

POST4F: Modify the design of POST2 to produce a table of charges with weights from 1 to 10 in
the first column and the corresponding charge in the second column

Weight Charge
1 $1.50
2 $3.00
… …
… …
9 $10.00
10 $10.00

POST2: Calculate the postage charge for a parcel when the weight of the parcel (in Kg) is entered
from the keyboard. Allow for a maximum charge of $10.00 no matter what weight in kg is entered.
The postage rate is set at $1.50 per kg.

Page 217
Exercise 12-5

TEMP4F: Produce a Fahrenheit to Celsius conversion table (with headings) as shown below for
values of 0 degreesF to 100 degreesF in steps of 5 degreesF. Use degC=(degF-32)/1.8

DegreesF DegreesC
0 -17.78
5 -15.00
10 -12.22


95 35.00
100 37.78

CHAPTER 12 – ITERATION STRUCTURE REVIEW QUESTIONS


1. What are the three iteration structures?

2. Which loop is known as the pre-test loop – while, repeat or for loop?

3. Which loop is known as the post-test loop – while, repeat or for loop?

4. Which loop is known as the fixed-test loop – while, repeat or for loop?

5. Which loop is the best loop to use for data validation?

6. Can an if statement be used for data validation – explain your answer?

7. Which loop is used when the processing must be done at least once?

8. Which is the best loop to use for a menu based program?

9. Is it possible to have a for loop within a while loop?

Page 218
CHAPTER 13 -
STRINGS

Upon successful completion of this chapter you will be able to:

• Declare and use strings in C programs

• Use the strcpy function in C to copy a string to a string variable

• Use the strcmp function in C to compare if one string is equal to, greater than or less
than another string

Summary of new terms:

String – an array of characters.


Null character - the character at the end of the string is set to 0, which is the null character,
which acts as a sentinel to mark the end of the string.
strcpy – the string copy function in C to copy a string to a string variable.
strcmp – the string comparison function in C to compare if one string is equal to, greater than or less
than another string.
strlen – the string length function returns the length of the string, which an integer result.

Page 219
OVERVIEW
In this chapter we look at a special kind of array: an array of characters, also called string.
Strings are just ordinary arrays, and you can treat them as such, but because they are so
important and so useful, C provides some special facilities for processing them. You have
already seen some of these (for example, string literals and the string input/output specifier %s).
This chapter will cover C’s string facilities more fully.

STRING FACILITIES IN C
There is no such thing as a string datatype in C. A string is declared as an array of characters.
Each character in the string is stored as a separate element of the array.

Nevertheless, provides many facilities to manipulate strings, where a string is treated as a single
entity, so strings almost appear to be a datatype in their own right.

String literals
You have been using string literals since your first C program. They are sequences of characters
enclosed in double quotes. Remember that some characters, not easily typed, can be
represented by escape sequences using the backslash character \. For example, \n represents
the new-line character, and \\ is used for backslash itself.

Declaring strings
A string is declared as an array of characters, for example:

char Country[20];

This declared a variable called Country to be an array of 20 characters.

Always declare the length of char arrays at least one more than the maximum length of the string
that might be stored there. This is because the end of the string is marked by a null character
('\0') immediately after the last character, forming part of the string. It is recommended that you
define the string length as a constant. For example

#define MAX_LEN 20

char Country[MAX_LEN];

A string does not have to fill the array in which it is stored. How, then, does the computer know
how long the string is? The character after the end of the string will be set to 0, which is the null
character. This character acts as a sentinel to mark the end of the string. It is not a character that
occurs in the string itself; there is no way to type it in, for example. Strings of this sort, with the
null character used as a sentinel at the end, are called “null-terminated strings”.

Because of the need to store the null terminator, a character string can store a string up to one
less than its declared length. So our Country string could be used for a string of up to 19
characters (not including the null terminator).

Page 220
Assigning to strings
It would be nice if we could just do a direct string assignment, using the assignment operator like
this:

Country = "Japan";

But C does not allow this (although many other programming languages do). This is a reminder
that strings are not a datatype in C. They are arrays.

There are three ways to change the value of a string:

• By assigning characters to individual elements

• By using scanf to input a new value

• By copying from another string

Let’s see how each of these would work.

1. Initialise each single character within the string:


Country[0] = 'J';
Country[1] = 'a';
Country[2] = 'p';
Country[3] = 'a';
Country[4] = 'n';
Country[5] = '\0'; /* the null character to end the string */

If the final assignment was omitted, then the value of the new string would be added to any
previous characters stored in the array.

For example, if “Australia” had previously been stored in the string Country, then the above first
5 lines were executed (omitting Country[5] = '\0'), the string held in Country would be
“Japanalia” because the last 4 letters of “Australia” would still be regarded as part of the string.

2. Use scanf to input a new string


You have already used scanf to input strings from the keyboard. In this case, it would be like
this:

printf("Enter the country: ");


scanf("%s",&Country);

3. String Copy Function


The first method above is a very tedious way of setting each individual character, and it is not
always appropriate to use the keyboard to change the value of the string, but there is a third
way, which is almost as easy as directly assigning the whole string. To do this, as already

Page 221
explained, we cannot simply use the assignment operator "=". The assignment operator can
only be used for a single element in the array. We must use the library function strcpy. It has
two arguments, the name of the array to copy the string into and a string to be copied, which can
either be a string literal or another array name. In our example we would use:

strcpy(Country,"Japan");

Note: use of strcpy requires the header file <string.h>.

The strcpy function is only one of many useful library functions provided by string.h. Others are
described next.

STRING FUNCTIONS
C provides a variety of functions that perform useful operations on strings. The strcpy function
has already been mentioned. If you want to use any of these in your programs, you should add
the directive:

#include <string.h>

to the other #include directives at the start of your program.

String copy – strcpy


This function takes two parameters. The first must be a string variable. The second can be either
a string variable or a string literal. The string in the second parameter is copied into the first. You
have already seen an example of its use:

strcpy(Country,"Japan");

String Length Function – strlen


This function takes a single string parameter (variable or literal) and returns an integer result,
which is the length of the string. If Length is an integer variable, then the statement

Length = strlen("Australia");

Would set Length to 9. The terminating null character is not included in the length of the string.

String Comparison Function - strcmp


We often need to know if one string is alphabetically before or after another string or if the
strings are equal. You cannot compare strings by using the usual relational operators, that is,
you cannot do a test like Country=="Australia".

To compare strings we use the strcmp function which has two arguments, the first string and a
second string, which can either be a string literals or array names.

strcmp(String1,String2)

Page 222
Page 223
The function strcmp compares String1 and String2 and returns

a negative value if String1 is alphabetically before String2


0 if the strings are identical
a positive value if String1 is alphabetically after String2.

A typical use of the strcmp function is in a sentinel controlled loop. For example to input a Name
and continue processing while Name<>"END". In C we need to compare Name with the string
"END" to see if they are identical. We want to perform the body of the loop when they are not
identical, that is when the comparison does NOT equal 0.
PseudoCode:
INPUT Name
WHILE Name <> “END”
{
…processing…
INPUT Name
}

C code:
printf("Enter the Name (END to finish) : ");
scanf("%s",&Name);
while (strcmp(Name,"END") != 0)
{
/* while loop body processing */
printf("Enter the Name (END to finish) : ");
scanf("%s",&Name);
}

Another typical use of the strcmp function is in printing words in alphabetical order. The
following example program inputs two words and outputs them in alphabetical order, looping
until the first input word is "END".

Example – strcmp and string sorting


/* Program Sort3 inputs 2 words and sorts them into alphabetical
* order, looping until the first word is END.
*/

#include <stdio.h>
#include <string.h>
#include <conio.h>

#define MAX_WORD_LEN 31

int main(void)
{
char Word1[MAX_WORD_LEN];
char Word2[MAX_WORD_LEN];

printf("Enter your first word (END to stop) : ");


scanf("%s",&Word1);
while (strcmp(Word1,"END") != 0)

Page 224
{
printf("Enter your second word : ");
scanf("%s",&Word2);
if (strcmp(Word1,Word2) <= 0)
printf("Alphabetical order %s %s\n", Word1, Word2);
else
printf("Alphabetical order %s %s\n", Word2, Word1);
printf("Enter your first word (END to stop) : ");
scanf("%s",&Word1);
}
printf("Press enter to continue");
getch();
return 0;
}

Converting a string to uppercase


A string cannot be converted to uppercase as a whole string. To do this you need to convert
each individual character to uppercase. For example to convert the name of a country to
uppercase you will need the following code:

#define MAX_LEN 20

char Country[MAX_LEN];
int Counter = 0;

for (Counter = 0; Counter < MAX_LEN; Counter ++)


{
Country[Counter] = toupper( Country[Counter]);
}

Example – Modular design Coin2

Let’s see how we can use a function to pass a string by looking at the example used previously,
Coin2. The program description for this example is repeated below:

DESCRIPTION

Design a program to calculate the value of a group of $2, $1, 50 cent, 20 cent, 10 cent
and 5 cent pieces. The number of each type of coin is entered at the keyboard and the
result is displayed on the screen in cents or dollars depending if a C or a D is entered.

INPUTS
Name Description Legal Values Data type Source
FiftyC Number of 50c coins entered Non-negative Integer Keyboard
FiveC Number of 5c coins entered Non-negative Integer Keyboard
OneD Number of $1 coins entered Non-negative Integer Keyboard
TenC Number of 10c coins entered Non-negative Integer Keyboard
TwentyC Number of 20c coins entered Non-negative Integer Keyboard
TwoD Number of $2 coins entered Non-negative Integer Keyboard
Choice C or D for answer in cents or dollars C or D Char Keyboard

Page 225
PROCESSING
calculate value in cents for C entered, dollars for D

OUTPUTS
value of coins in cents or dollars to the screen

MAJOR TASKS
input number of each coin
calculate total value in cents, adjust to dollars
if D is entered
output value

This program is not really long or complex enough to need modularisation, but let’s see how it
would work anyway.

The program specification already gives some clues about how the modules could be set up. In
the “major tasks” section, the operation of the program has already been broken down, basically
into input, processing and output. These could each be planned as a module. Thus there would
be three modules:

1. Get the data from the user


2. Calculate the result
3. Display the result

When we look at the objectives for modules, however, we see that there may be a flaw in this
design. It satisfies the first objective, because each module is doing a well-defined task. But it
fails the second, because a large number of values (counts for each type of coin) need to be
passed from the input module on to the calculation module.

However, all is not lost. The third module objective suggests that repeated processes should be
made into modules. Are there any repeated processes here? T’s not obvious from the program
description, but if you look at the pseudocode you see this:

INPUT TwoD, INPUT OneD


INPUT FiftyC, INPUT TwentyC
INPUT TenC, INPUT FiveC

The corresponding C code looks like this:

printf("Enter the number of two dollar coins: ");


scanf("%i",&TwoD);
printf("\nEnter the number of one dollar coins: ");
scanf("%i",&OneD);
printf("\nEnter the number of fifty cent coins: ");
scanf("%i",&FiftyC);
printf("\nEnter the number of twenty cent coins: ");
scanf("%i",&TwentyC);

Page 226
printf("\nEnter the number of ten cent coins: ");
scanf("%i",&TenC);
printf("\nEnter the number of five cent coins: ");
scanf("%i",&FiveC);

The repetition here is obvious, but can we give a clear description of what is required? For each
repetition, we first display a request on the screen, and then accept an integer from the
keyboard. The test of the request is different each time.

In more general terms, we could describe the operation of the proposed module like this:
“Display a prompt (supplied as a text string by the calling module), then read an integer from the
keyboard and return it to the calling program.”

This proposed module does a well-defined task, it needs minimal communication with the other
modules (it receives a text string and returns an integer) and it is used in many places in the
algorithm. It is an ideal candidate for being a module.

Module development
But how would it work in C? Ideally, once you have identified a module and its task, you should
go through the program specification procedure for the module, as you do for the program as a
whole. Let’s call the module Query. The specification would look something like this:

PROGRAM SPECIFICATION
DESCRIPTION
Display a prompt (supplied as a text string by the calling module), then read an integer
from the keyboard and return it to the calling program.
INPUTS
prompt string to be displayed
PROCESSING
display prompt string on the screen
read integer typed by user
OUTPUTS
Integer typed by user to the screen
MAJOR TASKS
display prompt string on the screen
read integer typed by user

DATA DICTIONARY
Variable Description Legal Values Source Type
Prompt Prompt string Any string Internal parameter String
Answer Number typed by user any value Keyboard, integer

Pseudocode
MODULE Query (Prompt)
Display prompt

Page 227
Read answer from keyboard
Return answer as function value

The following C code for the function is given just to give you an idea of how the function would
be coded. You are not expected to understand it at this stage, although you should be able to
see the correspondences between the pseudocode and the C code, and to understand how
printf and scanf are being used.

Page 228
C Code
/*
* PRE: Prompt contains a prompts string to be
* displayed on the screen.
* POST: Number typed by user is returned as the
* the value of the function.
*/

int Query(char Prompt[])


{
int Answer;

printf("\n%s ",Prompt);
scanf("%i",&Answer);
return Answer;
}

It is important to realise that this is not the whole program – it is just the definition of a single
function. The program, redesigned to use the function, is shown below. Again, there will be
things in this program that you will not understand yet. The details of passing arrays in functions
will be presented in the next chapter.

C Code
/*
* Program Coin2
* This program calculates the total number of cents from the
* number of each type of coin entered and displays either total
* cents or dollars depending on the choice requested.
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

int Query(char prompt[]); /* function prototype */

int main(void)
{
int Cents = 0;
int TwoD = 0;
int OneD = 0;
int FiftyC = 0;
int TwentyC = 0;
int TenC = 0;
int FiveC = 0;
char Choice =’ ‘;
float Dollars = 0;

clrscr();
TwoD =Query(“Enter the number of two dollar coins: ");
OneD =Query(“Enter the number of one dollar coins: ");
FiftyC =Query("Enter the number of fifty cent coins: ");
TwentyC=Query("Enter the number of twenty cent coins: ");
TenC =Query("Enter the number of ten cent coins: ");

Page 229
FiveC =Query(“Enter the number of five cent coins: ");
printf("\nEnter your choice of conversion");
printf("\nC for cents or D for dollars: ");
fflush(stdin);
scanf("%c", &Choice);

Choice = toupper(Choice);
Cents = (TwoD * 200) + (OneD * 100) + (FiftyC * 50)
+ (TwentyC * 20) + (TenC * 10) + (FiveC * 5);

if (Choice =='C')
{
printf("The total number of cents is: %i",Cents);
}
else
{
Dollars=Cents/100.0;
printf("The total dollar value of the coins is: ");
printf("%.2f",Dollars);
}
printf("\nPress Enter to continue");
getch();
return 0;
}

/*
* function Query
* PRE: prompt contains a prompts string to be
* displayed on the screen.
* POST: Number typed by user is returned as the
* the value of the function.
*/

int Query(char Prompt[])


{
int Answer;

printf("\n%s ",Prompt);
scanf("%i",&Answer);
return Answer;
}

Exercise 13-1

Create a C program that declares a character array with 20 elements called Name, allows the
user to input a name and then outputs the name.

Exercise 13-2

1) Type in the example program Sort3 and run the program with the following test data:
alpha beta
beta alpha

Page 230
Alpha beta
alpha Beta
END

2) Convert String1 and String2 to uppercase and test with the above data.

Page 231
Exercise 13-3

What string is printed in the following C code:


(a)
char Word[6];
int Pos = 0;
for (Pos = 0; Pos < 5; Pos=Pos+1)
{
Word[Pos] = 'Z';
}
Word[5] = '\0';
printf("%s",Word);

(b)
char Word[6];
int Pos = 0;
strcpy(Word, "Hello");
for (Pos = 0; Pos < 5; Pos=Pos+2)
{
Word[Pos] = 'A';
}
printf("%s",Word);

Exercise 13-4

STRING1: Enter the following program and run it.

/* Filename: STRING1.C
Name:
Purpose: Three ways of initialising arrays of char with strings
*/

#include <stdio.h>
#include <conio.h>
#include <string.h>

#define MAX_LEN 21
#define MAX_PCODE_LEN 5
#define MAX_STATE_LEN 4

int main(void)
{
char Name[MAX_LEN];
char Location[MAX_LEN];
char City[MAX_LEN];
char Postcode[MAX_PCODE_LEN];
char State[MAX_STATE_LEN];

clrscr();

strcpy(Name,"patrick raft");
strcpy(Location, "Memorial Drive");
Postcode[0] = '5';

Page 232
Postcode[1] = '0';
Postcode[2] = '0';
Postcode[3] = '0';
Postcode[4] = '\0';
printf("\nEnter City: ");
scanf("%s",&City);
printf("\nEnter state code: ");
scanf("%s",&State);

printf("\n\nThe details are\n\n");


printf("%s\n", Name);
printf("%s\n", Location);
printf("%s", City);
printf("\t%s", State);
printf("\t%s\n", Postcode);

printf(“Press enter to continue…”);


getch();
return 0;
}

Exercise 13-5
STRING2: Modify STRING1 and make the following changes at the end of the output
statements. After each change, insert a printf statement to check the results of the changes you
have made.
1)
a) Capitalise the first letter of the first and last name of "patrick raft"
b) Change the last name of "Patrick Raft" to "Patrick Rafter"
c) Change the name "Patrick Rafter" to "Patricia After"
d) Change the name "Patricia After" to "Pat"
2) Output the name "Pat" vertically on the screen
3) Use the string copy function to change the contents of location to "Football Park"
4) Declare another character array called title and input the value "Doctor" using the scanf
function.
5) Output to the screen, using the arrays already defined, "Doctor Pat is performing at Football
Park on Saturday night".

Exercise 13-6

BANK5S: Modify the BANK4W program as follows:


A loan officer requires a program to calculate the monthly repayment M on a customer loan by
entering from the keyboard the Customer Name ("END" will stop processing), Principal P,
at an annual interest rate of R% pa., over a period of T years and the Customer's monthly
income. The monthly repayment is calculated as M=P(1+RT/100.0)/(12T). Output the details
entered and the monthly repayment. On exiting the program, ie when a Customer Name of
"END" is entered, output the total principal of the loans accepted to the screen.

Page 233
Page 234
CHAPTER 14 -
ONE-DIMENSIONAL ARRAYS

Upon successful completion of this chapter you will be able to:

• Declare and use one-dimensional arrays in C programs

• Input and output elements of an array

• Use common array processing tasks such as searching through an array to find a minimum or
maximum value or total all values in an array

• Use arrays as parameters in functions

Summary of new terms:

Array - like a single row of the same type of data stored in memory, declared with a datatype, name of the
array and array size.
Element – a single value of an array that is stored at a particular location of the array accesed by an index
number.

Page 235
OVERVIEW
Arrays are such an important concept in programming that it is worth spending some time with them. This
chapter introduces some further ways to work with arrays (you have previously learnt about strings), and
presents some more examples of their use. In particular, it deals with the use of arrays in modular
programming.

Processing the elements of an array requires an operation that repeats a fixed number of times (once for
each element of the array). FOR loops do this, and there is generally a close relationship between FOR
loops and arrays.

INTRODUCING ARRAYS
An array is a way of dealing with a number of similar data items. If we have a large set of similar items we
do not need a separate variable for each item. Imagine if we had to store the rainfall for each day of the
year we would need 365 different variables eg a variable called Rainfall010103 to store the rainfall for
January 1 2003, a variable Rainfall020103 to store the rainfall for January 2 2003 etc. This would be very
tedious to have to work with variables this way. Imagine the calculation to find the average rainfall for a
year! To make programming easier, we can use a single array to store all of these items.

An array may be visualised as being a series of boxes, each containing information of the same data type
and each box being addressed sequentially. The array enables the use of a single name to refer to the data
with each data item in the array being referred to as an element. The elements of the array are identified
through the use of an index. (This will be discussed in detail later.) Using the rainfall example we could set
up an array to store the daily rainfall where each “box” contains the rainfall (mm) for a particular day:

Rainfall
1st element contains the rainfall for Jan 1 2003 2
2nd element contains the rainfall for Jan 2 2003 5
… …
365th element contains the rainfall for Dec 31 2003 0

Arrays are often used in programming. Some examples of things that arrays could be used for include:

• rainfall for each day of the year (an array of 365 integers)
• temperature for each day of the year (an array of 365 floats)
• test results for each student in a class (an array of integers)
• the text of a C program (an array of characters)
• the colour of each point on a computer screen (a two-dimensional rectangular array of 800×600
colours)

You have previously dealt with some data of this sort, but you have read and processed the items one at a
time. You have not had all the values in the computer’s memory at the same time. Arrays are the natural
way of doing this.

Page 236
In this section we learn how arrays work in C. We learn how to declare an array and how to access the
individual elements of an array by using an index.

Types of array
Arrays can be used to store numeric or character data. They can be either one-dimensional or multi-
dimensional. A one-dimensional array is a basically a single row of data stored in memory. A two-
dimensional array stores the data in rows and columns. In order to address the information in a multi-
dimensional array the location must be determined using both row and column positions, similar to
referencing a cell in a spreadsheet.

One-dimensional arrays
One-dimensional arrays in C have the following characteristics:

• The array must be declared with a single data type. Each element of the array has the same data
type. It can be of type integer, float or character.

• The array must be declared with a variable name.

• The array must be declared with a size. There are a fixed number of elements in the array.

• The array elements are numbered, beginning at zero. Using the array name followed by the index in
square brackets refers to individual array elements.

Declaring arrays
In order to use an array in a C program, you need to declare it first. This is much the same as for declaring
any other variable, except that you need to give the additional information of how big the array is (how
many elements it contains).

As mentioned above, an array declaration contains the data type, name and size.

For example:

float Rainfall[365];
int Result[50];
char Line[80];

The rules for array names are the same as for other variables. There is no limitation to the size of the array
except the available size and arrangement of the computer being used.

Initialising arrays
When the array is declared, space is set aside for the array on the stack. This memory is not necessarily
initialised to any value.

Page 237
As part of the array declaration, you can initialise the values of the elements. This is always a good idea,
and is required by your programming standards. If you know in advance what values the array will contain,
then you can set them up straight away.

Page 238
For example:

int Coins[6] = {5,10,20,50,100,200};

This declaration will set up an array called Coins with the elements containing the values (in cents) of the six
coins currently used in Australia.

More commonly, you will not know in advance what the initial values of the array elements should be. In
that case, the safest policy is to just set them all to zero. Since all elements will be initialised to zero you are
not required to write down 0 for every element in the array, you can just use the set notation {0} which will
initialise every element in the array to 0. The declarations given above would then be:

float Rainfall[365] = {0};


int Result[50] = {0};
char Line[80] = {0};

Note with char arrays (strings) the variable declaration is the only time you can use the assignment
statement as in the 3rd example above.

Array elements
The elements of an array can be used just like ordinary variables. You can assign values to them, read
values into them, use their values in expressions and calculations and display their values on the screen.

Using the array name, followed by the index in square brackets, refers to an array element. It is important
to remember that in C, the elements are numbered starting from 0.

Given the array declaration for coins above:

int Coins[6] = {5,10,20,50,100,200};

The elements and their values would be as follows:

Index

1st element of Coins Coins[0] 5


2nd element of Coins Coins[1] 10
3rd element of Coins Coins[2] 20
4th element of Coins Coins[3] 50
5th element of Coins Coins[4] 100
6th element of Coins Coins[5] 200

Although there are six elements in the array, the first element starts at index 0 and the last element is index
5. This is because in C the numbering always starts from zero.

Page 239
Often in a program the index you use will be a variable and it will often be the variable controlling a FOR
loop. We will now look at examples of processing elements in arrays.

INPUT AND OUTPUT OF ARRAYS


C provides no facilities for the input and output of whole arrays. Only individual elements of an array, one
at a time, can be input or output.

There is one exception to this rule – a one-dimensional array of characters (also called a string). These are
so common, and so important, that C does provide facilities for their input and output. You have already
met the %s specifier for the input and output of strings using scanf and printf. Strings are discussed in a
separate chapter.

For other types of arrays, input and output requires you to program the input or output of the individual
elements, one at a time. This can usually most easily be done using a FOR loop.

For example, the following program segment would display the array given above:

for (Index = 0; Index < 6; Index ++)


{
printf("\n\t%i\t%i", Index, Coins[Index]);
}

The loop will repeat six times, with the value of Index going from 0 to 5. Each time through the loop, the
printf statement will display the value of Index and the value of Coins[Index]. So the first time through the
loop, it will display 0 and the data held in Coins[0], which is 5. The second time, Index will be 1, and the
printf will display 1 and the data held in Coins[1], which is 10, and so on until the loop finishes when Index
reaches 6. The loop will not be executed for Index = 6.

Output is as follows:

0 5
1 10
2 20
3 50
4 100
5 200

Example– Output of an Array of Scores


Suppose you have an array of integers, set up like this:

int Scores[5] = {40,2,86,24,7}

and you want to output the values to the screen. First, you need to decide how you want the information
displayed. Do you just want the numbers listed on the same line, or do you want them in a vertical column?
If in a column, how do you want them to line up – do you want them left or right justified? C provides great
flexibility about this.

Page 240
Page 241
Let’s try several possibilities. The following code will display the array elements all on the same line:

for (Count = 0; Count < 5; Count ++)


{
printf("%i ",Scores[Count]);
}
printf("\n");

The FOR loop uses a variable Count, which runs from 0 to 4 inclusive. The body of the loop contains a
single printf statement, which prints element Count of the array Score. There is no \n in this printf, so the
elements will be displayed on the same line, like this:

40 2 86 24 7

Notice the blank space after the %i (but still inside the format string). This is required to separate the
elements.

Without the blank spaces the scores would appear like this:

40286247

The final printf (after the loop) outputs a new line, so that further output will appear on the next line of the
display.

The following variation of the program will display the array elements in a vertical list:

for (Count = 0; Count < 5; Count ++)


{
printf("%i\n",Scores[Count]);
}

We have added a new line after each element. The final printf statement is no longer necessary. The
numbers will be displayed like this:

40
2
86
24
7

When numbers are displayed in columns, it is customary to right-justify them. This can be achieved by
adjusting the format specifier, like this:

for (Count = 0; Count < 5; Count ++)


{
printf("%2d\n",Scores[Count]);
}

Page 242
This forces every number to take up two characters on the display. They will look like this:

40
2
86
24
7

Example– Input of an Array of Scores


Similar techniques, using scanf, can be used to input the values of an array from the keyboard.

If all we wanted to do was read in the five values of the Score array, we could do it like this:
for (Count = 0; Count < 5; Count ++)
{
scanf("%i",&Scores[Count]);
}

Here we have used scanf to input the value of each element in turn. Note the use of & with the scanf
variable, as you have used before when inputting a variable.

The problem with this solution is that whoever is typing the input will not know what to type. The program
will just stop, waiting for input. It will not continue until five numbers have been typed. We need to display
prompt messages telling the user what is required.

There are two alternatives.

1. We could display a single prompt at the beginning, as shown here:

printf("Please type 5 integers separated by spaces: ");


for (Count = 0; Count < 5; Count ++)
{
scanf("%i",&Scores[Count]);
}
The program will not continue until 5 integers have been entered.

2. We could prompt separately for each element of the array, as shown here:

printf("Please type the scores\n");


for (Count = 0; Count < 5; Count ++)
{
printf("Scores[%i]: ",Count);
scanf("%i",&Scores[Count]);
}

Can you see the point of the following variation?

printf("Please type the scores\n");


for (Count = 0; Count < 5; Count ++)
{
printf("Scores[%i]: ",Count + 1);

Page 243
scanf("%i",&Scores[Count]);
}

Here the prompt numbers the scores starting from 1 (by using Count + 1 as the index), which some users
may find more natural rather than entering from element 0.

COMMON ARRAY M ANIPULATION TASKS


Example – Total an Array of Scores

To find a total of the scores entered in the above Scores example we could use the following C code:

TotalScores = 0;
for (Count = 0; Count < 5; Count ++)
{
TotalScores = TotalScores + Scores[Count];
}
printf(“The total of all scores is %i\n”, TotalScores);

In this example we only had 5 scores to process. More realistically, there could be a class of up to a
maximum of 30 students’ scores to process. If we have defined a constant MAX_STUD as 30, the array
Scores would be initialised as:

int Scores[MAX_STUD] = {0}

Quite often not all the array elements are used at all times. The array Scores allows for 30 students’ scores
to be entered but there may only be 20 students in the class. The number of students should be input at the
start of the program, eg NumStudents. The for loops used within the program would therefore be coded to
loop more efficiently by using a maximum index of NumStudents-1 (subtract 1 because the index starts at
0). The C code to find the total of scores would now be:

TotalScores = 0;
for (Student=0; Student<NumStudents-1; Student++)
{
TotalScores = TotalScores + Scores[Student];
}
printf(“The total of all scores is %i\n”, TotalScores);

The code in C is complicated by the fact that the indexing starts at 0 and therefore ends at NumStudents-1.
This means that if there were 20 students in the class (NumStudents = 20) then the indexing is from 0 to 19
ie 20-1.

Page 244
Example – Search an Array of Scores for the Maximum
To search for and print the maximum score (MaxScore) and the corresponding index to record which
student had the maximum score (MaxStudent). This uses similar logic to a previous example, Sort3,
explained in while loops.
C code:
MaxScore = Scores[0]; /* set max score to first element */
MaxStudent = 0; /* set MaxStudent to first student */
for (Student=1; Student<NumStudents-1; Student++)
{
if (Scores[Student] > Maximum)
{
MaxScore = Scores[Student];
MaxStudent = Student;
printf(“Student %i achieved the maximum score %i\n”,
MaxStudent,MaxScore);
}
}

Note that the for loop starts with the second element ie Student = 1.

Example– Search an Array of Scores for a particular value


To search for a user requested score (ScoreWanted) and stop processing once the first occurrence is
found, we could use the following C code:

printf(“/nEnter the score wanted: “);


scanf(“%i”,&ScoreWanted);
Student = 0;
while (Student<MAX_STUD-1 && Scores[Student]<>ScoreWanted)
{
Student = Student+1
}
printf(“\nStudent %i was the first student to achieve
%i”,Student,ScoreWanted);

The logical expression in the while loop includes a test Student<MAX_STUD-1 to ensure that we don't go
past the last element in the array - element 29. MAX_STUD was defined as 30 and when the array was
declared the array elements start at 0 and go up to 29. In fact it is not necessary, or recommended, that
you go beyond the last element, which can actually contain other data.

Exercise 14-1

1. Declare an array of Scores to hold 5 integers.


2. Enter Scores (1-100) into each element of the array.
3. Print each score.

Page 245
Exercise 14-2

Modify the previous question to print each score and its corresponding grade where the grades are
determined as follows.

>= 85 D
>= 75 C
>= 50 P
< 50 F

Exercise 14-3

1. Declare an array of 7 floats to store the maximum temperature for each day of the week.
2. Enter the maximum temperature for days 1-7 (Sun – Sat).
3. Calculate and print the average temperature.
4. Find the highest temperature for the week using the following algorithm:

MaxTemp = Temp[0]
FOR Index = 1 to 6
IF Temp[Index] > MaxTemp
MaxTemp = Temp [Index]
END IF
END FOR

Exercise 14-4

1. Declare an array of 7 floats to store the maximum temperature and initialise each element to 30.
2. For each day when the temperature is not 30, input the day number (1-7) and the temperature for
that day. Terminate when 0 is entered as the day number.
3. Print the temperatures for each day of the week.

Page 246
ARRAYS AS PARAMETERS
Code to display an array, using the methods described in the previous section,. would be useful in many
programs. We should consider making it into a module, a function that we can use over and over again.

We would want such a module to be as general as possible. The code given in the last examples above will
only work for arrays of five. In the output example, the justification will only work for numbers up to 99.
Ideally, we would like a function that would work for any size of array, and for any size of number.

By writing such a function, we are effectively extending the C language. In its raw form, as we said before,
C does not provide facilities for the input and output of whole arrays. With our proposed new functions, it
will. We see here another important application of the module concept: modules can be used to extend the
facilities offered by the base programming language.

However, before we can write such modules, we need to look at how arrays are passed as parameters.

Formal array parameters


A function can be written to accept an array as a parameter. Suppose we wanted to write a function called
OutputArray to output the values of an array. We want to pass the array to the function as a parameter.
The function prototype would look like this:

void OutputArray(int EgArray[])

The square brackets after the parameter name EgArray tell the compiler that EgArray is an array. The int
tells the compiler that it is an array of integers.

Actual array parameters


When a function with an array parameter is called, the name of a declared array is given as the actual
parameter. During the call, this array will be substituted for the formal array named in the prototype.

For example, if we wanted to call the function prototyped above with the array Scores defined previously,
we would use:

OutputArray(Scores);

Page 247
Example – OutputArray function
We are now in a position to make our previous code for outputting an array into a function. We can start
with something like this:

void OutputArray(int Array[])


{
int Count = 0;

for (Count = 0; Count < 5; Count ++)


{
printf("%2d\n",Array[Count]);
}
}

This function will work, but it will only work for arrays of five elements. If it is called with a larger array, it
will display only the first five elements, and if it is called with a smaller array, it will be referring to memory
locations that are outside the array, which is likely to give either an error, or peculiar results.

We can make the function more general by making the size of the array a parameter. It will be an integer
parameter. Let’s call it ArraySize. Then, instead of counting from 0 to 4, becomes count from 0 to n-1.
The function would look like this:

void OutputArray(int Array[], int ArraySize)


{
int Count = 0;

for (Count = 0; Count < ArraySize; Count ++)


{
printf("%10d\n",Array[Count]);
}
}

To use the function on our Scores array, we need to call it like this:

OutputArray(Scores,5)

Here we tell the function which array to use (OutputArray) and we tell it how big the array is (5).

Example - InputArray
The coding of a function to input arrays is similar to the OutputArray example. Before you look at the
function, however, you should be aware of a peculiarity about array parameters.

Earlier you learned that, when a parameter is passed to a function, the function uses a copy of the value. If
the function changes the parameter, the change will have no effect in the calling program. You saw
examples of this in Chapter Functions.

Page 248
This copying process does not happen with array parameters. When an array is passed as a parameter, it is
not copied. The function, while it is running, has direct access to the array that is passed to it. It can
therefore both use and change the values of the array elements.

This is crucial for our function to input an array, because this function will need to change the values of the
array elements to the values it has input from the keyboard.

The InputArray function will look like this:

void InputArray(int Array[], int ArraySize)


{
int Count = 0;

for (Count = 0; Count < ArraySize; Count ++)


{
printf("Element[%i]: ",Count);
scanf("%i",&Array[Count]);
}
}

The function has two parameters. The first (Array) is the array to be input, and the second (ArraySize) is
the size of the array. The function will input n elements into the array Array.

Although the function prompts individually for each element, it does not say initially what the elements
mean. This will vary from call to call, and it is therefore the responsibility of the calling program to tell the
user what is expected before InputArray is called. For example:

printf("Please type the scores\n");


InputArray(Scores,5);

WORKED EXAMPLE
Example - arrays

As a further illustration of the use of for loops, arrays, and modular design, let’s develop a more complex
example.

We’ll develop a program that will read an array of numbers. The values will be displayed. It will then find
the smallest number, the largest number, and the average of the numbers. These results will then be
displayed.

PROGRAM SPECIFICATION

Description
A program to input and display, a set of numbers, and to find and display the minimum, maximum and
mean of the numbers.

Page 249
Inputs
The number of numbers to be processed
The numbers themselves
Processing
Identify Minimum
Identify Maximum
Calculate mean
Outputs
The numbers originally input
The Minimum
The Maximum
The Mean
Overall Tasks
Input numbers
Calculate Minimum, Maximum, Mean
Output numbers, Minimum, Maximum, Mean
Known results
Input: 3, 44, 67, 32
Output: Numbers: 3, 44, 67, 32
Minimum: 3
Maximum: 67
Mean: 36.5
Pseudocode
Program Analyse
DO GetCount
DO InputArray
DO GetMinimum
DO GetMaximum
DO GetMean
DO OutputArray
OUTPUT Minimum
OUTPUT Maximum
OUTPUT Mean
END Analyse

The main program is little more than a sequence of calls to other modules. We also need pseudocode for
each of the modules.

MODULE GetCount
WHILE Count < 0 OR Count > 20
OUTPUT error message
INPUT Count
ENDWHILE
RETURN Count
END GetCount

Page 250
MODULE InputArray
FOR Index=0 to Count-1
INPUT Array[Index]
ENDFOR
END InputArray

MODULE OutputArray
FOR Index=0 to Count-1
OUTPUT Array[Index]
ENDFOR
END OutputArray

MODULE GetMinimum
Min=Array[0]; {set min to first element}
FOR Index=1 to Count-1
IF Array[Index]<Min
Min=Array[Index]
ENDIF
ENDFOR
RETURN Min
END GetMinimum

MODULE GetMaximum
Max=Array[0]; {set max to first element}
FOR Index=1 to Count-1
IF Array[Index]>Max
Max=Array[Index]
ENDIF
ENDFOR
RETURN Max
END GetMaximum

MODULE GetMean
Sum=0
FOR Index=0 to Count-1
Sum = Sum+Array[Index]
ENDFOR
RETURN Sum/Count
END GetMaximum

The modules GetMinimum and GetMaximum may need some explanation. The job of finding the minimum
of an array is done in the same way as you would do it yourself, by hand. Suppose you had the set of
numbers

20
25
10
18

and you wanted to find the minimum. You would scan down the list, keeping track of the “smallest found
so far”. So at the top, the smallest found so far is 20. The next number is 25, which is bigger than 20, so
the smallest so far is still 20. The next number is 10, which is smaller that the smallest so far (20), so the

Page 251
smallest so far changes to 10. The last number, 18, is larger than 10, so we finish the scan with a minimum
of 10.

The pseudocode for GetMinimum works in just this way. The “smallest so far” value is kept in the variable
Min. This is initially set to Array[0]. We then look through the remaining elements of the array, one by one.
If any is less than Min, then it is smaller than anything we have seen so far, so we copy its value into Min.
By the time we reach the end of the array, Min has the value of the smallest element.

GetMaximum works in the same way, except that it keeps track of the largest number found so far.

The C code for the program begins on the next page.

Page 252
/**********************************************************************
* Author | DMIT
* Date written | 2003
* System | MS-DOS
*---------------+
* Functions | Calculate the minimum, maximum and mean value
* | of an array of integers.
*/

#include <stdio.h>
#include <conio.h>

#define MAX_SIZE 20

int GetCount(int Limit);


void InputArray(int Array[], int ArraySize);
void OutputArray(int Array[], int ArraySize);
int GetMin(int Array[], int ArraySize);
int GetMax(int Array[], int ArraySize);
float GetMean(int Array[], int ArraySize);

/******************************************************
*/
int main (void)
{
int Array[MAX_SIZE] = {0};
int Count = 0;
int Min = 0;
int Max = 0;
float Mean = 0;

clrscr();
Count = GetCount(MAX_SIZE);
InputArray(Array,Count);

Min = GetMin(Array,Count);
Max = GetMax(Array,Count);
Mean = GetMean(Array,Count);

OutputArray(Array,Count);
printf("Minimum is %4d\n",Min);
printf("Maximum is %4d\n",Max);
printf("Mean value is %6.2f\n",Mean);
printf("Press any key to continue");
getch();
return 0;
}

/******************************************************
* function GetCount obtains a validated count of numbers from the user.
* PRE Limit is the largest value of count
* POST Count is an integer between 1 and Limit
*/
int GetCount (int Limit)
{
int Count = 0;
printf("How many numbers do you have to enter(1..%i): ",Limit);

Page 253
scanf("%i",&Count);
while ((Count < 1) || (Count > Limit))
{
printf("How many numbers do you have to enter(1..%i): ",Limit);
scanf("%i",&Count);
}
return Count;
}

/******************************************************
* function InputArray gets the elements of the given array of integers
* PRE n is the number of elements to be read
* POST Numbers have been read into the first n elements of Array
*/
void InputArray (int Array[], int n)
{
int Index = 0;

for (Index = 0; Index < n; Index++)


{
printf("Element[%i]: ",Index);
scanf("%i",&Array[Index]);
}
return;
}

/******************************************************
* function OutputArray displays the elements of the given array of integers
* PRE Array is an array of integers
* n is the number of elements in Array
* POST none
*/
void OutputArray (int Array[], int n)
{
int Index = 0;

printf("Array: ");
for (Index = 0; Index < n; Index++)
{
printf("%4d",Array[Index]);
}
printf("\n");
return;
}

/******************************************************
* function GetMin finds the minimum value in an array of integers
* PRE Array is an array of integers
* n is the number of elements in Array
* POST return value is the minimum element in the array
*/
int GetMin(int Array[], int n)
{
int Index = 0;
int Min = 0;

Min = Array[0];
for (Index = 1; Index < n; Index++)

Page 254
{
if (Array[Index] < Min)
{
Min = Array[Index];
}
}
return Min;
}

/******************************************************
* function GetMax finds the maximum value in an array of integers
* PRE Array is an array of integers
* n is the number of elements in Array
* POST return value is the maximum element in the array
*/
int GetMax(int Array[], int n)
{
int Index = 0;
int Max = 0;

max = Array[0];
for (Index = 1; Index < n; Index++)
{
if (Array[Index] > Max)
{
Max = Array[Index];
}
}
return Max;
}

/******************************************************
* function GetMean finds the mean value of an array of integers
* PRE Array is an array of integers
* n is the number of elements in Array
* POST return value is the mean value of the array
*/
float GetMean(int Array[], int n)
{
int Index = 0;
float Sum = 0;

for (Index = 0; Index < n; Index++)


{
Sum = Sum + Array[Index];
}
return Sum / n;
}

PASSING A CHARACTER ARRAY TO A FUNCTION.


You have already learned about passing arrays to functions. You learned that a function could change the
elements of an array passed to it as a parameter. This is like the “pass by reference” parameters that we
have previously covered.

When working with arrays the following general rule should be remembered:

Page 255
An array name when used on its own undergoes an automatic data type conversion to a pointer to the
element data type, except when used with the & and sizeof operator.

We declare a string array

char Surname[21];

If we wish to pass an array to a function, a pointer to the array is copied. This takes up much less space
than copying the whole array.

We have seen this used in scanf

scanf ("%s", Surname);

Note that because of the exception in the above rule the scanf example could be written as

scanf ("%s",&Surname);

Because surname is an array, the effect is the same whether or not the & is included. Without the &, a
pointer to the array is passed anyway. Equally, in the examples in the previous chapter, we could have
included the & in front of the array name when we used it as a parameter.

The function receives a pointer to the start of the array. This is most easily specified with an array
specification as shown below.

Example – Array to function

/*****************************************************
Program to demonstrate passing an array to a function
******************************************************/

#include <stdio.h>

void GetName(char Name1[]);


void PrintName(char Name2[]);

int main(void)
{
int Repeat = 0;
char Name[11] = {0};

for (Repeat = 0; Repeat < 5; Repeat++)


{
GetName(Name);
PrintName(Name);
}
}

/*
* Function GetName

Page 256
* PRE: Nothing
* POST: Name1 contains a string entered at the keyboard
*/
void GetName(char Name1[])
{
printf("\n\nPlease enter your name (max 10 characters) :");
scanf("%s",Name1);
}

/*
* Function PrintName
* PRE: Name2 contains a string
* POST: Name2 has been displayed
*/
void PrintName(char Name2[])
{
printf("\nHello %s",Name2);
}

Page 257
Exercise 14-5

BANK5A:
Modify Bank5S to include a function to Input the customer’s name.

Exercise 14-6

ANIM5A:
Modify Anim4R to include a menu option to output all details entered so far and the corresponding fees.
Arrays will be required to store Animal Type, Hours, Owner Type and Fee.

Exercise 14-7

ANIM5A2
Modify Anim5A to include a function to output the average Fee on quitting the program. You should use
your array that holds the Fee to calculate the average.

Exercise 14-8

1. Write a function called SetArray. It has two parameters, an integer array Array and an integer
NumElements. It should set the first n elements of Array to 1, 2, 3, … n. Remember that the array
elements are indexed from 0.

The prototype of this function would be:

void SetArray(int Array[], int NumElements);

2. Write a function called Output Array that will output the elements of the above array.

The prototype of this function would be:

void OutputArray(int Array[], int NumElements);

3. Write a function to input the number of elements of the array and validate this is between 1-20.

The prototype of this function would be:

int InputNumElements(void);

Page 258
Exercise 14-9

This program asks the user for six positive integers. It then lists the integers and notes whether each is
above, below or equal to the mean.
Code the following pseudocode in C and get the program working.

Pseudocode
DEFINE MAX_NUM = 6
Declare array Numbers[MAX_NUM]
Sum=0
FOR Count = 1 TO MAX_NUM
INPUT Numbers[Count]
Sum=Sum + Numbers[Count]
ENDFOR
Mean=Sum / MAX_NUM
FOR Count = 1 TO MAX_NUM
OUTPUT Numbers[Count]
IF Numbers[Count] < Mean
OUTPUT “below mean”
ELSE
IF Numbers[Count] > Mean
OUTPUT “above mean”
ELSE
OUTPUT “Mean”
ENDIF
ENDIF
ENDFOR

Page 259
CASE STUDY - PFEECAL8
Change PFeeCal7 to include the final table.

You will need to declare three arrays to hold the data for the Customer ID, Customer type and Customer
Cost.

CHAPTER 14 – ARRAYS REVIEW QUESTIONS


What is the special name given to an array af characters?

Which character marks the end of an array of characters?

Can you assign a string to a variable, for example Name = = “Julie”? True or false?

How many different datatypes can you store in an array at any one time?

Processing of arrays often uses which loop – while, repeat or for?

Arrays can only hold a maximum of 100 elements. True or false?

Page 260
CHAPTER 15 -
COMBINING TECHNIQUES

Upon successful completion of this chapter you will be able to:

• Combine all techniques learnt to solve more complex problems:

o Use various datatypes, constants and variables


o Use a modular structured design approach using combinations of sequence, selection
and iteration structures
o Write Functions in C
o Use Arrays to store data and process data on exit of a program

Page 261
OVERVIEW
In this chapter, we consider the complete set of programming skills you have learned during the
previous chapters, and look at how they can be used in combination to solve larger problems.

QUICK REVIEW
Consider the various programming techniques you have learned in the previous chapters:
• Systematic program development
• Systematic documentation
• Datatypes, constants and variables
• Modular design
• Functions
• Selection
• Iteration
• Arrays
These techniques now form a set of tools that you can draw on to solve programming problems.
You only need to select the right tool for the right job.

Program development
If you go about program development in the way that you have learned, the choice of appropriate
tools will usually be obvious. Remember the following:
• You cannot write a program if you do not understand what the program is supposed to
do. That is why the program specification is so important. Writing the specification helps
to clarify in your mind the task to be performed.
• Devise some known results – sample data whose output results you know. If you don’t
know how the program is supposed to behave, you will not know it is working correctly.
• Use stepwise refinement. This approach naturally leads to a modular design. Break the
larger task up into manageable parts. Each part then becomes a module. Even if the
overall task is a large one, you only need to deal with one piece at a time.
• When designing the details of an algorithm, think clearly about what the program has to
do. How would you do it, if you had to do it by hand?
• What variables will the program need in order to perform its work? Start developing a
data dictionary, which will develop further during the testing of your algorithm.
• Develop the algorithm using pseudocode.
• Desk-check your algorithm. This is a most important step. When you desk-check, behave
like the computer. Follow each step literally and slavishly. Assume nothing except what
the algorithm tells you.

Page 262
• Once your algorithm is designed and checked, you can code it in C. The only errors you
should have to worry about now are syntax errors.
• Once the program is running, check it with the known results. Check the program as
thoroughly as you can. If you find logic errors (incorrect results, infinite loops, etc) then
desk-check the program to discover where it is going wrong. Try to make your program
NOT work!
It is worth knowing that the techniques you have been studying are much the same for all
programming languages. The programming techniques (selection, loops, functions, etc) that you
have learned here will are directly transferable to any other programming language you may learn
in the future.
In the above list, only the second-to-last point will vary from one programming language to
another. All the rest is independent of which language you are using. If C has been your first
programming language, you will find others much easier.

Exercises – Combining Techniques


The following exercises are more complex versions of problems you have seen before. In
developing programs for these exercises, you will have the opportunity to use all the techniques
you have previously learnt.

For each exercise write the modular design pseudocode, structure chart and C code.

Exercise 15-1

POST6: A program requires the weight of a parcel in Kg (0.1 - 25kg) and the parcel type (S-
surface, C-courier or E-express) to be entered from the keyboard. Validate each of the inputs as
they are entered. The charge is set at $1.50 per kg. There is a maximum charge of $10 for surface
parcels and a maximum charge of $20 for courier and express parcels. There is also an additional
surcharge of $8 for courier parcels and a surcharge of $5 for express parcels. The parcel type and
charge is to be output to the screen. Allow for continued use of the program by prompting for
Y/N. On exiting the program, the weight, parcel type and charge for each parcel is to be output to
the screen. Arrays must be kept to store these values. Output statistics of the total weight of each
parcel type and the total charges of each parcel type.

Exercise 15-2

ANIM6: A program accepts the number of hours (0.5-4) of the consultation, the animal type (B-
bird, C-cat, D-dog, O-other) and the type of owner (N-normal or F-farmer) from the keyboard.
All inputs must be validated. The consultation fee for a vet is obtained by multiplying the number of
hours by the hourly rate. The hourly rate is set at $20 for birds, $25 for cats, $30 for dogs and
$40 for other animals. There is a 20% discount on the consultation fee for farmers. Output all the
inputs and the consultation fee to the screen. After consultation details are entered the vet is to be
given the chance to continue or terminate the program. Once the consultation session finishes, the

Page 263
number of consultations for each category of animal, the number of consultations for each
category of owner and the total charge are displayed on the screen. The hours, animal type and
fee grouped for each owner type is also to be output to the screen. Arrays must be kept to store
these values.

Exercise 15-3

BANK6: A loan officer requires a program to calculate the monthly repayment M on a customer
loan by entering from the keyboard the Customer Name ("END" stops processing), the principal
P (1000-50000), the term T of the loan (5, 10 or 15 years) and the loan type (C-car, I-
investment or S-staff). All inputs (except for Customer Name) are to be validated. The monthly
repayment is calculated as
M=P(1+RT/100)/(12T)
where the annual interest rate of R% pa. is set at 10% for car loans, 13% for investment loans and
8% for staff loans.

All inputs and the monthly repayment is output to the screen. When a Customer Name of "END"
is entered, the program will stop and output the principal, term and monthly repayment grouped
into loantype for each customer. Arrays will be needed to store this information. The program
should also output the accumulated principal and number of each type of loan.

Page 264
CHAPTER 16 -
TEXT FILES

Upon successful completion of this chapter you will be able to:

• Open a text file for reading, writing and appending.

• Write algorithms to sequentially process all records in a text file

• Understand the use of the end of file marker.

Summary of new terms:

Field - a collection of data given a name to indicate the nature of the data and distinguish it from other
collections.
Record a set of fields.
Data file - a collection of data that is stored in a secondary storage device. Often organised as a collection
of records.
Text file - a data file that contains a sequence of ASCII characters.
End Of File marker – a marker indicating the end of the file. Usually a particular ASCII character.
Read - To accept input from a data file.
Write - To output data to a new data file.
Append - To output data to the end of a data file.

Page 265
OVERVIEW
This chapter covers the the use of simple text files. Use special C commands to open and close files and to
read, write and append files. It will also look at the processing of data in files.

WHAT IS A FILE?
A data file is in essence a collection of data that is stored in a secondary storage device. Data files can be
stored in two ways: as either a text file or binary file. A text file contains a sequence of ASCII characters
where a character is any letter (A to Z and a to z), digit (0 to 9) or symbol (! # % & ( _ + ~ { | : " < ? are
some examples). A binary file can also contain non-ASCII characters i.e. characters stored in more than
one byte. This chapter will only cover text files.

The characters in a text file are normally sensibly collected or grouped to form fields. Fields usually have a
name to distinguish them from one another and to indicate the nature of the data that the field may contain.
For example, a field named postcode could have the value of any postcode and a field named colour could
have the value of any colour.

A set of fields that have some relationship to one another constitute a record. For example, the fields
surname, given name and address constitute a record of information sufficient to mail the person something.

A collection of records of similar structure and nature of data constitute a file. Hence one or more records
as described above would constitute a file.

A Data File example would be the details of MEMBERS in a club:

A file which contains details of MEMBERS of a club would typically be set up so that each record has the
fields surname, given name and address with a maximum of 15, 20 and 44 characters allocated as the
number of characters respectively the fields may contain. Furthermore, the field address may be divided into
subfields of 20, 20 and 4 characters for street, suburb and postcode.

WHY USE A FILE?


There are a number of reasons why data files are used in programming. Using a file allows the data to be
separate from any program. This allows the data to be modified or updated without involving
modifications to any programs. This of course helps to maintain the integrity of the data. Imagine the
situation where the same data is repeated within 4 or 5 programs. A change to the data means being careful
to change all 4 or 5 occurrences whereas using a file means changing only one occurrence of the data. This
leads us to another advantage of using a file - the fact that many programs can now use the data.

How Are The Records Organised?


As far as C is concerned, files are nothing more than a stream of bytes (hence the appearance of the word
stream in the literature). Programs you use to look at text files (such as notepad) make you think that files
are organised into lines but really the lines are only there because of the way the program you have used to
view the file has interpreted the stream of characters, in particular the \n (newline) character.

Page 266
When programming in C it is useful for you to force yourself to think of a file as one long sequence of
characters NOT as a collection of records even though logically that is what the file may contain.

The End Of File Marker


Further to the method of organisation is the idea of a marker indicating the end of the file. Every data file
contains the marker, referred to as the End Of File marker or EOF for short. It is a physical marker
appearing directly after the last record. If the data file has been created but no records have actually been
written to the file then all it would contain is the EOF marker.

USING DATA FILES IN PROGRAMS


There are three basic tasks that a program that wishes to use a data file will need to do.

Firstly, the program must prepare the file for usage, often called opening the file. This involves many
background tasks by the computer. For example if the file already exists it is at this stage that the operating
system will do the job of finding the file on the secondary storage device.

Secondly, the program will either read data from the file or write data to the file. Since a program can work
with many data files, when the program wishes to write or read to a file it must in some way indicate which
file it wants to work with.

Thirdly, before the program finishes it must indicate to the computer that it has finished with the data file, that
is, it must properly close the data file. This again causes many background tasks to be performed by the
computer for example the correct recording of the EOF marker.

OPEN A FILE
For example, assume that we have a data file called MEMBERS as in the previous example. In C we need
the following code to open a file:

1. FILE *InFile;
2. InFile = fopen("MEMBERS", "r");

In C, files are opened by connecting a variable of type FILE * to the file actually on the disk. The variable
InFile then identifies which file is being used later in the program. *InFile is a pointer to the file, ie the
location of the file.

Line 2 indicates that the file to be used is called MEMBERS and that it will be used for input into the
program, that is, it will provide data for the program. This means that data from the file will be read by the
program, NOT written to, indicated by “r”. If the MEMBERS file does not exist a NULL error is returned.
We will see in a later example how this can be used for error checking to make sure processing of the file
does not continue unless the file has been successfully opened.

Files can be also be opened for


“w” writing to a file
“a” appending to a file

Page 267
Note if writing to an existing file, the original contents of the file will be removed and replaced with the new
contents.

READ FROM A FILE


All input so far has been from the keyboard, by default, the standard input device stdin. When input is via a
file you need to use special file commands to change the default keyboard input scanf to file input using
fscanf.

fscanf(InFile, "%s%s%s", SurName, Name, Address);

This statement is reading information from the file InFile, which is in fact reading 3 strings SurName, Name
and Address from the file MEMBERS. It is reading from the file MEMBERS because of the statement used
in line 2 above, where variable InFile was linked to the file MEMBERS when it was opened.

CLOSE A FILE
To close a file, a simple statement is used, which again references the MEMBERS file via the variable InFile

fclose(InFile);

The above example is for C but actually all programming languages contain commands that do similar tasks.

PROCESSING THE DATA IN A FILE


Before any processing of data from the file begins, the program should check to see if the file has
successfully been opened.

Checking For Successful Open Of File


The result of the fopen command can be used to check if the file has actually been successfully opened.
Often if the file is not successfully opened, the program should terminate gracefully as the following example
demonstrates
C Code
InFile = fopen("MEMBERS", "r");
if (InFile == NULL)
{
printf("Cannot open file MEMBERS – program aborting");
exit(EXIT_FAILURE);
}

Once the file has been successfully opened, all records in the file can be used for processing. The way the
processing is handled depends on whether the number of records in the file is known or not. Using the
MEMBERS file as an example here are the two methods:

Number Of Records Are Known - Stored In The File As The First Entry
In the following example, the checking of the file open result has been omitted for clarity. Here we use a for
loop to process each record in the file since we know how many records exist.

Page 268
Pseudocode
OPEN file members
FOR I = 1 to NumOfRecords
READ a record from members
DO ProcessRecord
CLOSE the file members

C Code
int main(void)
{
FILE* InFile;
int I;
int NumOfRecords;

InFile = fopen("MEMBERS", "r");

fscanf(InFile, "%d", &NumOfRecords);


for (I=0 ; I<NumOfRecords; I++)
{
fscanf(InFile, "%s%s%s", SurName, Name, Address);
ProcessRecord(SurName, Name, Address);
}
fclose(InFile);
}

Number Of Records Are Not Known


In the following example, the checking of the file open result has been omitted for clarity. Here we use a
while loop to process each record in the file since we do not know how many records exist and must check
for the EOF (End Of File) marker.
Pseudocode
OPEN file members
READ a record from members
WHILE not EOF(members)
PROCESS the record
READ a record from members
ENDWHILE
CLOSE the file members

The important point about the second algorithm is that all languages provide some way of testing the EOF
marker and therefore the logical expression not EOF(members) is used. In C we use the feof function to
test for the EOF marker.

C Code
int main(void)
{
FILE* InFile;

InFile = fopen("MEMBERS", "r");

fscanf(InFile, "%s%s%s", SurName, Name, Address);


while (!feof(InFile))

Page 269
{
ProcessRecord(SurName, Name, Address);
fscanf(InFile, "%s%s%s", SurName, Name, Address);
}
fclose(InFile);
}

Page 270
Number Of Records Are Not Known – Using Result From fscanf
Function.
int main(void)
{
FILE* InFile;
int ReturnResult;

InFile = fopen("MEMBERS", "r");

ReturnResult = fscanf(InFile, "%s%s%s", SurName, Name, Address);


while (ReturnResult != EOF)
{
ProcessRecord(SurName, Name, Address);
ReturnResult = fscanf(InFile, "%s%s%s", SurName, Name, Address);
}
fclose(InFile);
return 0;
}

or often :

int main(void)
{
FILE* InFile;
int i;

InFile = fopen("MEMBERS", "r");

while (fscanf(InFile, "%s%s%s", SurName, Name, Address) != EOF)


{
ProcessRecord(SurName, Name, Address);
}
fclose(InFile);
return 0;
}

WRITE TO A FILE
The following example opens a file, EG1.DAT, for writing and uses the functions fprintf to write a string to
the file and fputc to write a single character to the file.
C Code
/*
Filename: Write1.c
This program opens the file EG1.DAT,
creating it if it does not already exist.
Several lines of text are written to it and it is then closed */

#include <stdio.h>

int main(void)
{
FILE *fp;

fp = fopen("a:\EG1.DAT","w");

Page 271
if (fp == NULL)
{ printf("Unable to open the file EG1.DAT\n");
return(1);
}
fprintf(fp, "First line of the sample file\n");
fprintf(fp, "Second line of sample file\n");
fputc('3',fp);
fputc('\n',fp);
fclose(fp);
return 0;
}

The result of this program will be the created of a file called EG1.DAT on a floppy disk with the following
contents:
First line of the sample file
Second line of sample file
3

APPEND T O A FILE
The following example opens a file, EG1.DAT, for appending data using the function fputs to add a string
(including the null terminator) to the file EG1.DAT.
C Code
/*
Filename: AppendEg.c
Appends two names to EG1.DAT file
*/
#include <stdio.h>

int main(void)
{
FILE * fp;
fp = fopen("a:\EG1.DAT","a");
fputs("Douglas Mawson\n",fp);
fputs("Your Name\n",fp);
fclose(fp);
return 0;
}

The result of this program will be the created of a file called EG1.DAT on a floppy disk with the following
contents:
First line of the sample file
Second line of sample file
3
Douglas Mawson
Your Name

M AKE A COPY OF A FILE


/*
Filename: ReadWrit.c

Page 272
Makes a copy of a file
requesting the name of the input file and output file
*/
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
FILE * infp;
FILE * outfp;
char InFilename[41];
char OutFilename[41];
int InChar;

printf("What is the name of the input file? :");


gets(InFilename);
printf("What is the name of the output file? :");
gets(OutFilename);
infp = fopen(InFilename,"r");
if (infp == NULL)
{
printf("\n\n*** %s does not exist ***\n",InFilename);
exit(1);
}
outfp = fopen(OutFilename,"w");
if (outfp == NULL)
{
printf("\n\n*** Error opening %s ***\n",OutFilename);
exit(1);
}
printf("Copying...\n");
while((inchar = getc(infp))!=EOF)
{
putc(inchar, outfp);
}
printf("\nThe file %s has been copied to %s. \n", InFilename,OutFilename);
getch();

fclose(infp);
fclose(outfp);
return 0;
}

Exercise 16-1

Write a program to write the following text into a file called Ex16-1.DAT using the most appropriate I/O file
functions:
This line was written using the fprintf function
This line was written using the fputs function
1
\n

Page 273
Exercise 16-2

Write a program to append your name to the file Ex16-1.DAT

Exercise 16-3

Write a program that will input the following data from the keyboard and write it to a file called Ex16-
3.DAT. Input should stop when an ItemCode of 0 is entered.

ItemCode Quantity Price


11 1 10
12 2 10
22 10 5
33 100 4.5
0

Exercise 16-4
Write a program that will read the file EX16-3.DAT and using the result from the fscanf function, calculate
the total price for all items. Output the result to the screen.

CHAPTER 16 REVIEW QUESTIONS


1. How is data stored in a data file if it is to be used as a text file.

2. What is the purpose of the end of file marker?

3. Opening a file for READ access means what?

4. Opening a file for WRITE access means what?

5. Opening a file for APPEND access means what?

Page 274
APPENDIX A – INTEGRATED DEVELOPMENT
ENVIRONMENT
This section discusses and explains how to use the integrated development environment (IDE) to create a
program as well as understanding and fixing problems that occur while attempting to compile and execute
the program. It explains an appropriate development environment to create, retrieve, modify, save and
execute a program in the chosen 3GL.

Turbo C

C programs are developed using a DOS-based integrated development environment called Turbo C. Turbo
C allows you to spend most of your time editing your program, with the facility to compile, link and run your
program you are developing. The main facilities it provides are:

• Text editor – this is where you will spend most of your time. The editor is used to type programs into
the computer and to correct errors in programs.

• Compiler – This translates your C programs into machine code. It is very fast. If your program contains
syntax errors, the compiler will tell you about them, and will not be able to complete the translation.

• Linker – The linker’s main task is to link your program with modules it needs from the C run-time
library. These include modules to interact with the keyboard and the screen. Linking is automatically done
after a successful compilation.

• Debugger – This can be used to monitor the behaviour of the program, which can help track down
subtle errors in the logic.

• Help – allows you to look up anything you need to know about C and the IDE.

Running Turbo C

Borland C++ Builder 3, is a sophisticated package used by serious program developers. We will only be
using the earlier simpler version, Turbo C++ V3.0 to cover examples of programs written using Standard C.
By all means explore what Turbo C has to offer but do not confuse yourself with details which are not part
of the course.

There is a freely available clone of Turbo C called TC-Lite. It is available for free download from a number
of Internet sites. This may be convenient for you to use at home. See the later section “Installing the C IDE”
for information about how to obtain and install it.

Page 275
Online Help
Sooner or later you are going to require help with the Turbo C commands. In this regard you are lucky to be
using Turbo C since it has an excellent online help facility. Here are the basic ways to use the on-line help:

Pressing F1 gives on-line help

If you are in editor mode, then putting the cursor on a word and pressing CTRL-F1 gives specific
help on that item. This is an excellent and quick method to get help, even on C commands.
For specific help on a topic you can go directly to the help index with SHIFT-F1
To exit from any help level, press the escape key (ESC).

Windows and Menus


The Turbo C Main Menu screen consists of 3 parts

1. The main menu across the first line


2. The edit window; where programs are entered and modified
1. A bottom line that shows which keys are currently active.

To switch back and forth between the edit window area (where you type your programs) into the top menu
press F10.

You can also get to the menu options by using ALT and the letter e.g. ALT F gives the file dialogue box.

Choosing a menu option often displays another menu or a dialogue box. A dialogue box is a window that
appears in which you are expected to respond to some prompt i.e. it is a box which expects there to be
some dialogue between the user and the computer! Pressing ESC (the escape key) will also go back a menu
level and eventually get you to the edit window.

To select an item from the main menu type the first letter of the menu command or else move the cursor
using the arrow keys and press enter.

Press ESC to leave a menu or to escape “up” one level of a pull down menu.

Use ALT-F5 to display the output window, which is where your programs output appears (and any key to
return).

To exit Turbo C use File-Exit (F10 F E)

Page 276
Menu Short-cuts
There is often more than one way to do a task using a computer and this is certainly the case in relation to
the Turbo C menus. Once a person has used Turbo C for a while they want to be able to choose menu
options quickly.

For this purpose there are special keys that can be used instead of going through the menus. These are often
called hot keys. For example if you want to save the text in the edit window, press F2.

Look at the File-Open menu you will notice that it says F3. This means that you can press F3 at any time to
do the same thing as going through the File-Open menu. Many of the more commonly used menu commands
have the short-cut hot key facility and the key to press is stated next to the menu option as a reminder. Do
not bother yourself too much with these hot-keys, at this level I would expect you to be using the menus.

Editing
The editor supplied as part of Turbo C has a large number of features. It can be successfully used initially
with just the following few commands:

· The arrow keys for left, right, up and down


· PgUp and PgDn for up and down a page at a time
· Home to go to the beginning of a line
· End to go to the end of a line
· Del to delete the current character
· Backspace to delete the character one place to the left
· Ctrl-Y to delete a line

It is wise to learn how to CUT AND PASTE

MARK the Text Use the SHIFT - arrow keys


COPY use Ctrl INS (makes another copy)
CUT use Shift DEL (moves the marked area)
PASTE use Shift INS (inserts the CUT or COPY)

If you can’t remember these keys ALT E exposes the EDIT Menu.

File Management

F10 F or ALT F will open the file menu.


F10 F C or ALT F C will allow you to change directory. You should log this to your personal
floppy disk (A: or B:) when you start work.
F10 F O, ALT F O or F3 will allow you to open an existing file. Use N for a new file.
F10 F S, ALT F S, or F2 will save the file in your current window. DO THIS OFTEN.
The Print option does not work properly in a network environment so copy your code into a
windows editor like Notepad and then print it.

Page 277
Suggested Settings for Turbo C V3.0

Please ensure that the following settings for Turbo C++ v3.0 are in place. Students should be encouraged to
have the same settings at home (or similar if using another package).

1) Options/Compiler/Source ANSI
2) Option/Compiler/Messages/Display ALL
Errors Stop After 1
Warnings Stop After 5
3) Options/Environment/Editor
Default Extension C
4) Options/Directories
Include – this will depend on your installation
Libraries –this will depend on your installation
Output – leave blank
Source – leave blank
5) Options/Environment/Preferences
Auto-Save – check all

You may find it easier to run from a window rather than just a dos shell.
Don’t forget to choose: OPTIONS SAVE

INSTALLING THE C IDE


This section describes the acquisition and installation of TC-Lite. TC-Lite is version 1.0 of Borland’s Turbo
C++. It is available free, and is available from download on the Internet. An Internet search should readily
locate it. Two sites that have it as these notes were written are:

• http://www.neilstuff.com/index.php?p=18
• http://courseweb.xu.edu.ph/installers/tclite/

TC-Lite is distributed as a zip archive. The zip file decompresses into about 100 files, set up within a number
of subdirectories, which normally go in the C:\TCLITE directory. Installing the system is simply a matter of
extracting the files into the appropriate directory structure, which will be done automatically by most zip
extractors.

The only other step involved in installation is to make the compiler and other programs automatically
available to the DOS command interface. This can be done by adding the C:\TCLITE\BIN directory to the
DOS path.

Other DOS-based C compilers will install in a similar way. Windows-based compilers will have their own
installation programs, which are generally very simple to run.

Page 278
APPENDIX B – NS DIAGRAMS AND
FLOWCHARTS
NASSI-SHNEIDERMAN DIAGRAMS
The concept of structured programming, the top-down approach to design and the use of Nassi-
Shneiderman (NS) diagrams to depict logic go hand in hand.

The logic and geometry of a properly drawn Nassi-Shneiderman diagram ensures that the algorithm it
represents is structured.

The entry point to any part of the diagram is from the part immediately preceding (or above) it. The exit
point from any part of the diagram is to the part immediately following (or below) it. This ensures that there
is only one entry and only one exit to each structure. The program logic flows step by step from the top to
the bottom of the box.

In this way there can be no “jumping around”, therefore the program written exactly from the logic will also
be structured. Also because there is a standard Nassi-Shneiderman diagram for each program structure a
person familiar with the diagrams should easily be able to follow a design documented using Nassi-
Shneiderman diagrams.

Rules
The standards that should be followed for using and documenting Nassi-Shneiderman diagrams can be
found on the next page. The examples are based on those standards.

No Nassi-Shneiderman diagram should ever be larger than one normal size sheet of paper. The rationale for
this is that if you use the top-down approach to solution development then you will not need to draw a
diagram that necessitates that much paper. All modules are to be drawn separately.

A Nassi-Shneiderman diagram should have four straight sides. The start of the diagram is indicated by the
line across the top and the end of the diagram is indicated by the line across the bottom. The diagram
should be given a title.

PROGRAM TITLE

Page 279
Page 280
Sequence with Nassi-Shneiderman diagrams
The sequence structure allows for one box to be placed on top of another indicating the sequence of one
process to the next.

The major components used are the same as for pseudocode.

Example - TAX1

A simple tax problem reads in the GrossPay, calculates the Tax as 25% of GrossPay, deducts
this from GrossPay and prints out the NettPay.

Nassi-Shneiderman Diagram
PROGRAM Tax1

Example - SORT1

Design a program to accept three whole numbers from the keyboard and output them in reverse order to the
screen. (Actually swap the values in the variables.)

Nassi-Shneiderman Diagram
PROGRAM Sort1

Page 281
Example - Coin1

Design a program to calculate the number of cents in a group of $2, $1, 50 cent, 20 cent, 10 cent, and 5
cent pieces. The number of each type of coin is entered from the keyboard and the result in cents returned
to the screen.

Nassi-Shneiderman Diagram
PROGRAM Coin1

SELECTION USING NS DIAGRAMS


There is a one-to-one matching of the pseudocode structures and the Nassi-Shneiderman diagrams for the
selection structures.

The general format of the selection structure in a NS diagram is:

If the logical expression is true the statements in the left hand column of the NS diagram will be executed; if
the logical expression is false the statements in the right hand column (if any) will be executed.

Page 282
Example – Rain1

Below are pseudocode and Nassi-Shneiderman examples of the Rain1 problem

If there are no statements to be executed when the logical expression is false the format of the simple
selection structure in the NS diagram is depicted in the first diagram above.

Example - Tax2

The pseudocode and Nassi-Shneiderman comparison of the tax algorithm is shown below.

Pseudocode
PROGRAM Tax2
DEFINE BASE=5000, TAX_RATE=0.25
INPUT GrossPay
IF GrossPay > BASE THEN
Tax = (GrossPay - BASE)*TAX_RATE
ELSE
Tax = 0
ENDIF
NettPay = GrossPay - Tax
OUTPUT NettPay
END Tax2

Page 283
Nassi-Shneiderman Diagram

Example - Sort2

Design a program to accept three whole numbers from the keyboard and output them in ascending order to
the screen.

Nassi-Shneiderman Diagram
PROGRAM Sort2

Page 284
Example - Coin2

Design a program to calculate the value of a group of $2, $1, 50 cent, 20 cent, 10 cent and 5 cent pieces.
The number of each type of coin is entered at the keyboard and the result is displayed on the screen in cents
or dollars depending if a C or a D is entered.

Nassi-Shneiderman Diagram
PROGRAM Coin2

Example - Tax3NEST

Consider the following tax scale


GrossPay TaxRate
0 - 5000 0
5001-20000 25%on excess over 5000
> 20000 tax on first 20,000+40% on excess over 20000
Calculate and output the Nett pay given a Gross pay.

Nassi Shneiderman diagram:


PROGRAM Tax3Nest

Page 285
Example - Program CalcCase

Write a program to input a choice to calculate the +, -, x, / of 2 numbers and output the result. When
division is chosen print an error message if the second number is zero otherwise perform the calculation.

Nassi Shneiderman diagram:


PROGRAM CalcCase

Modules in Nassi-Schneiderman Diagrams


The DO ModuleName in pseudocode is represented in an N-S diagram with the ModuleName written on a
separate line in a rectangle with double lines down the left and right hand sides. The MODULE itself is
drawn as a separate N-S diagram with the name of the module at the top.

For example:

PROGRAM Mainline

Iteration With NS Diagrams

There is a one-to-one matching of the pseudocode structures and the Nassi-Shneiderman diagrams for the
three iteration structures.

Pseudocode
Pre-test Loop

WHILE condition
statement(s)

Page 286
ENDWHILE
Nassi-Shneiderman Diagram

Pseudocode
Post-test Loop

REPEAT
statement(s)
UNTIL condition

Nassi-Shneiderman Diagram

Pseudocode
Fixed Loop

FOR Variable = Value1 TO Value2


statement(s)
ENDFOR

Nassi-Shneiderman Diagram

Page 287
FLOWCHARTS:
FLOWCHARTS FOR SEQUENCE
Another method for depicting algorithms in a graphical format is known as flowcharting. Flowcharts need to
be used with care because the symbolism allows the designer to break the rules of structured programming,
and it was for this reason that flowcharts lost favour as a design tool with some people, even though it is
possible to use a flowchart to design a structured program. Flowcharting was the original method used for
designing programs in the 50’s and 60’s but lost favour because of the ability to use it to design non-
structured algorithms.

Flowcharts consist of a series of shapes and arrows representing the three control structures of sequence,
selection and iteration.

To interpret a flowchart, begin at the top box labelled START and follow the arrows to each task. The
program terminates when the END box has been reached.

BASIC SYMBOLS

Page 288
Example - TAX1

Below is the pseudocode from Example Tax1 with the corresponding flowchart.

Note the use of the following in the above example:


1. The flowcharts starts with the labelled START and finishes with the box labelled END.
2. The tasks flows from top to bottom.
3. Each task can be represented by a phrase similar to structured English.
4. Each shape represents some type of process.

Page 289
Example - Sort1

Page 290
Example - Coin1

Page 291
SELECTION WITH FLOWCHARTS
The standard shape for a simple selection control structure using flowcharts is the diamond. This shows the
two alternative paths diagrammatically, depending on the outcome of a logical expression.

The general format of the simple selection structure in a flowchart is:

If the logical expression is true the statements on the left-hand side of the logical expression will be executed;
if the logical expression is false the statement on the right-hand side (if any) will be executed.

Page 292
Example - Rain2

Below is the pseudocode and flowchart comparisons from example Rain2

Page 293
Example - Tax2

Below is the pseudocode and flowchart comparisons from example Tax2

Page 294
Example - Sort2

Page 295
Example - Coin2

Page 296
ITERATION WITH FLOWCHARTS
There is no specific flowchart symbol for WHILE and REPEAT/UNTIL loops. These are made up from the
IF structures.

Page 297
Example Mean

Compare the flowchart with the pseudocode from Example Mean

Page 298
Example – Sort3

Page 299
APPENDIX C – C PROGRAMMING STANDARDS

1. C PROGRAMMING STANDARDS
The following order is to be used in laying out a program. Some sections are optional, and can be included
as required.

1. Program title/data block


2. Included files
3. Local program definitions
4. Local structures - those needed for this program only
5. Local prototypes - for functions coded in the program
6. Global variables – not usually required.
7. main function (if stand-alone program)
8. Local function definitions

For Example :

/*************************************************************
* Author | DMIT
* Date Written | Sem 2 2003
* System |
*--------------+
* Function& | Process ….
* Notes |
*--------------+
* Files | ORACLE TABLES - tm_fascia_schedule
* Accessed | - bumper_comb ….
*--------------+
* SCCS Version | 1.23 - Last Updated 11:14:44 97/09/03
* Change |
* History:Who | DMIT Lect
* Date | 17-July-97
* What | Included CheckViscountOrder.pc to issue
* | order to viscount
*--------------+
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "genl.h"
#include "scn.h"
/************************************************************/
#define SEQUENCE_NAME "WesternPlantFascia"
#define ANSI_CursorOff() printf("\33[?25l")
#define ANSI_CursorOn() printf("\33[?25h")
/******************************************************************/

typedef struct

Page 301
{
int x;
int y;
} TPos;

/******************************************************************/
char * AlignCentred(char *InputString, int FieldWidth);
void CheckArguments(int argc, char *argv[]);
void CleanUp(void);
void ClientMessHandler(TMessage Message);
int CompSchedEntry(void *A, void *B);
int CompSchedStatus(void *A, void *B);
void DoTheBars(void *ArgWinPtr);

/******************************************************************/
/*
* Global Variables needed for cleanup and for event driven
*/
char *ProgName = "fasc0020.pc";
char gSyncPointName[20] = "";
char gLastColour[3] = "";
FILE *gClientFile = NULL;
int gCurFasciaPos = 0;

/******************************************************************/
int main(int argc, char *argv[])
{
. . …
}

1.1. OBJECT NAMING CONVENTIONS


Variables and function names should consist of combinations of words and/or abbreviations, which convey
some meaning of their intended usage or action. The first letter of each word and/or abbreviation should be
capitalised with subsequent letters in lower case. Do not use underscores to separate each word and/or
abbreviation. Variables used for counting or indexing can be a single lower case character.

For example:

PrintScreen();
PlcSendToReturn();
LastPos = TRUE;
for (i = 0; i < 25; i++)
printf("i = %d\n", i);

In general, the first character of a variable name is not used to indicate type. The following cases are the
only exceptions to this rule.
• Global variables should be prefixed with a lower case 'g' to indicate their scope.
• Complex declarations may be prefixed with an Upper case ‘T’.

Example :

typedef
{

Page 302
int a
int b
} TExample;

int gTotalTimeLost = 0;

1.2. SIMPLE DECLARATIONS


Standard • Only one item should appear per declaration line. Do not use comma separated
lists of variables.
• All base types, items and initialisations within a group should be vertically aligned
using tabs.
• All variables should be initialised when they are declared..
• Use {0} to initialise the memory of an entire structure with zeroes.
• A string can be either initialised to null by using {0} or by setting the first of its
elements with ‘\0’.

For example:

char *FuncName = “AnExampleFunction”;


int i = 0;
char *TapeName = "/dev/rht0";
unsigned int Offset = 0;
int CurrentState = Start;
Tvehicle VehData = {0};
Tvehicle *VehPtr = &VehData;
char TheString[9] = {0};

1.3. COMPLEX DECLARATIONS


Standard • The definitions of complex types such as struct, union, and enum should be made
using typedef and then declaring each instance of the new type separately.
• The use of an Uppercase ‘T’ to indicate a complex type at declaration is not a
mandatory standard, but a desirable one.

For example:

typedef enum
{
Start,
Idle,
Active,
}TStates;

typedef struct
{
int x,
int y,

Page 303
}TPoint;

Tstates CurrentState = Start;


Tpoint Where = {0, 0};

1.4. FUNCTIONS
Function names should consist of combinations of words and/or abbreviations, which convey some meaning
of their intended usage or action. The first letter of each word and/or abbreviation should be capitalised with
subsequent letters in lower case. Do not use underscores to separate each word and/or abbreviation.

1.4.1. Prototypes

Standard • Prototypes for all functions used that do not appear in any included header files
must be placed at the beginning of the program as described in a previous section.
• The function return type is placed on the same line as the function name.
• The leading bracket of the formal parameter list should be placed immediately after
the function name. The formal parameters themselves should be placed on the
same line with a space after each comma. The closing bracket should be placed
hard against the last formal parameter. If there are no parameters, void must be
substituted for the parameter list.

For example:

char * SubStr(char *OutString, char *InString, int StartPos,


int NoOfChars);
static int GetNewVehicle(void);
int GetTheSum(int V1, int V2);

1.4.2. function body

Standard • The first declaration in a functions body will be the setting up of the string pointer
‘FuncName’ which will be assigned a literal of the functions name itself.

Example :

int GetTheSum(int V1, int V2)


{
char *FuncName = "GetTheSum";/*Setting up pointer FuncName */

}

1.5. CODE BLOCKS


Blocks have two parts surrounded by curly braces.
• Declarations local to this block.
• Executable statements.

Page 304
Standard • Where the block is the body of a function the curly 'on' brace is placed on a line of
its own, hard against the left margin.
• Each time a sub-block is opened the curly 'on' brace is indented one further tab
stop from the level of the enclosing block. Therefore each time a sub-block is
closed the curly 'off' brace is indented back one tab stop from the level of the
enclosing block.
• The braces always appear on a separate line.

For example:

while (i < 6)
{
DoThis();
DoThat();
}

The local declarations are started on a new line indented one tab from the initial brace. One blank line
should be left between the local declarations and the executable statements.

For example:

{
char *P = NULL; /* local */
int i = 0; /* declarations */

p = "this is a demo"; /* beginning of executable */


i = 0; /* statements */
.
.
}

1.6. EXECUTABLE STATEMENTS


Standard • Statements are placed on new lines indented one tab stop from the level of the 'on'
and 'off' braces of their surrounding block. Only one statement should appear on
each line.

For example:
i = 0; j = 10; /* WRONG */
i = j = 0; /* WRONG */
i = 0;
j = 10; /* RIGHT */

1.7. EXPRESSIONS
Standard • When an expression forms a complete statement, it should occupy one or more
lines of its own and be indented to the current level.
• Binary operators should be surrounded by spaces. Unary operators should be
placed hard against their operand.

Page 305
For Example :

*p++; /* unary operator */


i = i * 10 + c; /* binary operators */

Standard • The ternary operator "?:" should be formatted as follows.

NewMax = (i > Max) ? i : Max; /* ternary operators */

/* Note: The above statement is equivalent to the following.*/

if (i > Max)
NewMax = i;
else
NewMax = Max;

Standard • When a sub-expression is enclosed in brackets, the first symbol of the sub-
expression should be placed hard against the opening bracket. The closing
bracket should be placed immediately after the last character of the sub-
expression.

a = b * (c - d); /* sub-expression */

Standard • The round brackets, which surround the arguments of a function call, attract no
spaces.

puts("Hi there!"); /* function call */

Standard • Commas, whether used as operators or separators, should be placed hard against
the previous symbol and followed by a space.

fprintf(2, "Hi there!", 7); /* function call */

Standard • Expressions that are too large to fit on a single line should be reformatted over
several lines.

fprintf(stderr, "%s: Could not open %s for reading. %s\n",


MyName, TapeName, errno > sys_err ? "" : sys_errlist[errno] )

OR

fprintf(stderr,
"%s: Could not open %s for reading. %s\n",
MyName,
TapeName,
errno > sys_err ? "" : sys_errlist[errno])

Page 306
1.8. FLOW CONTROL
Standard • In order to give visual distinction between flow control constructs (such as for and
while) and function calls, a small variation in formatting is introduced. A space is
used to separate a flow control keyword from any controlling expression.
• Statements, which flow over one line due to being comprised of more than one
conditional statement, will start the next line with their logical operator as the first
character on the line, directly under the first line in the expression.

if ((Id->IdType == NULL)
|| ((Id->IdType->What == XtArray)
&& (Item->Left->What == XtArray)))

1.8.1. if statement

Standard • In a simple if - else combination, the else keyword should be placed on a line of
its own at the same indentation as the if.

if (Ptr == NULL)
exit(1);

if (Ptr != NULL)
{
DoThis();
DoThat();
}
else
{
DoSomethingElse();
}

1.8.2. for Statement


for (i = 0; i < Max; i++)
DoSomething();

for (i = 0; i < Max; i++)


{
DoThis();
DoThat();
}

for (;;)
{

}

1.8.3. while Statement


while ((c = getchar()) != EOF)
putchar(c);

c = getchar();

Page 307
while (c != EOF)
{
putchar(c);
c = getchar();
}

1.8.4. do while Statement


Standard • In ‘do while’ statements the while keyword should be placed on the same line as
the ending brace.

do
{
This();
} while (!Finished);

1.8.5. case Statement


Standard • The keyword case should be placed on a line of its own and indented one level
from the controlling switch keyword. A case statement should always include the
default clause as a catch all. Even if you believe it will never be executed
• The code for each case should finish with the break statement, even if it is the last.

Key = GetField(CurField);

switch (Key)
{
case Key_F(1):
Message("No help available");
break;

case Key_F(3):
Message("Exiting");
break;

default:
Message("Wrong key pressed");
break;
}

1.9. COMMENTS
This document is concerned with code formatting standards that are aimed at improving readability.
Comments in themselves do not improve readability but should directly aid understanding of concepts and
maintenance of code.

Inline comments in procedural code should be avoided wherever possible. They are likely to be scrambled
when code is modified or deleted along with code that is no longer required. It is better to use a few large
comments rather than many small ones distributed through the text.

For example:

Page 308
/*
* This demonstrates the layout of a block comment.
* One comment such as this at the head of a hundred line
* function is often more useful than hundreds of two or
* three word comments.
*/
int main(int argc, char *argv[])
{
/*
* Block comments such as this and the above, should follow
* the indent level of the code to which they refer.
*/
for (;;;)
{
/*
* Indented when the code is indented.
*/
. . .
}

Inline comments after variable declarations and definitions are acceptable and can use the // comment
indicator.

For example:

int KeyPress = KEY_UP; // Current key stroke


TWindow *PtOff = NULL; // Pre Trim Window
char ErrMessage[130] = ""; // Error message string

One of the most important aspects of comments is their semantic content. They should therefore contain
either:

• Complete English sentences, with capital letters and full stops.


• Some sort of well defined logical symbolism.
• Diagrams.

For example:

/*
* Warning!
* i + strlen(str) + base - p <= BUFSIZE
* or else core dump occurs.
*/

/*
* The shape of the input file is thus:
*
* +----------------+
* | header |
* +----------------+
* | hashtable |
* | (hashsize * |
* | TABENTLEN) |
* +----------------+

Page 309
* | table |
* | (tabsize * |
* | TABENTLEN |
* +----------------+
* | entries |
* \ . /
* .
* / . \
* | eof |
* +----------------+
*/

1.10. DEFINED CONSTANTS


Standard • Defined constants should consist of combinations of words and/or abbreviations,
which convey some meaning of their intended use or action.
• They should be capitalised with underscores used to separate each word and/or
abbreviation.
• Defined constants are most often found in include files as part of the interface to a
package of functions.

For example:
#define CONSOLE 0
#define NO_CONSOLE 1
#define INPUT_DEVICE "/dev/tty11"

Page 310
APPENDIX D –
TEXTBOOK EXERCISES SELECTED SOLUTIONS
Chapter 2 Solutions

Exercise - Sequence C Code Solutions


Exercise 2-1. POST1
/*
Filename:Post1.c
Author : DMIT
Date : Semester 2 2002
Purpose : Calculate the postal charge for a parcel whose weight is entered
at the keyboard ($1.50 per Kilo)
*/

#include <stdio.h>
#include <conio.h>

#define POSTAL_RATE 1.5

int main(void)
{
float Weight = 0.0;
float Charge = 0.0;

clrscr();
printf("*** Program Post1 ***\n\n");
printf("Enter the weight: ");
scanf("%f", &Weight);
Charge = Weight * POSTAL_RATE;
printf("\n\nThe charge is $%0.2f", Charge);
printf("\n\nPress any key to continue...");
getch();
return 0;
}

Exercise 2-2. ANIM1


/*
Filename: Anim1.C
Author : DMIT
Date : Semester 2 2002
Purpose : Calculate the fee for a Vet consultation charged @ $25.00 / hour
*/

#include <stdio.h>
#include <conio.h>

#define HOURLY_RATE 25.0

Page 311
int main(void)
{
int Hours = 0;
float Fee = 0.0;

clrscr();
printf("*** Program Anim1 ***\n\n");
printf("Enter the number of hours: ");
scanf("%i", &Hours);
Fee = Hours * HOURLY_RATE;
printf("\n\nThe fee is $%0.2f", Fee);
printf("\n\nPress any key to continue...");
getch();
return 0;
}

Exercise 2-3. BANK1


/*
Filename: Bank1
Author : DMIT
Date : Semester 2 2002
Purpose : Calculate the monthly repayment amount for a simple interest loan.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
float Principal = 0.0;
float Rate = 0.0;
float Years = 0.0;
float Repayment = 0.0;

clrscr();
printf("*** Program Bank1 ***\n\n");
printf("Enter the Principal: ");
scanf("%f", &Principal);
printf("Enter the interest rate: ");
scanf("%f", &Rate);
printf("Enter the term of the loan (in years): ");
scanf("%f", &Years);
Repayment = Principal * (1 + (Rate * Years / 100)) / (12 * Years);
printf("\n\nThe monthly repayment amount is $%.2f", Repayment);
printf("\n\nPress any key to continue...");
getch();
return 0;
}

Exercise 2-4. TEMP1


/*
Filename: Temp1.c
Author : DMIT
Date : Semester 2 2002
Purpose : Convert Fahrenheit to Celsius

Page 312
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
float Fahrenheit = 0.0;
float Centigrade = 0.0;

clrscr();
printf("*** Program Temp 1 ***\n\n");
printf("Please enter the temperature in Fahrenheit: ");
scanf("%f", &Fahrenheit);
Centigrade = (Fahrenheit - 32) / 1.8;
printf("\n\n%0.1f degrees Fahrenheit = %0.1f degrees Centigrade",
Fahrenheit, Centigrade);
printf("\n\nPress any key to continue...");
getch();
return 0;
}

Exercise 2-5. RECT1


/*
Filename: Rect1
Author : DMIT
Date : Semester 2 2002
Purpose : Calculate the perimeter and area of a rectangle
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
int Height = 0;
int Width = 0;
int Perimeter = 0;
int Area = 0;

clrscr();
printf("*** Program Rect1 ***\n\n");
printf("Please enter the width: ");
scanf("%i", &Width);
printf("Please enter the height: ");
scanf("%i", &Height);
Perimeter = (Width + Height) * 2;
Area = Width * Height;
printf("\n\nThe Perimeter is %i", Perimeter);
printf("\n\nThe Area is %i", Area);
printf("\n\nPress any key to continue...");
getch();
return 0;
}

Page 313
Exercise 2-6. DISC1
/*
Filename: Disc1.c
Author : DMIT
Date : Semester 2 2002
Purpose : Calculate the price after discount.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
float MarkedPrice = 0.0;
float DiscountRate = 0.0;
float DiscountedPrice = 0.0;

clrscr();
printf("*** Program Disc1 ***\n\n");
printf("Enter the Marked Price: ");
scanf("%f", &MarkedPrice);
printf("Enter the discount rate: ");
scanf("%f", &DiscountRate);
DiscountedPrice = MarkedPrice * (1.0 - (DiscountRate / 100));
printf("\n\nThe discounted price is $%0.2f", DiscountedPrice);
printf("\n\nPress any key to continue...");
getch();
return 0;
}

Exercise 2-7. TIME1


/*
Filename: Time1.c
Author : DMIT
Date : Semester 2 2002
Purpose : Calculate the number of seconds for given days, hours, minutes
and seconds
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
long TotalSeconds = 0;
long Days = 0;
long Hours = 0;
long Minutes = 0;
long Seconds = 0;

clrscr();
printf("*** Program Time1 ***\n\n");
printf("Enter the number of days: ");
scanf("%ld", &Days);
printf("Enter the number of hours: ");

Page 314
scanf("%ld", &Hours);
printf("Enter the number of minutes: ");
scanf("%ld", &Minutes);
printf("Enter the number of seconds: ");
scanf("%ld", &Seconds);
TotalSeconds = Days * 3600 * 24 + Hours * 3600 + Minutes * 60 + Seconds;
printf("\n\nThe total number of seconds is: %ld", TotalSeconds);
printf("\n\nPress any key to continue...");
getch();
return 0;
}

Page 315
Chapter 3 Solutions

Exercise – Program Specifications Solutions


Exercise 3-1. POST0
PROGRAM SPECIFICATION

Description
A program outputs to the screen the postage charge for a parcel when the weight of the parcel (in Kg) is
entered from the keyboard. The charge is set at $1.50 per kg.
Inputs
Name Description Legal Values Data type Source
Weight Weight of the parcel in Kg >0 Real keyboard

Processing
Define Constant RATE = 1.5
Charge = Weight * RATE
Outputs
Name Description Destination
Charge Postage charge of the parcel Screen

Major Tasks
Define Constant
INPUT Weight
Charge = Weight * RATE
OUTPUT Charge

KNOWN RESULTS
INPUTS OUTPUTS
Weight Charge
5 $7.50
10 $15.00

DATA DICTIONARY
Variable Description Legal Values Data type Source
Charge Postage charge of the >0 Real Derived
parcel
Weight Weight of the parcel in >0 Real keyboard
Kg

Page 316
Page 317
Exercise 3-2. ANIM0
PROGRAM SPECIFICATION

Description
The consultation fee for a vet is obtained by multiplying the number of hours by the hourly rate of $25. A
program accepts the number of hours (whole number) from the keyboard and outputs the consultation fee to
the screen.
Inputs
Name Description Legal Values Data type Source
Hours Hours of consultation >0 Integer Keyboard
Processing
Define Constant HOURLY_RATE = 25
Fee = Hours * HOURLY_RATE
Outputs
Name Description Destination
Fee Consultation Fee Screen
Major Tasks
DEFINE CONSTANT HOURLY_RATE = 25
INPUT Hours
Fee = Hours * HOURLY_RATE
OUTPUT Fee

KNOWN RESULTS

INPUT - Hours OUTPUT


1 $25
4 $100

Page 318
Exercise 3-3. BANK0
PROGRAM SPECIFICATION

Description
A loan officer requires a program to calculate the monthly repayment M on a customer loan by entering from
the keyboard the principal P, at an annual interest rate of R% pa., over a period of T years where
M=P(1+RT/100)/(12T). All inputs and the result is output to the screen.
Inputs
Name Description Legal Values Data type Source
P Principal of the loan >0 Real Keyboard
R Interest Rate as a percentage >0 Real Keyboard
T Term in years >0 Real Keyboard

Processing
M=P(1+RT/100)/(12T)
Outputs
Name Description Destination
P Principal of the loan Screen
R Interest Rate as a percentage Screen
T Term in years Screen
M Monthly repayment on the loan Screen

Major Tasks
INPUT P, R, T
M=P(1+RT/100)/(12T)
OUTPUT P, R, T, M

KNOWN RESULTS
INPUTS OUTPUT
P R T M
1000 10 10 $166.67
50000 5 20 $416.67

Page 319
Exercise – Sequence Algorithms Solutions
Exercise 3-8 POST1
PSEUDOCODE
PROGRAM POST1
DEFINE CONSTANT RATE=1.5
INPUT Weight
Charge = Weight * RATE
OUTPUT Charge
END POST1
NASSI-SHNEIDERMAN
PROGRAM POST1
DEFINE CONSTANT RATE=1.5
INPUT Weight
Charge = Weight * RATE
OUTPUT Charge

Exercise 3-9 ANIM1


PSEUDOCODE
PROGRAM ANIM1
DEFINE CONSTANT HOURLY_RATE = 25
INPUT Hours
Fee = Hours * HOURLY_RATE
OUTPUT Fee
END ANIM1

Exercise 3-10 BANK1


PSEUDOCODE
PROGRAM BANK1
INPUT P, R, T
M=P(1+RT/100)/(12T)
OUTPUT P, R, T, M
END BANK1

Page 320
Exercise – Sequence Documentation Solutions
Exercise 3-15 POST1
DATA DICTIONARY

Variable Description Legal Values Data type Source


Charge Postage charge of the parcel >0 Real Derived
Weight Weight of the parcel in Kg >0 Real keyboard
KNOWN RESULTS

INPUTS OUTPUTS
Weight Charge
5 $7.50
10 $15.00
DESK CHECK

Statement Weight Charge


DEFINE CONSTANT RATE=1.5
INPUT Weight 5
Charge = Weight * RATE 7.5
OUTPUT Charge 7.5

Conclusion: correct results

DESK CHECK

Statement Weight Charge


DEFINE CONSTANT RATE=1.5
INPUT Weight 10
Charge = Weight * RATE 15
OUTPUT Charge 15

Conclusion: correct results

Exercise 3-16 ANIM1


DATA DICTIONARY

Variable Description Legal Values Data type Source


Fee Consultation Fee >0 Float Derived
Hours Hours of consultation >0 Integer Keyboard

Page 321
KNOWN RESULTS

INPUT Hours OUTPUT


1 $25
4 $100
DESK CHECK

Statement Hours Fee


INPUT Hours 1
Fee = Hours * HOURLY_RATE 25
OUTPUT Fee 25

Conclusion: correct results

DESK CHECK

Statement Hours Fee


INPUT Hours 4
Fee = Hours * HOURLY_RATE 100
OUTPUT Fee 100

Conclusion: correct results

Exercise 3-17 BANK1


DATA DICTIONARY

Variable Description Legal Values Data type Source


M Monthly repayment on the loan >0 Real Derived
P Principal of the loan >0 Real Keyboard
R Interest Rate as a percentage >0 Real Keyboard
T Term in years >0 Real Keyboard
KNOWN RESULTS
INPUTS OUTPUT
P R T M
1000 10 10 $166.67
50000 5 20 $416.67
DESK CHECK

Statement P R T M
INPUT P, R, T 1000 10 10
M=P(1+RT/100)/(12T) 166.67

Page 322
OUTPUT P, R, T, M 1000 10 10 166.67

Conclusion: correct results

DESK CHECK

Statement P R T M
INPUT P, R, T 50000 5 20
M=P(1+RT/100)/(12T) 416.67
OUTPUT P, R, T, M 50000 5 20 416.67

Conclusion: correct results

Page 323
Chapter 4 Solutions

Exercise – Logical Expressions Solutions


Exercise 4-1
Hours = 0, Mins = 30

(a) T && T = T
(b) T && T = T
(c) F || F = F
(d) F || T = T
(e) !(F || F ) = !F = T
(f) !(F || F ) = !F = T
(g) F || T = T
(h) F && T = F
(i) !F && T = T &&T = T

Exercise 4-2
Hours = 10, Mins = 60

(a) T && T = T
(b) T && F = F
(c) F || F = F
(d) F || T = T
(e) !(F || F ) = !F = T
(f) !(F || T ) = !T = F
(g) F || F = F
(h) F && F = F
(i) !F || T = T || T = T

What do you notice about the results from questions (a) and (e) and the results from questions (b) and (f)?

!(A || B) is equivalent to !A && !B

Page 324
Chapter 5 Solutions

Exercise – Using If Solutions


Exercise 5-1 POST2
PROGRAM SPECIFICATION.

DESCRIPTION
A program is required that will display the postage charge for a parcel when the weight of the parcel (in
Kgs) is entered at the keyboard. Postage is charged at $1.50 per kilo with a maximum charge of $10.00.
INPUTS
Weight of parcel
PROCESSING
Calculate the postage charge
OUTPUTS
Postage charge
MAJOR TASKS
Input the weight
Calculate the charge
Output the charge
KNOWN RESULTS
INPUTS OUTPUTS
Weight Charge
5 7.5
20 10
DATA DICTIONARY

Variable Description Source Legal Values Type


Weight Weight of parcel Keyboard >=0 Float
Charge Cost of postage Keyboard >=0 and <=10 float

PSEUDOCODE
PROGRAM Post2
DEFINE CONSTANTS: RATE = 1.5, MAX_CHARGE = 10
INPUT Weight
Charge = Weight * RATE
IF Charge > MAX_CHARGE THEN
Charge = MAX_CHARGE
END IF

Page 325
OUTPUT Charge
END POST2
DESK CHECK
Using test set 1
PROGRAM Post2 Weight Charge Condition Output
INPUT Weight 5
Charge = Weight * RATE 7.5
IF Charge > MAX_CHARGE THEN False
Charge = MAX_CHARGE
END IF
OUTPUT Charge 7.5
END Post2

Using test set 2


PROGRAM Post2 Weight Charge Condition Output
INPUT Weight 20
Charge = Weight * RATE 30
IF Charge > MAX_CHARGE THEN true
Charge = MAX_CHARGE 10
END IF
OUTPUT Charge 10
END Post2
Conclusion – correct results.
C Code
/*
Filename: Post2.c
Author : DMIT
Date : Semester 2 2002
Purpose : Calculate the postal charge for a parcel, maximum charge $10. The
weight is entered at the keyboard ($1.50 per Kilo)
*/
#include <stdio.h>
#include <conio.h>
#define POSTAL_RATE 1.5
#define MAX_CHARGE 10

int main(void)
{
float Weight = 0.0;
float Charge = 0.0;

clrscr();
printf("*** Program Post1 ***\n\n");
printf("Enter the weight: ");
scanf("%f", &Weight);
Charge = Weight * POSTAL_RATE;
if (Charge > MAX_CHARGE)
{

Page 326
Charge = MAX_CHARGE;
}
printf("\n\nThe charge is $%0.2f", Charge);
printf("\n\nPress any key...");
getch();
return 0;
}

Page 327
Exercise 5-2 ANIM2

PROGRAM SPECIFICATION.

DESCRIPTION
The consultation fee for a vet is calculated by multiplying the number of hours by the hourly rate and adding
any sundry charges. The hourly rate varies according to the type of animal being treated. The user should
be able to enter the number of hours, a code to specify the animal type, and the sundry fee amount. The
rates and codes for each animal type are listed in the table below. The sundry fee is charged to cover the
cost of any medicines and equipment used in the treatment. Once the details of a treatment have been
entered the screen should be cleared, all input data re-displayed along with the consultation fee.
Animal Type Code Hourly Rate
Bird B $20.00
Cat C $25.00
Dog D $40.00
Other O $55.00
INPUTS
Animal Type, Hours, Sundry Fee
PROCESSING
Calculate the Consultation Fee
OUTPUTS
Animal Type, Hours, Sundry Fee, Consultation Fee
MAJOR TASKS
Input Animal Type, Hours, Sundry Fee
Calculate the Consultancy Fee
Output Animal Type, Hours, Sundry Fee, Consultation Fee.

KNOWN RESULTS

SET INPUTS DERIVED OUTPUTS


AnimalType Hours SundryFee ConsultationFee
1 B 2.5 32 82.00
2 C 3 0 75.00
3 D 5.5 58 278.00
DATA DICTIONARY
Variable Description Source Legal Values Type
AnimalType Type of animal treated Keyboard B, C, D, O Character
Hours Hours for treatment Keyboard >0 Float
SundryFee Fee for medicines etc. Keyboard >= 0 Float

Page 328
ConsultationFee Final amount charged Keyboard > 0 Float

PSEUDOCODE
PROGRAM Anim2
DEFINE CONSTANTS:
BIRD_RATE = 20.0
CAT_RATE = 25.0
DOG_RATE = 40.0
OTHER_RATE = 55.0
INPUT AnimalType, Hours, SundryFee
IF AnimalType = ‘B’:THEN
ConsultationFee = Hours * BIRD_RATE + SundryFee
ENDIF
IF AnimalType = ‘C’:THEN
ConsultationFee = Hours * CAT_RATE + SundryFee
ENDIF
IF AnimalType = ‘D’:THEN
ConsultationFee = Hours * DOG_RATE + SundryFee
ENDIF
IF AnimalType = ‘O’:THEN
ConsultationFee = Hours * OTHER_RATE + SundryFee
ENDIF
OUTPUT AnimalType, Hours, SundryFee, ConsultationFee
END Anim2

C Code
/*
Filename: Anim2.C
Author : DMIT
Date : Semester 2 2002
Purpose : Calculate the fee for a Vet consultation charged @ $25.00 / hour
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define B_RATE 20
#define C_RATE 25
#define D_RATE 40
#define O_RATE 55

int main(void)
{
int Hours = 0;
int Rate;
float Fee = 0.0;
float Sundry = 0.0;
char AnimType = ‘ ‘;

Page 329
clrscr();
printf("*** Program Anim1 ***\n\n");
printf("Enter the type of Animal:\n\n");
printf("B - bird C - cat D - Dog O - Other : ");
fflush(stdin);
scanf("%c", &AnimType);
AnimType = toupper(AnimType);
printf("\nEnter the number of hours: ");
scanf("%i", &Hours);
printf("\nEnter the sundry medicine charge: ");
scanf("%f", &Sundry);

if (AnimType == 'B')
Rate = B_RATE;
if (AnimType == 'C')
Rate = C_RATE;
if (AnimType == 'D')
Rate = D_RATE;
if (AnimType == 'O')
Rate = O_RATE;

Fee = Hours * Rate + Sundry;

printf("\n\nThe fee is $%0.2f", Fee);


printf("\n\nPress any key...");
getch();
return 0;
}

Exercise 5-3 BANK2


PROGRAM SPECIFICATION.

DESCRIPTION
A loan officer requires a program to calculate the monthly repayment M on a customer loan by entering from
the keyboard the principal P, at an annual interest rate of R% pa., over a period of T years where
M=P(1+RT/100.0)/(12T).
The customer’s monthly income should also be entered. If the repayment is greater than 25% of the monthly
income, display “Loan NOT approved.” If the repayment is 25% or less of the monthly income, display
“Loan approved”.
Display all inputs and the repayment amount
INPUTS
Principal
Rate
Term
Monthly Income
PROCESSING
Calculate the Monthly repayment amount
Determine if loan is approved

Page 330
OUTPUTS
Principal, Rate, Term, Monthly Income, Repayment amount, Approval decision.
MAJOR TASKS
Input Principal, Rate, Term, Monthly Income
Calculate the monthly repayment amount
Determine if loan is approved
Output Principal, Rate, Term, Monthly Income, Repayment Amount, Approval Decision.
KNOWN RESULTS

SET INPUTS DERIVED OUTPUTS


Principal Rat Term Monthly Repayment Approved
e Income Amount
1 10,000 8% 4 2000 244.13 Yes
2 20,000 10% 5 2000 429.94 Yes
3 30,000 9% 6 2000 540.77 No

DATA DICTIONARY
Variable Description Source Legal Values Type
Principal Loan Amount Keyboard >= 0 Float
Rate Interest Rate Keyboard >= 0 Float
Term Number of years Keyboard >0 Integer
MonthlyIncome Customer’s Keyboard >=0 Float
monthly income
RepaymentAmount Monthly Derived >= 0 Float
Repayment

PSEUDOCODE
PROGRAM Bank2
DEFINE CONSTANTS: APPROVAL_RATE = 0.25
INPUT Principal, Rate, Term, MonthlyIncome
RepaymentAmount = Principal*(1+Rate*Term/100)/(Term*12)
IF MonthlyIncome * APPROVAL_RATE > RepaymentAmount THEN
OUTPUT “Loan NOT Approved
ELSE
OUTPUT “Loan Approved”
END IF
OUTPUT Principal, Rate, Term, MonthlyIncome, RepaymentAmount
END Bank2

C Code
/*
Filename:Bank2.c

Page 331
Author :DMIT
Date :Semester 2 2002
Purpose :Calculate monthly repayments on a loan and determine whether you
can meet the repayments.
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
float M = 0.0;
float P = 0.0;
float R = 0.0;
float T = 0.0;
float MonthlyIncome = 0.0;

clrscr();
printf("Enter the principle: ");
scanf("%f", &P);
printf("Enter the interest rate: ");
scanf("%f", &R);
printf("Enter the years: ");
scanf("%f", &T);
printf("Enter your monthly income: ");
scanf("%f",&MonthlyIncome);

M = P*(1+(R*T)/100.0)/(12*T);

clrscr();
printf ("\n\nFor a loan of $%.2f at %.2f for %.1f years",P,R,T);
printf ("\n\nMonthly repayments are $%.2f ",M);
printf ("\n\nYour monthly income is $%.2f ",MonthlyIncome);

if (M > 0.25*MonthlyIncome)
{
printf("\n\n\tNO LOAN can be issued");
}
else
{
printf("\n\n\tLOAN OK ");
}
getch();
return 0;
}

Chapter 6 Solutions

Exercises - Nested If Solutions

Exercise 6-1 POST3N


C Code
/*

Page 332
Filename: Post3N.c
Author : DMIT
Date : Semester 2 2002
Purpose : A program requires the weight of a parcel in Kg and the parcel
type(S-surface, C-courier or E-Express) to be entered from the keyboard. The
charge is set at $1.50 per kg. There is a maximum charge of $10 for surface
parcels and a maximum charge of $20 for courier and express parcels. There is
also an additional surcharge of $8 for courier parcels and a surcharge of $5
for express parcels. The parcel type and charge is to be output to the screen.
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define POSTAL_RATE 1.5


#define MAX_CHARGE_S 10
#define MAX_CHARGE_C 20
#define MAX_CHARGE_E 20
#define SURCHARGE_C 8
#define SURCHARGE_E 5

int main(void)
{
float Weight = 0.0;
float Charge = 0.0;
char ParcelType = 0;

clrscr();
printf("*** Program Post3N ***\n\n");
printf("Enter the weight of the parcel: ");
scanf("%f", &Weight);
printf("Enter the type of parcel S C E : ");
fflush(stdin);
scanf("%c", &ParcelType);
ParcelType = toupper(ParcelType);

Charge = Weight * POSTAL_RATE;


if (ParcelType == 'S')
{
if (Charge > MAX_CHARGE_S)
Charge = MAX_CHARGE_S;
}
else
if (ParcelType == 'C')
{
if (Charge > MAX_CHARGE_C)
Charge = MAX_CHARGE_C;
Charge = Charge + SURCHARGE_C;
}
else
if (ParcelType == 'E')
{
if (Charge > MAX_CHARGE_E)
Charge = MAX_CHARGE_E;
Charge = Charge + SURCHARGE_E;
}

Page 333
printf("\n\nThe charge is $%0.2f", Charge);
printf("\n\n\nPress any key...");
getch();
return 0;
}

Exercise 6-2 ANIM3N


C Code
/*
Filename: Anim3N.c
Author : DMIT
Date : Semester 2 2002
Purpose : A program accepts the number of hours of the consultation, the
animal type (B-bird, C-cat, D-dog, O-other) and the type of owner (N-normal or
F-farmer) from the keyboard.
The hourly rate is set at
$20 for birds,
$25 for cats,
$30 for dogs and
$40 for other animals.
There is a 20% discount on the consultation fee for farmers.
Output all the inputs and the consultation fee to the screen.
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define B_RATE 20
#define C_RATE 25
#define D_RATE 40
#define O_RATE 55
#define DISC 0.20

int main(void)
{
int Hours = 0;
int Rate;
float Fee = 0.0;
char AnimType = ‘ ‘;
char OwnerType = ‘ ‘;

clrscr();
printf("*** Program Anim3N ***\n\n");
printf("Enter the type of Animal\n\n");
printf("\tB - bird\n\tC - cat \n\tD - Dog \n\tO - Other : ");
fflush(stdin);
scanf("%c", &AnimType);
AnimType = toupper(AnimType);
printf("\nEnter the number of hours: ");
scanf("%i", &Hours);
printf("\nEnter the type of Owner\n\n");
printf("\tN - Normal \n\tF - Farmer : ");
fflush(stdin);

Page 334
scanf("%c", &OwnerType);
OwnerType = toupper(OwnerType);

if (AnimType == 'B')
Rate = B_RATE;
else
if (AnimType == 'C')
Rate = C_RATE;
else
if (AnimType == 'D')
Rate = D_RATE;
else
if (AnimType == 'O')
Rate = O_RATE;

Fee = Hours * Rate;


if (OwnerType == 'F')
Fee = (1 - DISC) * Fee;

printf("\n\n\n\t\tThe fee is $%0.2f", Fee);


printf("\n\n\nPress any key...");
getch();
return 0;
}

Exercise 6-3 BANK3N


C Code
/*
Filename: Bank3N.c
Author : DMIT
Date : Semester 2 2002
Purpose : A loan officer requires a program to calculate the monthly
repayment M on a customer loan by entering from the keyboard the principal P,
the term T of the loan(in years) and the loan type (C-car, I-investment or S-
staff). The monthly repayment is calculated as M=P(1+RT/100)/(12T). The annual
interest rate of R% pa. is set at 10% for car loans, 13% for investment loans
and 8% for staff loans. All inputs and the result is output to the screen.
*/

#include <stdio.h>
#include <conio.h>

#define C_RATE 10
#define I_RATE 13
#define S_RATE 8

int main(void)
{
float M = 0.0;
float P = 0.0;
float T = 0.0;
int Rate = 0;
char LoanType = ‘ ‘;

clrscr();
printf("Enter the principle: ");

Page 335
scanf("%f", &P);
printf("Enter the years: ");
scanf("%f", &T);
printf("Enter the Type of loan\n ");
printf("\n\tC - car loan\n\tI - investment loan\n\tS - staff loan : ");
fflush(stdin);
scanf("%c", &LoanType);
LoanType = toupper(LoanType);

if (LoanType == 'C')
Rate = C_RATE;
else
if (LoanType == 'I')
Rate = I_RATE;
else
if (LoanType == 'S')
Rate = S_RATE;

M = P*(1+(Rate*T)/100)/(12*T);

clrscr();
printf ("\n\nFor a loan of $%.2f at %i%%pa for %.1f years",P,Rate,T);
printf ("\n\nMonthly repayments are $%.2f \n",M);
getch();
return 0;
}

Chapter 7 Solutions

Exercises - Case Solutions

Exercise 7-1 POST3C


C Code
/*
File: Post3C.c
Date: 2/9/02
Author: DMIT
Purpose: Calculate PostageCharge from the Weight (in Kg) entered via the
keyboard. Maximum charge is $10.00 for Surface mail, $20 for Courier or
Express. Also a Surcharge of $8 for Courier and $5 for Express
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define RATE 1.50


#define S_MAX_CHARGE 10.00
#define C_MAX_CHARGE 20.00
#define E_MAX_CHARGE 20.00
#define C_SURCHARGE 8.00
#define E_SURCHARGE 5.00

int main(void)

Page 336
{
float Weight = 0.0;
float Charge = 0.0;
float Surcharge =0.0;
char ParcelType = ‘ ‘;

clrscr();
gotoxy(25,2);
printf("Post3.C - Calculate Postage\n\n\n");
printf("\nPlease enter the Weight (in Kg): ");
scanf("%f",&Weight);
printf("\nPlease enter the Parcel Type: ");
printf("\nS(urface), C(ourier), E(xpress): ");
fflush(stdin);
scanf("%c",&ParcelType);
ParcelType = toupper(ParcelType);

Charge = Weight * RATE;


switch(ParcelType)
{
case 'S':
if (Charge > S_MAX_CHARGE)
Charge = S_MAX_CHARGE;
Surcharge = 0;
break;
case 'C':
if (Charge > C_MAX_CHARGE)
Charge = C_MAX_CHARGE;
Surcharge = C_SURCHARGE;
break;
case 'E':
if (Charge > E_MAX_CHARGE)
Charge = E_MAX_CHARGE;
Surcharge = E_SURCHARGE;
break;
}
Charge = Charge + Surcharge;

printf("\n\nPostage charge for %c-type parcel is $%.2f", ParcelType,


Charge);
printf("\n\n\nPress any key to continue...");
getch();
return 0;
}

Exercise 7-2 ANIM3C


C Code
/* Filename: Anim3C.c
Author : DMIT
Date : Semester 2 2002
Purpose : A program accepts the number of hours of the consultation, the
animal type (B-bird, C-cat, D-dog, O-other) and the type of owner (N-normal or
F-farmer) from the keyboard. The hourly rate is set at
$20 for birds,
$25 for cats,
$30 for dogs and

Page 337
$40 for other animals.
There is a 20% discount on the consultation fee for farmers.
Output all the inputs and the consultation fee to the screen.
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define B_RATE 20
#define C_RATE 25
#define D_RATE 40
#define O_RATE 55
#define DISC 0.20

int main(void)
{
int Hours = 0;
int Rate = 0;
float Fee = 0.0;
char AnimType = ‘ ‘;
char OwnerType = ‘ ‘;

clrscr();
printf("*** Program Anim3N ***\n\n");
printf("Enter the type of Animal\n\n");
printf("\tB - bird\n\tC - cat \n\tD - Dog \n\tO - Other : ");
fflush(stdin);
scanf("%c", &AnimType);
AnimType = toupper(AnimType);
printf("\nEnter the number of hours: ");
scanf("%i", &Hours);
printf("\nEnter the type of Owner\n\n");
printf("\tN - Normal \n\tF - Farmer : ");
fflush(stdin);
scanf("%c", &OwnerType);
OwnerType = toupper(OwnerType);

switch(AnimType)
{
case 'B':
Rate = B_RATE;
break;
case 'C':
Rate = C_RATE;
break;
case 'D':
Rate = D_RATE;
break;
case 'O':
Rate = O_RATE;
break;
}
Fee = Hours * Rate;
if (OwnerType == 'F')
Fee = (1 - DISC) * Fee;

printf("\n\n\n\t\tThe fee is $%0.2f", Fee);

Page 338
printf("\n\n\nPress any key...");
getch();
return 0;
}

Exercise 7-3 BANK3C


C Code
/* Filename: Bank3C.c
Author : DMIT
Date : Semester 2 2002
Purpose : A loan officer requires a program to calculate the monthly
repayment M on a customer loan by entering from the keyboard the principal P,
the term T of the loan(in years) and the loan type (C-car, I-investment or S-
staff). The monthly repayment is calculated as M=P(1+RT/100)/(12T). The annual
interest rate of R% pa. is set at 10% for car loans, 13% for investment loans
and 8% for staff loans. All inputs and the result is output to the screen.
*/

#include <stdio.h>
#include <conio.h>

#define C_RATE 10
#define I_RATE 13
#define S_RATE 8

int main(void)
{
float M = 0.0;
float P = 0.0;
float T = 0.0;
int Rate = 0;
char LoanType = ‘ ‘;

clrscr();
printf("Enter the principle: ");
scanf("%f", &P);
printf("Enter the years: ");
scanf("%f", &T);
printf("Enter the Type of loan\n ");
printf("\n\tC - car loan\n\tI - investment loan\n\tS - staff loan : ");
fflush(stdin);
scanf("%c", &LoanType);
LoanType = toupper(LoanType);

switch(LoanType)
{
case ‘C’: Rate = C_RATE;
break;
case ‘I’: Rate = I_RATE;
break;
case ‘S’: Rate = S_RATE;
break;
} /* end of switch */

M = P*(1+(Rate*T)/100)/(12*T);

Page 339
clrscr();
printf ("\n\nFor a loan of $%.2f at %i%%pa for %.1f years",P,Rate,T);
printf ("\n\nMonthly repayments are $%.2f \n",M);
getch();
return 0;
}

Chapter 8 Solutions
Exercise 8-1 POST4M
PseudoCode
PROGRAM POST4M
DEFINE CONSTANTS
DO InputWeight
DO InputParcelType
DO CalcCharge
DO OutputDetails
END POST4M

MODULE InputWeight
INPUT Weight
END InputWeight

MODULE InputParcelType
INPUT ParcelType
END InputParcelType

MODULE CalcCharge
Charge = Weight * RATE
CASE ParcelType
‘S’ : IF Charge > S_MAX_CHARGE THEN
Charge = S_MAX_CHARGE
ENDIF
Surcharge = S_MAX_CHARGE
‘C’ IF Charge > C_MAX_CHARGE THEN
Charge = C_MAX_CHARGE
ENDIF
Surcharge = C_SURCHARGE
‘E’ IF Charge > E_MAX_CHARGE THEN
Charge = E_MAX_CHARGE
ENDIF
Surcharge = E_SURCHARGE
ENDCASE
Charge = Charge + Surcharge
END CalcCharge

MODULE OutputDetails

Page 340
OUTPUT ParcelType, Charge
END OutputDetails

Exercise 8-2 ANIM4M


Pseudocode
PROGRAM ANIM4M
DEFINE CONSTANTS
DO InputAnimType
DO InputHours
DO InputSundry
DO InputOwnerType
DO CalcRate
DO CalcFee
DO OutputFee
END ANIM4M

MODULE InputAnimType
INPUT AnimType
END InputAnimType

MODULE InputHours
INPUT Hours
END InputHours

MODULE InputSundry
INPUT Sundry
END InputSundry

MODULE InputOwnerType
INPUT OwnerType
END InputOwnerType

MODULE CalcRate
CASE AnimType
‘B’: Rate = B_RATE
‘C’: Rate = C_RATE
‘D’: Rate = D_RATE
‘O’: Rate = O_RATE
ENDCASE
END CalcRate

MODULE CalcFee
Fee = Hours * Rate + Sundry
IF OwnerType = ‘F’ THEN
Fee = (1 – DISC) * Fee

Page 341
ENDIF
END CalcFee

MODULE OutputFee
OUTPUT Fee
END OutputFee

Exercise 8-3 BANK4M


Psuedocode
PROGRAM BANK4M
DEFINE CONSTANTS
DO InputPrincipal
DO InputTerm
DO InputLoanType
DO CalcRate
DO CalcMonthlyRepay
DO OutputDetails
END BANK4M

MODULE InputPrincipal
INPUT P
END InputPrincipal

MODULE InputTerm
INPUT T
END InputTerm

MODULE InputLoanType
INPUT LoanType
END InputLoanType

MODULE CalcRate
CASE LoanType
‘C’: Rate = C_RATE
‘I’: Rate = I_RATE
‘S’: Rate = S_RATE
ENDCASE
END CalcRate

MODULE CalcMonthlyRepay
M=P(1+RT/100.0)/(12T)
END CalcMonthlyRepay

MODULE OutputDetails
OUTPUT P, R, T, M

Page 342
END OutputDetails

Chapter 9 Solutions

Exercise 9-2
Inside main: Num1 = 0 Num2 = 0
Inside DoSomething: Num1 = 11 Num2 = 5
Inside main: Num1 = 0 Num2 = 0

Exercise 9-3
Inside main: Num1 = 1 Num2 = 1
Inside DoSomething: Num1 = 3 Num2 = 0
Inside main: Num1 = 3 Num2 = 1

Exercise - Functions Solution


Exercise 9-4 POST4M
C Code
/*
File: Post4M.c
Date: Sem 2 2003
Author: DMIT
Purpose:Modular design of Post3C
Calculate PostageCharge from the Weight (in Kg) entered via the
keyboard. Maximum charge is $10.00 for Surface mail, $20 for Courier or
Express. Also a Surcharge of $8 for Courier and $5 for Express.
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define RATE 1.50


#define S_MAX_CHARGE 10.00
#define C_MAX_CHARGE 20.00
#define E_MAX_CHARGE 20.00
#define S_SURCHARGE 0.00
#define C_SURCHARGE 8.00
#define E_SURCHARGE 5.00

/* Prototypes */
float InputWeight(void);
char InputParcelType(void);
float CalcCharge(char ParcelType, float Weight);
void OutputDetails(char ParcelType, float Charge);

int main(void)
{
float Weight=0.0;
float Charge=0.0;

Page 343
char ParcelType=0 ;

Weight = InputWeight();
ParcelType = InputParcelType();
Charge = CalcCharge(ParcelType,Weight);
OutputDetails(ParcelType, Charge);
return 0;
}
/***********************************************************************/
/* Functions */

float InputWeight(void)
{ float Weight = 0.0;
clrscr();
gotoxy(25,2);
printf("Post3.C - Calculate Postage\n\n\n");
printf("\nPlease enter the Weight (in Kg): ");
scanf("%f",&Weight);
return Weight;
}
/* end function InputWeight */
/***********************************************************************/

char InputParcelType(void)
{ char ParcelType = 0;
printf("\nPlease enter the Parcel Type: ");
printf("\nS(urface), C(ourier), E(xpress): ");
fflush(stdin);
scanf("%c",&ParcelType);
ParcelType = toupper(ParcelType);
return ParcelType;
}
/* end function InputParcelType */
/***********************************************************************/

float CalcCharge(char ParcelType, float Weight)


{ float Charge = 0.0;
float Surcharge = 0.0;

Charge = Weight * RATE;


switch(ParcelType)
{
case 'S':
if (Charge > S_MAX_CHARGE)
Charge = S_MAX_CHARGE;
Surcharge = S_SURCHARGE;
break;
case 'C':
if (Charge > C_MAX_CHARGE)
Charge = C_MAX_CHARGE;
Surcharge = C_SURCHARGE;
break;
case 'E':
if (Charge > E_MAX_CHARGE)
Charge = E_MAX_CHARGE;
Surcharge = E_SURCHARGE;
break;
}

Page 344
Charge = Charge + Surcharge;
return Charge;
}
/* end function CalcCharge */
/***********************************************************************/

void OutputDetails(char ParcelType, float Charge)


{
printf("\n\nPostage charge for %c-type parcel is $%.2f", ParcelType,
Charge);
printf("\n\n\nPress any key to continue...");
getch();
return;
}
/* end function OutputDetails */
/***********************************************************************/

Chapter 10 Solutions

Exercise 10-1
/**********************************************************************
* Program | GradV.c
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Uses a nested-if structure to count student's scores as:
* 90 - 100 A
* 80 - 89 B
* 70 - 79 C
* 60 - 69 D
* 0 - 50 F
* The program will validate the score
*/

#include <stdio.h>
#include <conio.h>

int main (void)


{
int Score = 0;

clrscr();
printf("Enter the score (0-100): ");
scanf("%i",&Score);
while (Score < 0 || Score > 100)
{
printf("Enter the score (0-100): ");
scanf("%i",&Score);
}
if (Score >= 90)
{
printf("\nA score of %i is an A\n");
}

Page 345
else
if (Score >= 80)
{
printf("\nA score of %i is a B\n");
}
else
if (Score >= 70)
{
printf("\nA score of %i is a C\n");
}
else
if (Score >= 60)
{
printf("\nA score of %i is a D\n");
}
else
printf("\nA score of %i is a F\n");
printf("\nPress enter to continue");
getch();
return 0;
}
Exercise 10-4
/**********************************************************************
* Program | Exam.c
* Author | Your name goes here
* Date written | The date goes here
* System | MS-DOS
*---------------+
* Function | Uses a nested-if structure to count student's scores as:
* 90 - 100 Outstanding
* 70 - 89 High Average
* 50 - 69 Satisfactory
* 1 - 50 Unsatisfactory
* The program will loop until a negative score is entered.
* The number of scores for each category will be printed.
*/

#include <stdio.h>
#include <conio.h>

int main (void)


{
int Score = 0;
int CountOutstanding = 0;
int CountAverage = 0;
int CountSatis = 0;
int CountUnsatis = 0;
float AverageScore = 0.0;
int NumScores = 0;
float TotalScore = 0;

clrscr();
printf("Enter the score (negative to end): ");
scanf("%i",&Score);
while (Score >= 0)
{
NumScores = NumScores + 1;

Page 346
TotalScore = TotalScore + Score;
if (Score >=90)
CountOutstanding = CountOutstanding + 1;
else
if (Score >=70)
CountAverage = CountAverage + 1;
else
if (Score >= 50)
CountSatis = CountSatis + 1;
else
CountUnsatis = CountUnsatis + 1;
printf("Enter the score (negative to end): ");
scanf("%i",&Score);
}

if (NumScores > 0)
{
printf("\n\nThe number of students with outstanding scores :
%i\n",CountOutstanding);
printf("The number of students with high average scores :
%i\n",CountAverage);
printf("The number of students with satisfactory scores :
%i\n",CountSatis);
printf("The number of students with unsatisfactory scores :
%i\n",CountUnsatis);
AverageScore = TotalScore/NumScores;
printf("\n\nThe average of all scores is : %.2f",AverageScore);
}
else
printf("\n\n** There were no scores entered **\n");

printf("\nPress enter to continue");


getch();
return 0;
}
Exercise 10–5
POST4W
/*
File: Post4W.c
Date: Sem 2 2003
Author: DMIT
Purpose:While loop design of Post4M
Calculate PostageCharge from the Weight (in Kg) entered via the
keyboard. Maximum charge is $10.00 for Surface mail, $20 for Courier or
Express. Also a Surcharge of $8 for Courier and $5 for Express.
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define RATE 1.50


#define S_MAX_CHARGE 10.00
#define C_MAX_CHARGE 20.00
#define E_MAX_CHARGE 20.00
#define S_SURCHARGE 0.00

Page 347
#define C_SURCHARGE 8.00
#define E_SURCHARGE 5.00

/* Prototypes */
float InputWeight(void);
char InputParcelType(void);
float CalcCharge(char ParcelType, float Weight);
void OutputDetails(char ParcelType, float Charge);

int main(void)
{
float Weight=0.0;
float Charge=0.0;
char ParcelType=0 ;

Weight = InputWeight();
ParcelType = InputParcelType();
Charge = CalcCharge(ParcelType,Weight);
OutputDetails(ParcelType, Charge);
return 0;
}
/***********************************************************************/
/* Functions */

float InputWeight(void)
{ float Weight = 0.0;
clrscr();
gotoxy(25,2);
printf("Post3.C - Calculate Postage\n\n\n");
printf("\nPlease enter the Weight (>0 Kg and <20 kg): ");
scanf("%f",&Weight);
while (Weight<=0 || Weight>20)
{
printf("\n\n *** Error in Weight - please re-enter ***\n");
printf("\nPlease enter the Weight (>0 Kg and <20 kg): ");
scanf("%f",&Weight);
}
return Weight;
}
/* end function InputWeight */
/***********************************************************************/

char InputParcelType(void)
{
char ParcelType = ' ';
printf("\nPlease enter the Parcel Type: ");
printf("\nS(urface), C(ourier), E(xpress): ");
fflush(stdin);
scanf("%c",&ParcelType);
ParcelType = toupper(ParcelType);
while (!(ParcelType=='S' || ParcelType=='C' || ParcelType=='E'))
{
printf("\n\n *** Error in parcel type - please re-enter ***\n\n");
printf("\nPlease enter the Parcel Type: ");
printf("\nS(urface), C(ourier), E(xpress): ");
fflush(stdin);
scanf("%c",&ParcelType);

Page 348
ParcelType = toupper(ParcelType);
}
return ParcelType;
}
/* end function InputParcelType */
/***********************************************************************/

float CalcCharge(char ParcelType, float Weight)


{ float Charge = 0.0;
float Surcharge = 0.0;

Charge = Weight * RATE;


switch(ParcelType)
{
case 'S':
if (Charge > S_MAX_CHARGE)
Charge = S_MAX_CHARGE;
Surcharge = S_SURCHARGE;
break;
case 'C':
if (Charge > C_MAX_CHARGE)
Charge = C_MAX_CHARGE;
Surcharge = C_SURCHARGE;
break;
case 'E':
if (Charge > E_MAX_CHARGE)
Charge = E_MAX_CHARGE;
Surcharge = E_SURCHARGE;
break;
}

Charge = Charge + Surcharge;


return Charge;
}
/* end function CalcCharge */
/***********************************************************************/

void OutputDetails(char ParcelType, float Charge)


{
printf("\n\nPostage charge for %c-type parcel is $%.2f", ParcelType,
Charge);
printf("\n\n\nPress any key to continue...");
getch();
return;
}
/* end function OutputDetails */
/***********************************************************************/

Exercise 10–6
POST4S
/*
File: Post4S.c
Date: Sem 2 2003
Author: DMIT
Purpose: While loop design of Post4M

Page 349
Calculate PostageCharge from the Weight (in Kg) entered via the
keyboard. Maximum charge is $10.00 for Surface mail, $20 for Courier or
Express. Also a Surcharge of $8 for Courier and $5 for Express.
*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define RATE 1.50


#define S_MAX_CHARGE 10.00
#define C_MAX_CHARGE 20.00
#define E_MAX_CHARGE 20.00
#define S_SURCHARGE 0.00
#define C_SURCHARGE 8.00
#define E_SURCHARGE 5.00

/* Prototypes */
float InputWeight(void);
char InputParcelType(void);
float CalcCharge(char ParcelType, float Weight);
void OutputDetails(char ParcelType, float Charge);
void OutputTotalCharge(float TotalCharge);

int main(void)
{
float Weight=0.0;
float Charge=0.0;
char ParcelType=0;
float TotalCharge = 0.0;

Weight = InputWeight();
while (Weight != 0)
{
ParcelType = InputParcelType();
Charge = CalcCharge(ParcelType,Weight);
OutputDetails(ParcelType, Charge);
TotalCharge = TotalCharge + Charge;
Weight = InputWeight();
}
OutputTotalCharge(TotalCharge);
return 0;
}
/***********************************************************************/
/* Functions */

float InputWeight(void)
{ float Weight = 0.0;
clrscr();
gotoxy(25,2);
printf("Post4S.C - Calculate Postage\n\n\n");
printf("\nPlease enter the Weight (>0 Kg and <20 kg, 0 to exit): ");
scanf("%f",&Weight);
while (Weight<0 || Weight>20)
{
printf("\n\n *** Error in Weight - please re-enter ***\n");
printf("\nPlease enter the Weight (>=0 Kg and <20 kg, 0 to exit): ");
scanf("%f",&Weight);

Page 350
}
return Weight;
}
/* end function InputWeight */
/***********************************************************************/

char InputParcelType(void)
{
char ParcelType = ' ';
printf("\nPlease enter the Parcel Type: ");
printf("\nS(urface), C(ourier), E(xpress): ");
fflush(stdin);
scanf("%c",&ParcelType);
ParcelType = toupper(ParcelType);
while (!(ParcelType=='S' || ParcelType=='C' || ParcelType=='E'))
{
printf("\n\n *** Error in parcel type - please re-enter ***\n\n");
printf("\nPlease enter the Parcel Type: ");
printf("\nS(urface), C(ourier), E(xpress): ");
fflush(stdin);
scanf("%c",&ParcelType);
ParcelType = toupper(ParcelType);
}
return ParcelType;
}
/* end function InputParcelType */
/***********************************************************************/

float CalcCharge(char ParcelType, float Weight)


{ float Charge = 0.0;
float Surcharge = 0.0;

Charge = Weight * RATE;


switch(ParcelType)
{
case 'S':
if (Charge > S_MAX_CHARGE)
Charge = S_MAX_CHARGE;
Surcharge = S_SURCHARGE;
break;
case 'C':
if (Charge > C_MAX_CHARGE)
Charge = C_MAX_CHARGE;
Surcharge = C_SURCHARGE;
break;
case 'E':
if (Charge > E_MAX_CHARGE)
Charge = E_MAX_CHARGE;
Surcharge = E_SURCHARGE;
break;
}

Charge = Charge + Surcharge;


return Charge;
}
/* end function CalcCharge */
/***********************************************************************/

Page 351
void OutputDetails(char ParcelType, float Charge)
{
printf("\n\nPostage charge for %c-type parcel is $%.2f", ParcelType,
Charge);
printf("\n\n\nPress any key to continue...");
getch();
return;
}
/* end function OutputDetails */
/***********************************************************************/
void OutputTotalCharge(float TotalCharge)
{
printf("\n\n The total postage charge for all parcels is
$%.2f\n",TotalCharge);
printf("\n\nPress any key to continue...");
getch();
return;
}
/* end function OutputTotalCharge */
/***********************************************************************/

Exercise 10-14
Pseudocode:
PROGRAM Ex10-14
ASSIGN CONSTANTS BASE_WAGE = 200
BONUS_RATE1 = 0.1
BONUS_RATE2 = 0.2
INPUT SalesAmount
WHILE SalesAmount <0 OR SalesAmount >50000
OUPUT error message
INPUT SalesAmount
ENDWHILE
IF SalesAmount < 1000 THEN
Bonus = 0
ELSE
IF SalesAmount < 10000 THEN
Bonus = SalesAmount * BONUS_RATE1
ELSE
Bonus = SalesAmount * BONUS_RATE2
ENDIF
ENDIF
WeeklyWage = BASE_WAGE + Bonus
OUTPUT Bonus, WeeklyWage
END Ex10-14.

Chapter 11 Solutions

Exercise – Repeat Loops Solutions


Exercise 11-1 POST4R
/*

Page 352
File: Post4R.c
Date: Sem 2 2003
Author: DMIT
Purpose: Repeat loop design of Post4. Calculate PostageCharge from the
Weight (in Kg)entered via the keyboard. Maximum charge is $10.00 for Surface
mail, $20 for Courier or Express. Also a Surcharge of $8 for Courier and $5
for Express parcels. Allow continued use of the program until N is entered to
Continue. Output the total cost of postage on exit.

*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define RATE 1.50


#define S_MAX_CHARGE 10.00
#define C_MAX_CHARGE 20.00
#define E_MAX_CHARGE 20.00
#define C_SURCHARGE 8.00
#define E_SURCHARGE 5.00

/* Prototypes */
float InputWeight(void);
char InputParcelType(void);
float CalcCharge(char ParcelType, float Weight);
void OutputDetails(char ParcelType, float Charge);
void OutputTotalPostageCharge(float TotalCharge);
char InputContinue(void);

int main(void)
{
float Weight =0.0;
float Charge =0.0;
char ParcelType = ‘ ‘;
char Continue = ‘ ‘;
float TotalPostage = 0.0;

do
{
Weight = InputWeight();
ParcelType = InputParcelType();
Charge = CalcCharge(ParcelType,Weight);
OutputDetails(ParcelType, Charge);
TotalPostage = TotalPostage + Charge;
Continue = InputContinue();
} while (Continue!='N');
OutputTotalPostageCharge(TotalPostage);
return 0;
}
/***********************************************************************/
/* Functions */

float InputWeight(void)
{ float Weight = 0.0;
clrscr();
gotoxy(25,2);
printf("Post3.C - Calculate Postage\n\n\n");

Page 353
printf("\nPlease enter the Weight (>0 Kg and <20 kg): ");
scanf("%f",&Weight);
while (Weight<=0 || Weight>20)
{
printf("\n\n *** Error in Weight - please re-enter ***\n");
printf("\nPlease enter the Weight (>0 Kg and <20 kg): ");
scanf("%f",&Weight);
}
return Weight;
}
/* end function InputWeight */
/***********************************************************************/

char InputParcelType(void)
{ char ParcelType = ‘ ‘;
printf("\nPlease enter the Parcel Type: ");
printf("\nS(urface), C(ourier), E(xpress): ");
fflush(stdin);
scanf("%c",&ParcelType);
ParcelType = toupper(ParcelType);
while (!(ParcelType=='S' || ParcelType=='C' || ParcelType=='E'))
{
printf("\n\n *** Error in parcel type - please re-enter ***\n\n");
printf("\nPlease enter the Parcel Type: ");
printf("\nS(urface), C(ourier), E(xpress): ");
fflush(stdin);
scanf("%c",&ParcelType);
ParcelType = toupper(ParcelType);
}
return ParcelType;
}
/* end function InputParcelType */
/***********************************************************************/

float CalcCharge(char ParcelType, float Weight)


{ float Charge = 0.0;
float Surcharge = 0.0;

Charge = Weight * RATE;


switch(ParcelType)
{
case 'S':
if (Charge > S_MAX_CHARGE)
Charge = S_MAX_CHARGE;
Surcharge = 0;
break;
case 'C':
if (Charge > C_MAX_CHARGE)
Charge = C_MAX_CHARGE;
Surcharge = C_SURCHARGE;
break;
case 'E':
if (Charge > E_MAX_CHARGE)
Charge = E_MAX_CHARGE;
Surcharge = E_SURCHARGE;
break;
}
Charge = Charge + Surcharge;

Page 354
return Charge;
}
/* end function CalcCharge */
/***********************************************************************/

void OutputDetails(char ParcelType, float Charge)


{
printf("\n\nPostage charge for %c-type parcel is $%.2f", ParcelType,
Charge);
return;
}
/* end function OutputDetails */
/***********************************************************************/

char InputContinue(void)
{
char Continue = ‘ ‘;
printf("\n\n\n\tDo you want to continue Y/N : ");
fflush(stdin);
scanf("%c",&Continue);
Continue = toupper(Continue);
while (!(Continue=='N' || Continue=='Y'))
{
printf("\n\tDo you want to continue Y/N : ");
fflush(stdin);
scanf("%c",&Continue);
Continue = toupper(Continue);
}
return Continue;
}
/*** end of function InputContinue ***/

void OutputTotalPostageCharge(float TotalCharge)


{
clrscr();
printf("\n\n\tThe total postage of all parcels is $%.2f",TotalCharge);
getch();
return;
}
/*** end of function OutputTotalPostageCharge ***/

Chapter 12 Solutions

Exercise 12.1
(a) Desk Check
Statements Logical Counter Loop Sum
Counter = 0 0
FOR Loop =5 TO 8 T 5
Sum = 0 0
WHILE Sum<30 T
Sum = Sum + Loop 5
Counter = Counter+1 1

Page 355
WHILE Sum<30 T
Sum = Sum + Loop 10
Counter = Counter+1 2
WHILE Sum<30 T
Sum = Sum + Loop 15
Counter = Counter+1 3
WHILE Sum<30 T
Sum = Sum + Loop 20
Counter = Counter+1 4
WHILE Sum<30 T
Sum = Sum + Loop 25
Counter = Counter+1 5
WHILE Sum<30 T
Sum = Sum + Loop 30
Counter = Counter+1 6
WHILE Sum<30 F
OUTPUT Sum,Loop,Counter 6 5 30
FOR Loop = 5 TO 8 T 6
Sum = 0 0
WHILE Sum<30 T
Sum = Sum + Loop 6
Counter = Counter+1 1
WHILE Sum<30 T
Sum = Sum + Loop 12
Counter = Counter+1 2
WHILE Sum<30 T
Sum = Sum + Loop 18
Counter = Counter+1 3
WHILE Sum<30 T
Sum = Sum + Loop 24
Counter = Counter+1 4
WHILE Sum<30 T
Sum = Sum + Loop 30
Counter = Counter+1 5
WHILE Sum<30 F
OUTPUT Sum,Loop,Counter 5 6 30
For Loop = 5 TO 8 T 7
Sum = 0 0
WHILE Sum<30 T
Sum = Sum + Loop 7
Counter = Counter+1 1
WHILE Sum<30 T
Sum = Sum + Loop 14
Counter = Counter+1 2

Page 356
WHILE Sum<30 T
Sum = Sum + Loop 21
Counter = Counter+1 3
WHILE Sum<30 T
Sum = Sum + Loop 28
Counter = Counter+1 4
WHILE Sum<30 T
Sum = Sum + Loop 35
Counter = Counter+1 5
WHILE Sum<30 F
OUTPUT Sum,Loop,Counter 5 7 35
For Loop = 5 TO 8 T 8
Sum = 0 0
WHILE Sum<30 T
Sum = Sum + Loop 8
Counter = Counter+1 1
WHILE Sum<30 T
Sum = Sum + Loop 16
Counter = Counter+1 2
WHILE Sum<30 T
Sum = Sum + Loop 24
Counter = Counter+1 3
WHILE Sum<30 T
Sum = Sum + Loop 30
Counter = Counter+1 4
WHILE Sum<30 F
OUTPUT Sum,Loop,Counter 4 8 30
For Loop = 5 To 8 F 9

(b) C code
/*
File: Ex12.1.c
Date: Sem 02 2003
Author: DMIT
Purpose: Solution Exercise FOR Loops
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
int Counter = 0;
int Loop = 0;
int Sum = 0;

clrscr();

Page 357
gotoxy(25,2);
printf("For Loops Exercise\n\n\n");
for (Loop = 5; Loop <= 8; Loop++)
{
Sum = 0;
while (Sum<30)
{
Sum = Sum + Loop;
Counter = Counter +1;
} /* end while */
printf("\n Sum = %i Loop = %i Counter = %i",Sum,Loop,Counter);
} /* end for */
printf("\n\n\nPress any key to continue...");
getch();
return 0;
}

Exercise 12-2 12x12 times table


C code
/*
File: TimesTab.c
Date: Sem 2 2003
Author: DMIT
Purpose: Exercise 12-2 - FOR Loops
*/

#include <stdio.h>
#include <conio.h>

int main(void)
{
int TableNum =0;
int RowNum =0;
int ColNum =0;

clrscr();
gotoxy(25,2);
printf("TimesTab.C\n\n\n");

for (ColNum = 1; ColNum <= 12; ColNum++)


{
for (RowNum = 1; RowNum <= 12; RowNum++)
{
printf("%5d", RowNum*ColNum);
}
printf("\n");
}
printf("\n\n\nPress any key to continue...");
getch();
return 0;
}

Page 358
Exercise 12-3
Desk check
Statements Logical Counter Loop Fred OUTPUT
FOR Counter = 1 TO 3 T 1
FOR Loop = 1 TO 3 T 1
OUTPUT ‘A’ A
FOR Loop = 1 TO 3 T 2
OUTPUT ‘A’ A
FOR Loop = 1 TO 3 T 3
OUTPUT ‘A’ A
FOR Loop = 1 TO 3 F 4
FOR Fred = 100 TO 103 T 100
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 T 101
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 T 102
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 T 103
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 F 104
OUTPUT Newline
FOR Counter = 1 TO 3 T 2
FOR Loop = 1 TO 3 T 1
OUTPUT ‘A’ A
FOR Loop = 1 TO 3 T 2
OUTPUT ‘A’ A
FOR Loop = 1 TO 3 T 3
OUTPUT ‘A’ A
FOR Loop = 1 TO 3 F 4
FOR Fred = 100 TO 103 T 100
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 T 101
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 T 102
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 T 103
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 F 104
OUTPUT Newline
FOR Counter = 1 TO 3 T 3
FOR Loop = 1 TO 3 T 1
OUTPUT ‘A’ A
FOR Loop = 1 TO 3 T 2

Page 359
OUTPUT ‘A’ A
FOR Loop = 1 TO 3 T 3
OUTPUT ‘A’ A
FOR Loop = 1 TO 3 F 4
FOR Fred = 100 TO 103 T 100
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 T 101
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 T 102
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 T 103
OUTPUT ‘B’ B
FOR Fred = 100 TO 103 F 104
OUTPUT Newline
FOR Counter = 1 TO 3 F 4

The OUTPUT would appear as:


AAABBBB
AAABBBB
AAABBBB

Chapter 13 Solutions

Exercise 13-1
C code
/* File: Ex13-1.c
Date: Sem 2 2003
Author: DMIT
Purpose: Exercise 13-1 - Strings
*/

#include <stdio.h>
#include <string.h>
#include <conio.h>

int main(void)
{
char Name[21];
clrscr();
printf("Enter your Name : ");
scanf("%s",&Name);
clrscr();
printf(“Your name is %s”,Name);
printf("\n\nPress enter to continue");
getch();
return 0;
}

Page 360
Exercise 13-2
/* Program Sort3 inputs 2 words and sorts them into alphabetical
* order, looping until the first word is END.
*/

#include <stdio.h>
#include <string.h>
#include <conio.h>

int main(void)
{
char Word1[31];
char Word2[31];
int Index=0;

clrscr();
printf("Enter your first word (END to stop) : ");
scanf("%s",&Word1);
for (Index=0; Index<31; Index = Index+1)
Word1[Index]=toupper(Word1[Index]);
while (strcmp(Word1,"END") != 0)
{
printf("Enter your second word : ");
scanf("%s",&Word2);
for (Index=0; Index<31; Index = Index+1)
Word2[Index]=toupper(Word2[Index]);
if (strcmp(Word1,Word2) <= 0)
printf("\n\nAlphabetical order:\t %s\t %s\n", Word1, Word2);
else
printf("\n\nAlphabetical order:\t %s\t %s\n", Word2, Word1);
printf("\n\nEnter your first word (END to stop) : ");
scanf("%s",&Word1);
for (Index=0; Index<31; Index = Index+1)
Word1[Index]=toupper(Word1[Index]);
}
printf("\n\nPress enter to continue");
getch();
return 0;
}

Exercise 13-3
(a) OUTPUT is ZZZZZ
(b) OUTPUT is AeAlA

Exercise 13-6 BANK5S


/*
Filename: Bank5S.c
Author : DMIT
Date : Semester 2 2003
Purpose : A loan officer requires a program to continually calculate the
monthly repayment M on a customer loan by entering from the keyboard the
principal P, term T of the loan(in years), loan type (C-car, I-investment or
S-staff). The monthly repayment is calculated as M=P(1+RT/100)/(12T). The
annual interest rate of R% pa. is set at 10% for car loans, 13% for investment
loans and 8% for staff loans. All inputs and the result is output to the

Page 361
screen. The user should be asked whether to continue processing. The total
value of loans is displayed on exit.
*/

#include <stdio.h>
#include <conio.h>

#define C_RATE 10.0


#define I_RATE 13.0
#define S_RATE 8.0

/*** prototypes ***/


float InputPrincipal(void);
float InputTerm(void);
char InputLoanType(void);
int CalcRate(char LoanType);
float CalcMonthlyRepayment(float P,int Rate,float T);
void OutputBankDetails(char LoanType, float P, int R, float T, float M);
void OutputTotalLoans(float TotalLoans);

int main(void)
{
float MonthlyRepayment = 0.0;
float Principal = 0.0;
float Term = 0.0;
int Rate = 0;
char LoanType = ‘ ‘;
float TotalLoans = 0.0;
char Name[31];
/* Input Customer Name */
clrscr();
printf("\nEnter Customer Name (END to stop processing\n");
scanf("%s",&Name);
while (strcmp(Name,"END")!=0)
{
Principal = InputPrincipal();
Term = InputTerm();
LoanType = InputLoanType();
Rate = CalcRate(LoanType);
MonthlyRepayment = CalcMonthlyRepayment(Principal,Rate,Term);
OutputBankDetails(LoanType,Principal,Rate,Term,MonthlyRepayment);
/* calculate the total value of loans */
TotalLoans = TotalLoans + Principal;
printf("/nEnter Customer Name (END to stop processing/n");
scanf("%s",&Name);
}
OutputTotalLoans(TotalLoans);
return 0;
} /*** end of main ***/
/***********************************************************************/
/* Functions */
float InputPrincipal(void)
{
float P =0.0;
clrscr();
printf("Enter the principle (1000 - 100000): ");
scanf("%f", &P);
while (P<1000 || P>100000)

Page 362
{
printf("\n ** Error in Principal - please re-enter **\n");
printf("\nEnter the principle (1000 - 100000): ");
scanf("%f",&P);
}
return P;
}
/*** end of function InputPrincipal ***/
/***********************************************************************/

float InputTerm(void)
{
float T = 0.0;
printf("\nEnter the years (1-20) : ");
scanf("%f",&T);
while (T<1 || T>20)
{
printf("\n ** Error in Term - please re-enter **\n");
printf("\nEnter the years (1-20): ");
scanf("%f",&T);
}
return T;
}
/*** end of function InputTerm ***/
/***********************************************************************/

char InputLoanType(void)
{
char LoanType = ‘ ‘;
printf("Enter the Type of loan\n ");
printf("\n\tC - car loan %.2f%",C_RATE);
printf("\n\tI - investment loan %.2f%",I_RATE);
printf("\n\tS - staff loan %.2f% : ",S_RATE);
fflush(stdin);
scanf("%c", &LoanType);
LoanType = toupper(LoanType);
while (LoanType != 'C' && LoanType != 'I' && LoanType != 'S')
{
printf("\n ** Error in loan type - please re-enter **\n");
printf("\nEnter the Type of loan\n ");
printf("\n\tC - car loan %.2f%",C_RATE);
printf("\n\tI - investment loan %.2f%",I_RATE);
printf("\n\tS - staff loan %.2f% : ",S_RATE);
fflush(stdin);
scanf("%c", &LoanType);
LoanType = toupper(LoanType);
}
return LoanType;
}
/*** end of function InputLoanType ***/
/***********************************************************************/

int CalcRate(char LoanType)


{
int Rate = 0;
switch(LoanType)
{
case 'C': Rate = C_RATE;

Page 363
break;
case 'I': Rate = I_RATE;
break;
case 'S': Rate = S_RATE;
break;
} /* end of switch */
return Rate;
}
/*** end of function CalcRate ***/
/***********************************************************************/

float CalcMonthlyRepayment(float P,int Rate,float T)


{
float M = 0.0;
M = P*(1+(Rate*T)/100)/(12*T);
return M;
}
/*** end of function CalcMonthlyRepayment ***/
/***********************************************************************/

void OutputBankDetails(char LoanType,float P, int R, float T, float M)


{
clrscr();
printf ("\n\nFor a %c loan of $%.2f at %i%%pa for %.1f
years",LoanType,P,R,T);
printf ("\n\nMonthly repayments are $%.2f \n",M);
return;
}
/*** end of function OutputBankDetails ***/
/***********************************************************************/

void OutputTotalLoans(float TotalLoans)


{
clrscr();
printf("\n\n\tThe total value of all loans is $%.2f",TotalLoans);
getch();
return;
}
/*** end of function OutputTotalLoans ***/
/***********************************************************************/

Exercise 14-5 BANK5A


This solution is similar to BANK5S where InputName is written as a function.

/*
Filename: Bank5A.c
Author : DMIT
Date : Semester 2 2003
Purpose : A loan officer requires a program to continually calculate the
monthly repayment M on a customer loan by entering from the keyboard the
principal P, term T of the loan(in years), loan type (C-car, I-investment or
S-staff). The monthly repayment is calculated as M=P(1+RT/100)/(12T). The
annual interest rate of R% pa. is set at 10% for car loans, 13% for investment
loans and 8% for staff loans. All inputs and the result is output to the
screen. The user should be asked whether to continue processing. The total
value of loans is displayed on exit.

Page 364
*/

#include <stdio.h>
#include <conio.h>

#define C_RATE 10.0


#define I_RATE 13.0
#define S_RATE 8.0
#define MAX_LEN 31

/*** prototypes ***/


float InputPrincipal(void);
void InputName(char Name[]);
float InputTerm(void);
char InputLoanType(void);
int CalcRate(char LoanType);
float CalcMonthlyRepayment(float P,int Rate,float T);
void OutputBankDetails(char LoanType, float P, int R, float T, float M);
void OutputTotalLoans(float TotalLoans);

int main(void)
{
float MonthlyRepayment = 0.0;
float Principal = 0.0;
float Term = 0.0;
int Rate = 0;
char LoanType = ‘ ‘;
float TotalLoans = 0.0;
char Name[MAX_LEN];

InputName(Name);
while (strcmp(Name,"END")!=0)
{
Principal = InputPrincipal();
Term = InputTerm();
LoanType = InputLoanType();
Rate = CalcRate(LoanType);
MonthlyRepayment = CalcMonthlyRepayment(Principal,Rate,Term);
OutputBankDetails(LoanType,Principal,Rate,Term,MonthlyRepayment);
/* calculate the total value of loans */
TotalLoans = TotalLoans + Principal;
InputName(Name);
}
OutputTotalLoans(TotalLoans);
return 0;
} /*** end of main ***/
/***********************************************************************/
/* Functions */
void InputName(char Name[])
{
int Index = 0;
clrscr();
printf("\nEnter Customer Name (END to stop processing\n");
scanf("%s",Name);
for (Index = 0; Index < MAX_LEN, Index++)
{
Name[Index] = toupper(Name[Index]);
}

Page 365
return;
}
/*** end of function InputName ***?
/***********************************************************************/

float InputPrincipal(void)
{
float P =0.0;
clrscr();
printf("Enter the principle (1000 - 100000): ");
scanf("%f", &P);
while (P<1000 || P>100000)
{
printf("\n ** Error in Principal - please re-enter **\n");
printf("\nEnter the principle (1000 - 100000): ");
scanf("%f",&P);
}
return P;
}
/*** end of function InputPrincipal ***/
/***********************************************************************/

float InputTerm(void)
{
float T = 0.0;
printf("\nEnter the years (1-20) : ");
scanf("%f",&T);
while (T<1 || T>20)
{
printf("\n ** Error in Term - please re-enter **\n");
printf("\nEnter the years (1-20): ");
scanf("%f",&T);
}
return T;
}
/*** end of function InputTerm ***/
/***********************************************************************/

char InputLoanType(void)
{
char LoanType = ‘ ‘;
printf("Enter the Type of loan\n ");
printf("\n\tC - car loan %.2f%",C_RATE);
printf("\n\tI - investment loan %.2f%",I_RATE);
printf("\n\tS - staff loan %.2f% : ",S_RATE);
fflush(stdin);
scanf("%c", &LoanType);
LoanType = toupper(LoanType);
while (LoanType != 'C' && LoanType != 'I' && LoanType != 'S')
{
printf("\n ** Error in loan type - please re-enter **\n");
printf("\nEnter the Type of loan\n ");
printf("\n\tC - car loan %.2f%",C_RATE);
printf("\n\tI - investment loan %.2f%",I_RATE);
printf("\n\tS - staff loan %.2f% : ",S_RATE);
fflush(stdin);
scanf("%c", &LoanType);

Page 366
LoanType = toupper(LoanType);
}
return LoanType;
}
/*** end of function InputLoanType ***/
/***********************************************************************/

int CalcRate(char LoanType)


{
int Rate = 0;
switch(LoanType)
{
case 'C': Rate = C_RATE;
break;
case 'I': Rate = I_RATE;
break;
case 'S': Rate = S_RATE;
break;
} /* end of switch */
return Rate;
}
/*** end of function CalcRate ***/
/***********************************************************************/

float CalcMonthlyRepayment(float P,int Rate,float T)


{
float M = 0.0;
M = P*(1+(Rate*T)/100)/(12*T);
return M;
}
/*** end of function CalcMonthlyRepayment ***/
/***********************************************************************/

void OutputBankDetails(char LoanType,float P, int R, float T, float M)


{
clrscr();
printf ("\n\nFor a %c loan of $%.2f at %i%%pa for %.1f
years",LoanType,P,R,T);
printf ("\n\nMonthly repayments are $%.2f \n",M);
return;
}
/*** end of function OutputBankDetails ***/
/***********************************************************************/

void OutputTotalLoans(float TotalLoans)


{
clrscr();
printf("\n\n\tThe total value of all loans is $%.2f",TotalLoans);
getch();
return;
}
/*** end of function OutputTotalLoans ***/
/***********************************************************************/

Chapter 15 Solutions

Page 367
Exercise 15-1 POST6
DESCRIPTION
A program requires the weight of a parcel in Kg(0.1 - 25kg) and the parcel type (S-surface, C-courier or
E-express) to be entered from the keyboard. Validate each of the inputs as they are entered. The charge is
set at $1.50 per kg. There is a maximum charge of $10 for surface parcels and a maximum charge of $20
for courier and express parcels. There is also an additional surcharge of $8 for courier parcels and a
surcharge of $5 for express parcels. The parcel type and charge is to be output to the screen. Allow for
continued use of the program by prompting for Y/N. On exiting the program output statistics of the total
weight of each parcel type and the total charges of each parcel type.

(This is just a repetition of the original problem description, which is clear enough. The basic task is to work
out the cost of sending a parcel, using a quite complicated algorithm. This has to be repeated, and we have
to produce summary statistics at the end of the day.)

INPUT
• Weight (the weight of the current parcel in kg). This will be of type float, and will be read from the
keyboard for each parcel sent.
• ParcelType (the type of parcel, S C or E). This will be of type char, and will be read from the
keyboard for each parcel sent.
• Continue (the answer to the question “Any more parcels?”). This will be of type char, and will be
read from the keyboard after each parcel is processed.

PROCESSING
For each parcel, we have to calculate the cost depending on its weight and type. We also need to
accumulate statistics. The statistics will need to be initialised when the program starts. We also need to store
each parcel’s details into arrays.

OUTPUT
For each parcel, we need to output the cost of postage.
At the end of the day, we need to output the arrays and statistics.

OVERALL TASKS
• Initialise statistics
• For each parcel,
o input weight and type
o calculate cost
o output the cost
o accumulate statistics
o update the arrays
• For the whole day, output the arrays and statistics

By the time we get to this stage, we should have a fair idea of what is involved in the design of this program.

Page 368
By looking at the Overall Tasks, we can devise an algorithm. The basic structure of the program is a loop,
which will execute for each parcel. We arrive at the following pseudocode:

Pseudocode
PROGRAM POST6
DEFINE Constants
INITIALISE statistics
REPEAT
DO InputWeight
DO InputParcelType
DO CalculateCharge
DO OutputCharge
Update statistics
DO UpdateArrays
DO InputContinue (any more parcels?)
UNTIL Continue=’N’
OUTPUT arrays and statistics
END POST6

The updating of the statistics for each parcel type can be done with a CASE statement, but we can’t use a
function to do this in C since there are 6 variables to update and return. This would be done using pointers,
but this is not covered here. The following would need to be a part of the main program:

NumParcels = NumParcels + 1
CASE ParcelType
case ‘S’: TotalSWeight=TotalSWeight+Weight
TotalSCharge=TotalSCharge+Charge
case ‘C’: TotalCWeight=TotalCWeight+Weight
TotalCCharge=TotalCCharge+Charge
case ‘E’: TotalEWeight=TotalEWeight+Weight
TotalECharge=TotalECharge+Charge
ENDCASE

This adds the weight and charge to the appropriate totals, depending on the type of the parcel.

MODULE InputWeight
INPUT Weight
WHILE Weight <0 OR Weight > 25
OUTPUT error message
INPUT Weight
ENDWHILE
END InputWeight

MODULE InputParcelType
INPUT ParcelType
WHILE ParcelType <> ‘S’ AND ParcelType <> ‘C’ AND ParcelType <> ‘E’
OUTPUT error message
INPUT ParcelType
ENDWHILE
END InputParcelType

MODULE InputContinue

Page 369
INPUT Continue
WHILE Continue <>’Y’ AND Continue<>’N’
OUTPUT error message
INPUT Continue
ENDWHILE
END InputContinue

MODULE CalculateCharge
Charge=Weight*1.5
CASE ParcelType
case ‘S’: IF (Charge>10)
Charge=10
ENDIF
case ‘C’: IF (Charge>20)
Charge=20
ENDIF
Charge=Charge+8
case ‘E’: IF (Charge>20)
Charge=20
ENDIF
Charge=Charge+5
ENDCASE
RETURN Charge
END CalculateCharge

MODULE OutputCharge
OUTPUT Charge
END OutputCharge

MODULE UpdateArrays
WeightArray[NumParcels] = Weight
ParcelTypeArray[NumParcels] = ParcelType
ChargeArray[NumParcels] = Charge
END UpdateArrays

The pseudocode, together with the data dictionary, should now be desk-checked, and then used as the
basis of the C program code.

/*
File: Post6.c
Date: Sem 2 2003
Author: DMIT
Purpose: Calculate PostageCharge from the Weight (in Kg)entered via the
keyboard. Maximum charge is $10.00 for Surface mail, $20 for Courier or
Express. Also a Surcharge of $8 for Courier and $5 for Express parcels. Allow
continued use of the program until N is entered to Continue. Output the total
cost of postage on exit.

*/

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define RATE 1.50


#define S_MAX_CHARGE 10.00

Page 370
#define C_MAX_CHARGE 20.00
#define E_MAX_CHARGE 20.00
#define C_SURCHARGE 8.00
#define E_SURCHARGE 5.00
#define MAX_PARCELS 100

/* Prototypes */
float InputWeight(void);
char InputParcelType(void);
float CalcCharge(char ParcelType, float Weight);
void OutputDetails(char ParcelType, float Charge);
void OutputTotalPostageCharge(float TotalCharge);
char InputContinue(void);
void UpdateArrays(float WeightArray[],float Weight, char ParcelTypeArray[],
char ParcelType, float ChargeArray[], float Charge, int NumParcels);
void OutputArrays(float WeightArray[],char ParcelTypeArray[],float
ChargeArray[], int NumParcels);
void OutputStatistics(float TotalSWeight, float TotalSCharge, float
TotalCWeight, float TotalCCharge, float TotalEWeight, float TotalECharge);

int main(void)
{
float Weight =0.0;
float Charge =0.0;
char ParcelType = ' ';
char Continue = ' ';
int NumParcels = 0;
float TotalPostage = 0.0;
float TotalSWeight = 0.0;
float TotalSCharge = 0.0;
float TotalCWeight = 0.0;
float TotalCCharge = 0.0;
float TotalEWeight = 0.0;
float TotalECharge = 0.0;
float WeightArray[MAX_PARCELS] = {0};
char ParcelTypeArray[MAX_PARCELS] = {0};
float ChargeArray[MAX_PARCELS] = {0};

do
{
Weight = InputWeight();
ParcelType = InputParcelType();
Charge = CalcCharge(ParcelType,Weight);
OutputDetails(ParcelType, Charge);
/* Update\Statistics */
TotalPostage = TotalPostage + Charge;
NumParcels++;
switch (ParcelType)
{
case 'S':TotalSWeight=TotalSWeight+Weight;
TotalSCharge=TotalSCharge+Charge;
break;
case 'C':TotalCWeight=TotalCWeight+Weight;
TotalCCharge=TotalCCharge+Charge;
break;
case 'E': TotalEWeight=TotalEWeight+Weight;
TotalECharge=TotalECharge+Charge;
break;

Page 371
}
UpdateArrays(WeightArray, Weight, ParcelTypeArray, ParcelType,
ChargeArray, Charge, NumParcels);
Continue = InputContinue();
} while (Continue!='N');
OutputArrays(WeightArray, ParcelTypeArray, ChargeArray, NumParcels);
OutputStatistics(TotalSWeight, TotalSCharge, TotalCWeight, TotalCCharge,
TotalEWeight, TotalECharge);
return 0;
}
/***********************************************************************/
/* Functions */

float InputWeight(void)
{ float Weight = 0.0;
clrscr();
gotoxy(25,2);
printf("Post3.C - Calculate Postage\n\n\n");
printf("\nPlease enter the Weight (>0 Kg and <20 kg): ");
scanf("%f",&Weight);
while (Weight<=0 || Weight>20)
{
printf("\n\n *** Error in Weight - please re-enter ***\n");
printf("\nPlease enter the Weight (>0 Kg and <20 kg): ");
scanf("%f",&Weight);
}
return Weight;
}
/* end function InputWeight */
/***********************************************************************/

char InputParcelType(void)
{ char ParcelType = ' ';
printf("\nPlease enter the Parcel Type: ");
printf("\nS(urface), C(ourier), E(xpress): ");
fflush(stdin);
scanf("%c",&ParcelType);
ParcelType = toupper(ParcelType);
while (!(ParcelType=='S' || ParcelType=='C' || ParcelType=='E'))
{
printf("\n\n *** Error in parcel type - please re-enter ***\n\n");
printf("\nPlease enter the Parcel Type: ");
printf("\nS(urface), C(ourier), E(xpress): ");
fflush(stdin);
scanf("%c",&ParcelType);
ParcelType = toupper(ParcelType);
}
return ParcelType;
}
/* end function InputParcelType */
/***********************************************************************/

float CalcCharge(char ParcelType, float Weight)


{ float Charge = 0.0;
float Surcharge = 0.0;

Charge = Weight * RATE;


switch(ParcelType)

Page 372
{
case 'S':
if (Charge > S_MAX_CHARGE)
Charge = S_MAX_CHARGE;
Surcharge = 0;
break;
case 'C':
if (Charge > C_MAX_CHARGE)
Charge = C_MAX_CHARGE;
Surcharge = C_SURCHARGE;
break;
case 'E':
if (Charge > E_MAX_CHARGE)
Charge = E_MAX_CHARGE;
Surcharge = E_SURCHARGE;
break;
}
Charge = Charge + Surcharge;
return Charge;
}
/* end function CalcCharge */
/***********************************************************************/

void OutputDetails(char ParcelType, float Charge)


{
printf("\n\nPostage charge for %c-type parcel is $%.2f", ParcelType,
Charge);
return;
}
/* end function OutputDetails */
/***********************************************************************/

char InputContinue(void)
{
char Continue = ' ';
printf("\n\n\n\tDo you want to continue Y/N : ");
fflush(stdin);
scanf("%c",&Continue);
Continue = toupper(Continue);
while (!(Continue=='N' || Continue=='Y'))
{
printf("\n\tDo you want to continue Y/N : ");
fflush(stdin);
scanf("%c",&Continue);
Continue = toupper(Continue);
}
return Continue;
}
/*** end of function InputContinue ***/
/***********************************************************************/

void UpdateArrays(float WeightArray[],float Weight, char ParcelTypeArray[],


char ParcelType, float ChargeArray[], float Charge, int NumParcels)
{
WeightArray[NumParcels] = Weight;
ParcelTypeArray[NumParcels] = ParcelType;
ChargeArray[NumParcels] = Charge;
return;

Page 373
}
/*** end of function UpdateArrays ***/
/***********************************************************************/

void OutputArrays(float WeightArray[],char ParcelTypeArray[],float


ChargeArray[], int NumParcels)
{
int Count = 0;
clrscr();
printf("\nOutput of each parcel:\n");
printf("\nParcelType Weight Charge");
for (Count = 1; Count<=NumParcels; Count++)
{
printf("\n%10c %10.2f %10.2f", ParcelTypeArray[Count], WeightArray[Count],
ChargeArray[Count]);
}
return;
}
/*** end of function OutputArrays ***/
/***********************************************************************/

void OutputStatistics(float TotalSWeight, float TotalSCharge, float


TotalCWeight, float TotalCCharge, float TotalEWeight, float TotalECharge)
{
printf("\n\nOutput Statistics:\n");
printf("\n Total Weight\tTotal Charge\n");
printf("S %10.2f\t%10.2f\n", TotalSWeight, TotalSCharge);
printf("C %10.2f\t%10.2f\n", TotalCWeight, TotalCCharge);
printf("E %10.2f\t%10.2f\n", TotalEWeight, TotalECharge);
printf("\nTotal Postage Charge $%.2f\n", TotalSCharge + TotalCCharge +
TotalECharge);
getch();
return;
}
/*** end of function OutputStatistics ***/
/***********************************************************************/

Chapter 16 Solutions

Exercise 16-1
/*
Filename: Ex16-1.c
This program opens the file Ex16-1.DAT,
creating it if it does not already exist.
Several lines of text are written to it and it is then closed */

#include <stdio.h>

int main(void)
{
FILE *fp;

fp = fopen("a:\EG1.DAT","w");
if (fp == NULL)
{ printf("Unable to open the file EG1.DAT\n");
return(1);

Page 374
}
fprintf(fp, " This line was written using the fprintf function\n");
fputs(" This line was written using the fputs function \n",fp);
fputc('1',fp);
fputc('\n',fp);
fclose(fp);
return 0;
}

Exercise 16-2
/*
Filename: Ex16-2.c
Appends your name to Ex16-1.DAT file
*/
#include <stdio.h>

int main(void)
{
FILE * fp;
fp = fopen("a:\Ex16-1.DAT","a");
if (fp == NULL)
{ printf("Unable to open the file EG1.DAT\n");
return(1);
}
fputs("Your Name\n",fp);
fclose(fp);
return 0;
}

Exercise 16-3
/*
Filename: Ex16-3.c
Writes the ItemCode, Quantity and price to file Ex16-3.DAT
*/
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
FILE * outfp;
int ItemCode = 0;
int Quantity =0;
float Cost = 0;

outfp = fopen("a:\Ex16-3.DAT","w");
if(outfp == NULL)
{
printf("\n\n*** Error opening Ex16-3.DAT ***\n");
exit(1);
}
clrscr();
printf("Enter the item code (0 to end): ");
scanf("%i",&ItemCode);
while (ItemCode != 0)
{
printf("Enter the quantity: ");

Page 375
scanf("%i",&Quantity);
printf("Enter the cost: ");
scanf("%f",&Cost);
/* write the data to the file */
fprintf(outfp, "%i %i %.2f\n",ItemCode, Quantity, Cost);
printf("Enter the item code (0 to end): ");
scanf("%i",&ItemCode);
}
getch();

fclose(outfp);
return 0;
}

Exercise 16-4
/*
Filename: Ex16-4.c
read the ItemCode, Quantity and price from file Ex16-3.DAT
Calculate total price for all items
*/
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int ItemCode = 0;
int Quantity =0;
float Cost = 0;
float TotalCost = 0;
int RetResult = 0;
FILE* InFile;

InFile = fopen("a:\Ex16-3.DAT", "r");


if(InFile == NULL)
{
printf("\n\n*** Error opening Ex16-3.DAT ***\n");
exit(1);
}

RetResult = fscanf(InFile,"%i%i%f",&ItemCode,&Quantity,&Cost);
while (RetResult != EOF)
{
TotalCost = TotalCost + Quantity*Cost;
RetResult = fscanf(InFile, "%i%i%f",&ItemCode,&Quantity,&Cost);
}
clrscr();
printf("\n Total Cost of all items is $%.2f\n",TotalCost);
getch();

fclose(InFile);
return 0;
}

Page 376
APPENDIX E -
CASE STUDY PFEECAL SOLUTIONS
The following pieces of code show one way of producing answers to the questions given. They should be
used as a guide and not just keyed in. It is not possible to learn how to program just by cutting and pasting
code

PFeeCal1 - Solution
/********************************************************************
* Program |PFeeCal1
* Authors |DMIT
* Date written |August 2003
* System |MS-DOS
* Function |Calculate the cost of hiring professionals given the
amount and the number of days
*/

#include <stdio.h>
#include <conio.h>

#define NCOST 115 /*Constants for cost*/


#define OCOST 120
#define PCOST 100

int main (void)


{
int NDays; /*variables for the days*/
int ODays;
int PDays;
int CustID; /*variable for customer ID*/
float Cost; /*cost for hire*/

clrscr();
printf("<<<<<<<<Admit Placement Fee Calculator>>>>>>>>\n\n");
/*Get all the input*/
printf("What is the customer ID? ");
fflush(stdin);
scanf("%i",&CustID);
printf("How many Network days >");
fflush(stdin);
scanf("%i",&NDays);
printf("How many Office professional days >");
fflush(stdin);
scanf("%i",&ODays);
printf("How many Programmer days >");
fflush(stdin);
scanf("%i",&PDays);
/*Calculation*/
Cost = NDays*NCOST + ODays*OCOST + PDays*PCOST;
/*Output*/
printf("\n\nCustomer %i will have to pay $%.2f",CustID,Cost);

Page 377
printf(“\n\nPress any key to end>>>");
getch();
return 0;
}

Page 378
PFeeCal2 - Solution
/********************************************************************
* Program |PFeeCal2
* Authors |DMIT
* Date written |March 2003
* System |MS-DOS
* Function |Calculate the cost of hiring professionals given the
amount and the number of days and format the output
*/

#include <stdio.h>
#include <conio.h>

#define NCOST 115 /*Constants for cost*/


#define OCOST 120
#define PCOST 100

int main (void)


{
int NDays =0; /*variables for the days*/
int ODays =0;
int PDays =0;
int CustID =0; /*variable for customer ID*/
float Cost = 0.0; /*cost for hire*/
float NCost = 0.0;
float OCost = 0.0;
float PCost = 0.0;

clrscr();
printf("\n\n\t\t<<<<<<Admit Placement Fee Calculator>>>>>>\n\n");
/*Get all the input*/
printf("\nWhat is the customer ID? ");
scanf("%i",&CustID);
printf("\nHow many Network days >");
scanf("%i",&NDays);
printf("How many Office professional days >");
scanf("%i",&ODays);
printf("How many Programmer days >");
scanf("%i",&PDays);
/*Calculation*/
NCost = NDays*NCOST;
OCost = ODays*OCOST;
PCost = PDays*PCOST;
Cost = NCost + OCost + PCost;
/*Output*/
clrscr();
printf("\nCustomer: %i\n",CustID);
printf("\n\tProffession\tDays\tCost\n");
printf("\n\t==================================\n");
printf("\n\tNetworker \t%3d\t$%8.2f",NDays,NCost);
printf("\n\tOffice \t%3d\t$%8.2f",ODays,OCost);
printf("\n\tProgrammer\t%3d\t$%8.2f\n",PDays,PCost);
printf("\n\t==================================\n");
printf("\n\tTotal cost\t\t$%8.2f",Cost);
printf("\n\n\n\nPress any key to end>>>");
getch();

Page 379
return 0;
}

Page 380
PFeeCal3 - Solution
(Header missing to save space)
#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define NCHARGE 115 /*constants for the cost*/


#define OCHARGE 120
#define PCHARGE 100
#define DISCOUNT 0.05

int main (void)


{
int Ndays = 0; /*variables for the days*/
int Odays = 0;
int Pdays = 0;
int CustID = 0; /*variable for customer ID*/
float TotalCost =0; /*cost for hire*/
float Ncost = 0;
float Ocost = 0;
float Pcost = 0;
char CustType = ‘ ‘; /*customer type*/

clrscr();
printf("\n\n\t\t<<<<<<<Admit Placement Fee Calculator>>>>>>>\n\n");
/*Get all the input*/
printf("\nWhat is the customer ID? ");
fflush(stdin);
scanf("%i",&CustID);
printf("\nWhat sort of customer (R/C)? ");
fflush(stdin);
scanf("%c",&CustType);
CustType = toupper(CustType); /*change input into upper case*/
printf("\nHow many Network days >");
fflush(stdin);
scanf("%i",&NDays);
printf("How many Office professional days >");
fflush(stdin);
scanf("%i",&ODays);
printf("How many Programmer days >");
fflush(stdin);
scanf("%i",&PDays);

/*Calculations*/
NCost = Ndays * NCHARGE;
OCost = Odays * OCHARGE;
PCost = Pdays * PCHARGE;

/*Calculate discount if required*/


if(CustType == 'R')
{
NCost = NCost*(1 – DISCOUNT);
OCost = OCost*(1 – DISCOUNT);
PCost = PCost*(1 – DISCOUNT);
}

Page 381
TotalCost = NCost + OCost + PCost;

/*Output*/
printf("\n===========================================\n");
printf("Customer %i", CustID);
if (CustType=='R')
printf(" (A regular customer) ");
else
printf(" (A casual customer) ");
printf("will be charged:\n");
printf("\n\tFor Net workers \t$%7.2f\t",NCost);
printf("\n\tFor Office workers \t$%7.2f\t",OCost);
printf("\n\tFor Programmers \t$%7.2f\t",PCost);
printf("\n\nTotal Cost\t\t\t$%7.2f",TotalCost);
printf("\n===========================================\n");
printf("\n\nPress any key to end>>>");
getch();
return 0;
}

PfeeCal4 - Solution
(Header missing to save space)
#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define NCHARGE 115 /*constants for the cost*/


#define OCHARGE 120
#define PCHARGE 100
#define DISCOUNT 0.05

int main (void)


{
int Ndays = 0; /*variables for the days*/
int Odays = 0;
int Pdays = 0;
int CustID = 0; /*variable for customer ID*/
float TotalCost = 0; /*cost for hire*/
float Ncost = 0;
float Ocost = 0;
float Pcost = 0;
char CustType = ‘ ‘; /*customer type*/

clrscr();
printf("\n\n\t\t<<<<<<<Admit Placement Fee Calculator>>>>>>>\n\n");
/*Validate the input*/
printf("\nWhat is the customer ID (1000 – 9999)? ");
scanf("%i",&CustID);
while (CustID < 1000 || CustID > 9999)
{
printf("\nSorry this is not valid - please try again");
printf("\nWhat is the customer ID(1000 – 9999)? ");
scanf("%i",&CustID);
}
printf("\nWhat sort of customer (R/C)? ");
fflush(stdin);

Page 382
scanf("%c",&CustType);
CustType = toupper(CustType); /*change input into upper case*/
while (CustType !='R' && CustType != 'C')
{
printf("\nSorry this is not valid - please try again");
printf("\nWhat sort of customer (R/C)? ");
fflush(stdin);
scanf("%c",&CustType);
CustType = toupper(CustType);
}
printf("\nHow many Network days >");
scanf("%i",&NDays);
while(NDays < 0)
{
printf("\nSorry, this is not valid - please try again.");
printf("\nHow many days? (must not be negative) >");
scanf("%i", &NDays);
}

printf("How many Office professional days >");


scanf("%i",&ODays);
while(ODays < 0)
{
printf("\nSorry, this is not valid - please try again.");
printf("\nHow many days? (must not be negative) >");
scanf("%i", &ODays);
}

printf("How many Programmer days >");


scanf("%i",&PDays);
while(PDays < 0)
{
printf("\nSorry, this is not valid - please try again.");
printf("\nHow many days? (must not be negative) >");
scanf("%i", &PDays);
}

/*Calculations*/
NCost = NDays * NCHARGE;
OCost = ODays * OCHARGE;
PCost = PDays * PCHARGE;

/*Calculate discount if required*/


if(CustType == 'R')
{
NCost = NCost*(1 – DISCOUNT);
OCost = OCost*(1 – DISCOUNT);
PCost = PCost*(1 – DISCOUNT);
}

TotalCost = NCost + OCost + PCost;

/*Output*/
printf("\n===========================================\n");
printf("Customer %i", CustID);
if (CustType=='R')
printf(" (A regular customer) ");
else

Page 383
printf(" (A casual customer) ");
printf("will be charged:\n");
printf("\n\tFor Net workers \t$%7.2f\t",NCost);
printf("\n\tFor Office workers \t$%7.2f\t",OCost);
printf("\n\tFor Programmers \t$%7.2f\t",PCost);
printf("\n\nTotal Cost\t\t\t$%7.2f",TotalCost);
printf("\n===========================================\n");
printf("\n\nPress any key to end>>>");
getch();
return 0;
}

Page 384
PfeeCal5 - Solution
(Header missing to save space)
#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define NCHARGE 115 /*constants for the cost*/


#define OCHARGE 120
#define PCHARGE 100
#define DISCOUNT 0.05

/* function prototypes */
int GetCustID(void);
char GetCustType(void);
int GetNDays(void);
int GetODays(void);
int GetPDays(void);
void OutputCustomerDetails(int CustID, char CustType, float NCost, float
OCost, float PCost, float TotalCost);

int main (void)


{
int Ndays = 0; /*variables for the days*/
int Odays = 0;
int Pdays = 0;
int CustID = 0; /*variable for customer ID*/
float TotalCost = 0; /*cost for hire*/
float Ncost = 0;
float Ocost = 0;
float Pcost = 0;
char CustType = ‘ ‘; /*customer type*/

/*Get and validate the input*/


CustID = GetCustID();
CustType = GetCustType();
NDays = GetNDays();
ODays = GetODays();
PDays = GetPDays();

/*Calculations*/
NCost = NDays * NCHARGE;
OCost = ODays * OCHARGE;
PCost = PDays * PCHARGE;

/*Calculate discount if required*/


if(CustType == 'R')
{
NCost = NCost*(1 - DISCOUNT);
OCost = OCost*(1 - DISCOUNT);
PCost = PCost*(1 - DISCOUNT);
}

TotalCost = NCost + OCost + PCost;

OutputCustomerDetails(CustID,CustType,NCost,OCost,PCost,TotalCost);

Page 385
return 0;
}
/***********************************************************/
int GetCustID(void)
{
int CustID = 0;
clrscr();
printf("\n\n\t\t<<<<<<<Admit Placement Fee Calculator>>>>>>>\n\n");
printf("\nWhat is the customer ID (1000 - 9999)? ");
scanf("%i",&CustID);
while (CustID < 1000 || CustID > 9999)
{
printf("\nSorry this is not valid - please try again");
printf("\nWhat is the customer ID(1000 - 9999)? ");
scanf("%i",&CustID);
}
return CustID;
}
/***********************************************************/
char GetCustType(void)
{
char CustType = ‘ ‘;
printf("\nWhat sort of customer (R/C)? ");
fflush(stdin);
scanf("%c",&CustType);
CustType = toupper(CustType); /*change input into upper case*/
while (CustType !='R' && CustType != 'C')
{
printf("\nSorry this is not valid - please try again");
printf("\nWhat sort of customer (R/C)? ");
fflush(stdin);
scanf("%c",&CustType);
CustType = toupper(CustType);
}
return CustType;
}
/***********************************************************/
int GetNDays(void)
{
int NDays = 0;
printf("\nHow many Network days >");
scanf("%i",&NDays);
while(NDays < 0)
{
printf("\nSorry, this is not valid - please try again.");
printf("\nHow many days? (must not be negative) >");
scanf("%i", &NDays);
}
return NDays;
}
/***********************************************************/
int GetODays(void)
{
int ODays = 0;
printf("How many Office professional days >");
scanf("%i",&ODays);
while(ODays < 0)
{

Page 386
printf("\nSorry, this is not valid - please try again.");
printf("\nHow many days? (must not be negative) >");
scanf("%i", &ODays);
}
return ODays;
}
/***********************************************************/
int GetPDays(void)
{
int PDays = 0;
printf("How many Programmer days >");
scanf("%i",&PDays);
while(PDays < 0)
{
printf("\nSorry, this is not valid - please try again.");
printf("\nHow many days? (must not be negative) >");
scanf("%i", &PDays);
}
return PDays;
}
/***********************************************************/
void OutputCustomerDetails(int CustID, char CustType, float NCost, float
OCost, float PCost, float TotalCost)
{
clrscr();
printf("\n===========================================\n");

if (CustType=='R')
printf("Regular customer Number ");
else
printf("Casual customer Number ");
printf("%i\n\n", CustID);
printf("will be charged:\n");
printf("\n\tFor Net workers \t$%7.2f\t",NCost);
printf("\n\tFor Office workers \t$%7.2f\t",OCost);
printf("\n\tFor Programmers \t$%7.2f\t",PCost);
printf("\n\nTotal Cost\t\t\t$%7.2f",TotalCost);
printf("\n===========================================\n");
printf("\n\nPress any key to end>>>");
getch();
return;
}

PfeeCal6 - Solution
(Header missing to save space)

/* PfeeCal6 */

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define NCHARGE 115


#define OCHARGE 120
#define PCHARGE 100
#define DISCOUNT 0.05

Page 387
/* function prototypes */
int GetCustID(void);
char GetCustType(void);
int GetDays(char Prompt[]);
void OutputCustomerDetails(int CustID, char CustType, float TotalCost);
void OutputDailyStatistics(int NumReg,int NumCas,float TotalDailyCost);
float CalcCost(int Ndays, int Odays,int Pdays, char CustType);
char GetContinue(void);

int main (void)


{
int NDays = 0;
int ODays = 0;
int PDays = 0;
int CustID = 0;
float TotalCost = 0.0;
char CustType = ‘ ‘;
char Continue = ‘ ‘;
int NumReg = 0;
int NumCas = 0;
float TotalDailyCost =0.0;

do
{
NDays = 0;
ODays = 0;
PDays = 0;
CustID = GetCustID();
CustType = GetCustType();
NDays = GetDays("networking days : ");
ODays = GetDays("office days : ");
PDays = GetDays("programming days: ");
TotalCost = CalcCost(NDays, ODays, PDays, CustType);
if (CustType == 'R')
NumReg = NumReg + 1;
else
NumCas = NumCas + 1;
TotalDailyCost = TotalDailyCost + TotalCost;
OutputCustomerDetails(CustID,CustType,TotalCost);
Continue = GetContinue();
} while (Continue == 'Y');

OutputDailyStatistics(NumReg,NumCas,TotalDailyCost);
return 0;
}

/***********************************************************/
int GetCustID(void)
{
int CustID = 0;
clrscr();
printf("\n\n\t\t<<<<<<<Admit Placement Fee Calculator>>>>>>>\n\n");
printf("\nWhat is the customer ID (1000 - 9999)? ");
scanf("%i",&CustID);
while (CustID < 1000 || CustID > 9999)
{

Page 388
printf("\nSorry this is not valid - please try again");
printf("\nWhat is the customer ID(1000 - 9999)? ");
scanf("%i",&CustID);
}
return CustID;
}
/***********************************************************/
char GetCustType(void)
{
char CustType = ‘ ‘;
printf("\nWhat sort of customer (R/C)? ");
fflush(stdin);
scanf("%c",&CustType);
CustType = toupper(CustType); /*change input into upper case*/
while (CustType !='R' && CustType != 'C')
{
printf("\nSorry this is not valid - please try again");
printf("\nWhat sort of customer (R/C)? ");
fflush(stdin);
scanf("%c",&CustType);
CustType = toupper(CustType);
}
return CustType;
}
/***********************************************************/
int GetDays(char Prompt[])
{
int Days = 0;
printf("\n Enter number of %s ",Prompt);
scanf("%i",&Days);
while(Days < 0)
{
printf("\nSorry, this is not valid - please try again.");
printf("\nHow many %s? (must not be negative) >",Prompt);
scanf("%i", &Days);
}
return Days;
}
/***********************************************************/

void OutputCustomerDetails(int CustID, char CustType, float TotalCost)


{
clrscr();
printf("\n===========================================\n\n");

if (CustType=='R')
printf("Regular customer Number ");
else
printf("Casual customer Number ");
printf("%i\n\n", CustID);
printf("\nwill be charged:\t$%7.2f\n",TotalCost);
printf("\n===========================================\n");
return;
}
/***********************************************************/
char GetContinue(void)
{
char Continue;

Page 389
printf("\n\nDo you want to process another customer (Y/N) ? ");
fflush(stdin);
scanf("%c",&Continue);
Continue = toupper(Continue);
while (Continue != 'Y' && Continue != 'N')
{
printf("\nSorry, this is not valid - please try again.");
printf("Do you want to process another customer (Y/N) ? ");
fflush(stdin);
scanf("%c",&Continue);
}
return Continue;
}

void OutputDailyStatistics(int NumReg,int NumCas,float TotalDailyCost)


{
clrscr();
printf("\n\n\t\t<<<<<<<Admit Placement Fee Calculator>>>>>>>\n\n");
printf("\n===========================================\n\n\n");
printf("\tTotal Regular Customers : %i\n",NumReg);
printf("\tTotal Casual Customers : %i\n",NumCas);
printf("\t-----------------------------\n");
printf("\tTotal Customers : %i\n\n",NumReg+NumCas);
printf("\tTotal Cost for the day $ %.2f\n\n",TotalDailyCost);
printf("\n===========================================\n");
printf("\n\nPress any key to continue");
getch();
return;
}

float CalcCost(int NDays, int ODays,int PDays, char CustType)


{
float NCost = 0.0;
float OCost = 0.0;
float PCost = 0.0;
float TotalCost = 0.0;

NCost = NDays * NCHARGE;


OCost = ODays * OCHARGE;
PCost = PDays * PCHARGE;

/*Calculate discount if required*/


if(CustType == 'R')
{
NCost = NCost*(1 - DISCOUNT);
OCost = OCost*(1 - DISCOUNT);
PCost = PCost*(1 - DISCOUNT);
}
TotalCost = NCost + OCost + PCost;
return TotalCost;
}

PfeeCal7 - Solution
(Header missing to save space)

/* PfeeCal7 */

Page 390
#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define NCHARGE 115


#define OCHARGE 120
#define PCHARGE 100
#define DISCOUNT 0.05

/* function prototypes */
char GetProfType(void);
int GetCustID(void);
char GetCustType(void);
int GetDays(char Prompt[]);
void OutputCustomerDetails(int CustID, char CustType, float TotalCost, int
ODays, int NDays, int PDays);
void OutputDailyStatistics(int NumReg,int NumCas,float TotalDailyCost);
float CalcCost(int Ndays, int Odays,int Pdays, char CustType);
char GetContinue(void);

int main (void)


{
int NDays = 0;
int ODays = 0;
int PDays = 0;
int Days = 0;
int CustID = 0;
float TotalCost = 0.0;
char CustType = ‘ ‘;
char ProfType = ‘ ‘;
char Continue = ‘ ‘;
int NumReg = 0;
int NumCas = 0;
float TotalDailyCost =0.0;

do
{
NDays = 0;
ODays = 0;
PDays = 0;
CustID = GetCustID();
CustType = GetCustType();
ProfType = GetProfType();
while (ProfType != 'X')
{
switch(ProfType)
{
case 'N' : Days = GetDays("networking days : ");
/* Update total number of Networker days */
NDays = NDays + Days;
break;
case 'O' : Days = GetDays("office days : ");
ODays = ODays + Days;
break;
case 'P' : Days = GetDays("programming days: ");
PDays = PDays + Days;
break;

Page 391
}
ProfType = GetProfType();
}
TotalCost = CalcCost(NDays, ODays, PDays, CustType);
if (CustType == 'R')
NumReg = NumReg + 1;
else
NumCas = NumCas + 1;
TotalDailyCost = TotalDailyCost + TotalCost;
OutputCustomerDetails(CustID,CustType,TotalCost, ODays, NDays, PDays);
Continue = GetContinue();
} while (Continue == 'Y');

OutputDailyStatistics(NumReg,NumCas,TotalDailyCost);
return 0;
}

/***********************************************************/
/* New function to get the profession type */
char GetProfType(void)
{
char Reply = ‘ ‘;
printf("\nEnter the type of professional? (N/O/P/X)? ");
fflush(stdin);
scanf("%c",&Reply);
Reply = toupper(Reply);
while (Reply != 'N' && Reply != 'O' && Reply != 'P' && Reply != 'X')
{
printf("\nSorry this is not valid - please try again");
printf("\nEnter the type of professional? (N/O/P/X)? ");
fflush(stdin);
scanf("%c",&Reply);
Reply = toupper(Reply);
}
return Reply;
}

/***********************************************************/
int GetCustID(void)
{
int CustID = 0;
clrscr();
printf("\n\n\t\t<<<<<<<Admit Placement Fee Calculator>>>>>>>\n\n");
printf("\nWhat is the customer ID (1000 - 9999)? ");
scanf("%i",&CustID);
while (CustID < 1000 || CustID > 9999)
{
printf("\nSorry this is not valid - please try again");
printf("\nWhat is the customer ID(1000 - 9999)? ");
scanf("%i",&CustID);
}
return CustID;
}
/***********************************************************/
char GetCustType(void)
{
char CustType = ‘ ‘;
printf("\nWhat sort of customer (R/C)? ");

Page 392
fflush(stdin);
scanf("%c",&CustType);
CustType = toupper(CustType); /*change input into upper case*/
while (CustType !='R' && CustType != 'C')
{
printf("\nSorry this is not valid - please try again");
printf("\nWhat sort of customer (R/C)? ");
fflush(stdin);
scanf("%c",&CustType);
CustType = toupper(CustType);
}
return CustType;
}
/***********************************************************/
int GetDays(char Prompt[])
{
int Days = 0;
printf("\n Enter number of %s ",Prompt);
scanf("%i",&Days);
while(Days < 0)
{
printf("\nSorry, this is not valid - please try again.");
printf("\nHow many %s? (must not be negative) >",Prompt);
scanf("%i", &Days);
}
return Days;
}
/***********************************************************/

void OutputCustomerDetails(int CustID, char CustType, float TotalCost, int


ODays, int NDays, int PDays)
{
clrscr();
printf("\n===================================================\n\n");

if (CustType=='R')
printf("Regular customer Number ");
else
printf("Casual customer Number ");
printf("%i\n\n", CustID);
printf("\nhas hired:\n");
printf("\t\t%i days of Network Professionals\n",NDays);
printf("\t\t%i days of Office Professionals\n",ODays);
printf("\t\t%i days of Programming Professionals\n",PDays);
printf("\n\nand will be charged:\t\t\t$%7.2f\n",TotalCost);
printf("\n===================================================\n");
return;
}
/***********************************************************/
char GetContinue(void)
{
char Continue = ’ ‘;
printf("\n\nDo you want to process another customer (Y/N) ? ");
fflush(stdin);
scanf("%c",&Continue);
Continue = toupper(Continue);
while (Continue != 'Y' && Continue != 'N')
{

Page 393
printf("\nSorry, this is not valid - please try again.");
printf("Do you want to process another customer (Y/N) ? ");
fflush(stdin);
scanf("%c",&Continue);
}
return Continue;
}

void OutputDailyStatistics(int NumReg,int NumCas,float TotalDailyCost)


{
clrscr();
printf("\n\n\t\t<<<<<<<Admit Placement Fee Calculator>>>>>>>\n\n");
printf("\n===========================================\n\n\n");
printf("\tTotal Regular Customers : %i\n",NumReg);
printf("\tTotal Casual Customers : %i\n",NumCas);
printf("\t-----------------------------\n");
printf("\tTotal Customers : %i\n\n",NumReg+NumCas);
printf("\tTotal Cost for the day $ %.2f\n\n",TotalDailyCost);
printf("\n===========================================\n");
printf("\n\nPress any key to continue");
getch();
return;
}

float CalcCost(int NDays, int ODays,int PDays, char CustType)


{
float NCost = 0.0;
float OCost = 0.0;
float PCost = 0.0;
float TotalCost = 0.0;

NCost = NDays * NCHARGE;


OCost = ODays * OCHARGE;
PCost = PDays * PCHARGE;

/*Calculate discount if required*/


if(CustType == 'R')
{
NCost = NCost*(1 - DISCOUNT);
OCost = OCost*(1 - DISCOUNT);
PCost = PCost*(1 - DISCOUNT);
}
TotalCost = NCost + OCost + PCost;
return TotalCost;
}

Page 394
PfeeCal8 - Solution
(Header missing to save space)

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

#define NCOST 115


#define OCOST 120
#define PCOST 100
#define DISCOUNT 0.95

/*Prototypes*/
char GetCustType(void);
int GetCustID(void);
int GetDaysRequired(char ProfType[]);
void ShowThisCust(int CustID, char CustType,float NCost, float OCost, float
PCost, float thisTotalCost);
char AskAnother(void);
void ShowStatistics(int Rcount, int Ccount, float allTotalCost,
int CustIDArray[], char CustTypeArray[], float CustCostArray[], int
ArrayCount);
char GetProfType(void);

int main (void)


{
int Ndays = 0; /*variables for the days*/
int Odays = 0;
int Pdays = 0;
int CustID = 0; /*variable for customer ID*/
int Rcount = 0; /*regular customer count*/
int Ccount = 0; /*casual customer count*/
float ThisTotalCost = 0; /*hire cost - one customer*/
float AllTotalCost = 0; /*hire cost - all customers*/
float Ncost = 0;
float Ocost = 0;
float Pcost = 0;
char CustType = ’ ‘; /*customer type*/
char ProfType = ‘ ‘; /*professional type*/
char Cont = ‘ ;
int CustIDArray[100] = {0}; /*Arrays for the table*/
char CustTypeArray[100] = {0};
float CustCostArray[100] = {0};
int ArrayCount = 0;

clrscr();
printf("\n\n\t\t<<<<<<<Admit Placement Fee Calculator>>>>>>>\n\n");

/*Customer loop*/
do
{
/*Start by clearing variables*/
NDays = 0;
PDays = 0;
ODays = 0;

Page 395
/*Now get the input*/
CustID = GetCustID();
CustType = GetCustType();
ProfType = GetProfType();

while (ProfType != 'X')


{
/*update relevant day counter*/
switch (ProfType)
{
case 'N':
NDays += GetDaysRequired("Networking professional");
break;
case 'O':
ODays += GetDaysRequired("Office professional");
break;
case 'P':
PDays += GetDaysRequired("Programmer");
break;
}
ProfType = GetProfType();
}
/*Calculations*/
NCost = NDays*NCOST;
OCost = ODays*OCOST;
PCost = PDays*PCOST;
ThisTotalCost = NCost + Ocost + PCost;

/*Calculate discount if required*/


if(CustType == 'R')
{
ThisTotalCost = ThisTotalCost*DISCOUNT;
NCost = NCost*DISCOUNT;
OCost = OCost*DISCOUNT;
PCost = PCost*DISCOUNT;
Rcount++;
}
else
Ccount++;

/*Running totals*/
AllTotalCost += ThisTotalCost;

/*Output*/
ShowThisCust(CustID, CustType, NCost, OCost, PCost, ThisTotalCost);

/*Update the arrays*/


CustIDArray[ArrayCount]=CustID;
CustTypeArray[ArrayCount]=CustType;
CustCostArray[ArrayCount]=ThisTotalCost;
ArrayCount++;

/*See if there are more customers*/


Cont = AskAnother();
} while (Cont == 'Y');

ShowStatistics(Rcount, Ccount, AllTotalCost, CustIDArray, CustTypeArray,


CustCostArray, ArrayCount);

Page 396
printf("\n\nPress any key to end>>>");
getch();
return 0;
}
/**************************************************************/
/*Routine with error checking to get the customer ID */
int GetCustID(void)
{
int CustID = 0;
printf("\nWhat is the customer ID? ");
scanf("%i",&CustID);
while (CustID < 1000 || CustID > 9999)
{
printf("\nSorry this is not valid - please try again");
printf("\nWhat is the customer ID? ");
scanf("%i",&CustID);
}
return CustID;
}

/**************************************************************/
/*Routine with error checking to get the customer type
*/
char GetCustType(void)
{
char CustType = ‘ ‘;
printf("\nWhat sort of customer (R/C)? ");
fflush(stdin);
scanf("%c",&CustType);
CustType = toupper(CustType);
while (CustType != 'R' && CustType != 'C')
{
printf("\nSorry this is not valid - please try again");
printf("\nWhat sort of customer (R/C)? ");
fflush(stdin);
scanf("%c",&CustType);
CustType = toupper(CustType);
}
return CustType;
}
/************************************************************/
/*Routine to get the number of days required for a given professional type */
int GetDaysRequired(char ProfType[])
{
int Days = 0;
printf("\nHow many %s days? >", ProfType);
scanf("%i",&Days);
while(Days < 0)
{
printf("\nSorry, this is not valid - please try again.");
printf("\nHow many %s days? (must not be negative) >", ProfType);
scanf("%i", &Days);
}
return Days;
}
/**************************************************************/

Page 397
/*Routine to output one customer's details
*/
void ShowThisCust(int CustID, char CustType, float NCost, float OCost, float
PCost, float ThisTotalCost)
{
printf("\n===========================================\n");
printf("Customer %i", CustID);
if (CustType == 'R')
printf(" (A regular customer) ");
else
printf(" (A casual customer) ");
printf("will be charged:\n");
printf("\n\tFor Net workers \t$%7.2f\t",NCost);
printf("\n\tFor Office workers \t$%7.2f\t",OCost);
printf("\n\tFor Programmers \t$%7.2f\t",PCost);
printf("\n\nTotal Cost\t\t\t$%7.2f",thisTotalCost);
printf("\n===========================================\n");
return;
}
/**************************************************************/
/*Routine with error checking to see if there are more customers*/
char AskAnother(void)
{
char Reply = ‘ ‘;
printf("\nAnother customer? (Y/N)? ");
fflush(stdin);
scanf("%c",&Reply);
Reply = toupper(Reply);
while (Reply != 'Y' && Reply != 'N')
{
printf("\nSorry this is not valid - please try again");
printf("\nAnother customer (Y/N)? ");
fflush(stdin);
scanf("%c",&Reply);
Reply = toupper(Reply);
}
return Reply;
}
/**************************************************************/

/*Routine to output the day's statistics


*/
void ShowStatistics(int Rcount, int Ccount, float AllTotalCost, int
CustIDArray[], char CustTypeArray[], float CustcostArray[], int ArrayCount)
{
int Index = 0;
clrscr();
printf("\n****************************************************\n");
printf("Daily statistics:\n");
printf("\n\tTotal number of customers \t\t%i",Rcount+Ccount);
printf("\n\tTotal number of regular customers \t%i",Rcount);
printf("\n\tTotal number of casual customers \t%i",Ccount);
printf("\n\tTotal income for the day\t$%8.2f\n\n",AllTotalCost);
printf("----------------------------------------------------\n");
printf("Customers for the day:\n\n");
printf("ID\t\tType\t\tCost\n");
for (Index = 0; Index<ArrayCount; Index++)

Page 398
printf("%i\t\t%c\t\t$%8.2f\n", CustIDArray[Index], CustTypeArray[Index],
CustcostArray[Index]);
printf("\n***************************************************\n");
return;
}
/**************************************************************/
/*Routine with error checking to get the professional type
*/
char GetProfType(void)
{
char Reply = ‘ ‘;
printf("\nWhat sort of professional? (N/O/P/X)? ");
fflush(stdin);
scanf("%c",&Reply);
Reply = toupper(Reply);
while (Reply != 'N' && Reply != 'O' && Reply != 'P' &&
Reply != 'X')
{
printf("\nSorry this is not valid - please try again");
printf("\nWhat sort of professional? (N/O/P/X)? ");
fflush(stdin);
scanf("%c",&Reply);
Reply = toupper(Reply);
}
return Reply;
}

Page 399
GLOSSARY
Algorithm Set of logical steps that describe the actions to be carried out to
solve the overall problem.
ANSI C American National Standards Institute standard for the C
language.
Append to a file To output data to the end of a data file.
Array Like a single row of the same type of data stored in memory,
declared with a datatype, name of the array and array size.
ASCII American Standard Code for Information Interchange.
Assembly language A language very close to machine language.
assignment operator An equal sign (=), which is used to create an assignment
statement.
Compiler Translates the whole code into a machine code file before the
program is executed.
Constant A meaningful English name given to data that does not change
during the running of the program.
Data dictionary An alphabetic list of the names of all the data items used by the
program.
Data file A collection of data that is stored in a secondary storage device.
Often organised as a collection of records.
Data validation Continually prompting the user for data until a valid data is
entered.
Datatype The type of data to be stored needs to be defined when the
variable is created.
Desk check A technique for testing the algorithm with test data.
Element A single value of an array that is stored at a particular location
of the array accesed by an index number.
End Of File marker A marker indicating the end of the file. Usually a particular ascii
character.
fflush(stdin) statement Used to flush the input buffer of any data it contains.
Field A collection of data given a name to indicate the nature of the
data and distinguish it from other collections.
FOR loop Is also known as the fixed loop since it executes a known (or
fixed) number of times.
Function A module within a C program, independently designed and
written. It communicates with the rest of the program by means
of parameters and a return value.
Global variable A variable that is defined outside a function and can be shared
by all the functions in the program.
Initialise Set a variable to an initial value.
Interpreter Translates a single program line into machine code and if there
are no errors the code is immediately executed.
Iteration Performing a specific task in a program a number of times.

Page 400
Local variable Variable declared inside the main program that can only be used
locally to the main program.
Local variables Are defined inside a function and are accessible only within that
function.
Logic errors The program will run but the program doesn't do what you want
it to do.
Logical expression An expressions that can have only two possible values: true or
false.
Logical operators Not, and, or.
Modular design The solution to a program is broken up into smaller tasks called
modules.
Nested loops To have one loop inside another.
Non-printable characters Characters not displayable on printers and screens.
Null character The character at the end of the string is set to 0, which is the null
character, which acts as a sentinel to mark the end of the string.
Object-oriented Based on the design of objects.
programming language
Parameter The data that is passed to a function.
printf statement Used to print formatted output to standard output, the screen.
Procedure Oriented language – a language closer to the English language
designed to be used for a certain type of problem
Program Sets out the input, processing and output required, in a language
the computer can understand, for performing a task.
Program development The stages in the program development process.
cycle
Program specification A formal way of documenting what a computer program is to
do.
Prototype Before a function can be used in a program, the compiler needs
to know about the name, the data type of each parameter and
return type of the function.
Pseudocode A method for writing the algorithm using English-like
instructions.
Read from a file To accept input from a data file.
Record A set of fields.
Reference parameter A parameter whose address (rather than value) is passed to a
function. This allows the function to change the value of the
parameter. Arrays are automatically passed by reference.
Relational operators Used to make comparisons between data of the same datatype
eg >, <, =.
REPEAT_UNTIL loop Is referred to as a post-test loop because the condition for
terminating the loop is tested at the end of the set of tasks to be
repeated.
Return Type The data type of the value that is being returned from the
function.
Return value The result (one only) returned from a function to the function
that called it.

Page 401
Run-time error When the program instructs the computer to perform an illegal
operation, such as subscript out of range, dividing a number by
zero, type mismatch or manipulating undefined or invalid data.
scanf statement Provides us with a means of reading in formatted input from a
standard input device.
Scope of a variable Is the part of the program where a variable can be used.
Selection Structure Used to make a choice between tasks, where the choice can be
either true or false.
Sentinel A value chosen to end loop processing.
Sentinel controlled while Where processing a program consists of continually entering
loop values until a sentinel is reached.
strcmp The string comparison function in C to compare if one string is equal
to, greater than or less than another string.
strcpy The string copy function in C to copy a string to a string
variable.
String An array of characters.
strlen The string length function returns the length of the string, which
an integer result.
Structure chart Diagram that shows each of the modules in a box and the
hierarchy of the modules called.
Syntax errors Occur when the code attempts to do something that breaks the
rules specified for the particular compiler. The program will not
run.
Text file A data file that contains a sequence of ASCII characters.
Top-down design Breaking the problem down into a number of tasks to establish
an outline of the solution, and then breaking these tasks down
into sub-tasks until the solution of each task is manageable.
Variable Allows us to refer to the area of memory via a more meaningful
English name.
Void Used when there are no parameters to be passed to a function
or when there is no return type.
WHILE loop A pre-test loop where the condition for terminating the loop is
tested at the beginning of the set of tasks to be repeated.
Write to a file To output data to a new data file.

Page 402

You might also like