c4PT (A) C Textbook 04S209
c4PT (A) C Textbook 04S209
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
Glossary.............................................................................. 400
Page 8
CHAPTER 1 – INTRODUCING C
Upon successful completion of this chapter you will be able to:
• Define a variable
• Define a constant
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.
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.
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).
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
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
• 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.
Page 6
• C offers a clean interface into the Assembly Language level.
• C provides ready access to the lower levels, providing support for specialist hardware.
• 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.
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.
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.
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.
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.
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.
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).
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:
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.
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).
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.
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
#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.
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
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.
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.
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");
Page 16
General points about C programs
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.
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");
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();
Count = 1;
while (Count <= 5)
{
printf("%s\n",FirstName);
Count = Count + 1;
}
printf("\a\a\a\a\a");
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");
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");
if (Choice == 'H')
{
printf("\nHalf of %.2f is %.2f\n", Number, Number/2);
}
else
{
printf("\nDouble %.2f is %.2f\n", Number, Number*2);
}
Page 30
CHAPTER 1 REVIEW QUESTIONS
1. Explain how a compiler works.
2. Define a variable.
Page 31
CHAPTER 2 -
SIMPLE SEQUENCE PROGRAMS
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).
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
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;
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>
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.
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.
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.
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
If the value of the variable Days and Year is 365 and 2003 respectively then the output of the printf
statement will be:
\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.
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 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);
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.
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.
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.
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.
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.
Page 46
Exercises – Sequence 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
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:
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:
Page 49
Page 50
Processing
1. Enter the customer ID
3. Enter the type of professional required (N/O/P) for Networking, Office or Programming.
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
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
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
Page 52
3211 R $ 95.00
Page 53
REQUIREMENTS
For this case study you must present your work in a professional manner:
• Program Specification
• Pseudocode
• Data Dictionary
• Documented Source Code
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:
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?
7. Write the C code statements to input a number, multiply it by 2 and output the result.
Page 56
CHAPTER 3 -
PROGRAM DEVELOPMENT
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
INPUT
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.
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
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
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:
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.
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
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:
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
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)
DESK CHECK
for Input 9, 14, 7 (known solution 7,14,9)
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
DATA DICTIONARY
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
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
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.
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
Page 78
CHAPTER 3 REVIEW QUESTIONS
1. List the six stages in the program development cycle.
Page 79
CHAPTER 4 -
LOGIC AND EXPRESSIONS
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.
Note that in all of the above examples there are only two possible “answers” to or values of the
expression:
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 .
== equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
!= not equal to
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.
Tax ≠ 0
MenuChoice = 1
Temperature > Minimum
Age > 10
MyWeeklyPay < YourWeeklyPay
Tax ≤ 5
ParkingFine ≠ 0
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:
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
Page 83
This statement will only be true if both the temperature is greater than 90 and the humidity is greater
than 80.
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:
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.
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:
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.
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.
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.
Operator Opposite
== !=
< >=
> <=
<= >
>= <
Page 85
!= ==
eg. !(GrossPay < 0) is equivalent to GrossPay >= 0
!(GrossPay > 2000) is equivalent to GrossPay <= 2000
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
Exercise 4-2
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
• Use the if - else statement in C code programs to solve a selection structured program
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.
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.
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.
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>
int main(void)
{
float GrossPay = 0;
float NettPay = 0;
float Tax = 0;
clrscr();
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
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
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);
/*
* 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
}
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
PSEUDOCODE
PROGRAM Coin2
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
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
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.
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
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.
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 }
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
Page 113
Example Program Tax3NEST
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)
Page 114
We could replace the Calculation of Tax with another recommended solution:
(In this second solution we are working down the scale.)
We could also replace the Calculation of Tax with a series of linear IF-THEN statements (which is
NOT recommended):
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>
NettPay = GrossPay-Tax;
/* 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
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.
Page 122
CHAPTER 7 -
SELECTION: CASE STRUCTURE
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 }
• 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>
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>
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);
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
Exercise 7-5
Using a case structure write a program which inputs a number and a choice ('A','B','C') where a
choice of
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.
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.
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.
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.
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
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.
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
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.
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:
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:
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:
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.
Page 140
Example – Modular Design
Consider the Tax3Nest problem presented previously.
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:
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
The mainline of the pseudocode would appear as module calls for each of the above tasks that need
to be done.
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>
/* prototypes */
float InputGrossPay(void);
float CalcNettPay(float TaxableIncome);
void OutputNettPay(float NettPay);
GrossPay = InputGrossPay();
NettPay = CalcNettPay(GrossPay);
OutputNettPay(NettPay);
return 0;
}
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.
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
• Declare a function in C
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:
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:
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.
Write an integer function called CubeNum that accepts an integer Number as an argument and
returns the cube of that argument.
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.
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:
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.
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.
• 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:
• 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.
To save creating an extra variable to store the answer, this could have been coded as
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:
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.
/******************************************************
* using local variables *
* Count is local to the function Counter *
* Increment is local to the function main *
******************************************************/
#include <stdio.h>
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;
}
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.
/******************************************************
* a formal argument is local to the function it is *
* declared in *
******************************************************/
#include <stdio.h>
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;
}
In main, num = 20
In temp, num = 30
In main, num = 20
Page 155
Returning A Value
To correct the program in Example – parameter passing, you must return the value of Num to the
function main.
In main, num = 20
In temp, num = 30
In main, num = 30
/********************************************************
* 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 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;
}
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.
/******************************************************/
* using global variables *
* Num1 is visible in all functions, *
* Num2 is visible in Func2 and main only *
******************************************************/
#include <stdio.h>
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;
}
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.
/******************************************************
* using local and global variables *
* function2 uses local version of Num1, *
* rather than the global variable Num1 *
******************************************************/
#include <stdio.h>
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;
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.
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
#include <stdio.h>
#include <conio.h>
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;
}
Page 160
Exercise 9-3
#include <stdio.h>
#include <conio.h>
int main(void)
{
int Num1 = 1;
int Num2 = 1;
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.
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.
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?
Page 163
CHAPTER 10 –
ITERATION: THE WHILE LOOP
• Use the while statement in C code programs to solve an iteration structured program
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
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:-
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:
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.
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);
}
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:
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.
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.
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.
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
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>
int main(void)
{
int Number = 0;
int Largest = 0;
int Smallest = 0;
clrscr();
printf("Enter a number: ");
scanf("%i", &Number);
Smallest = Number;
Largest = Number;
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.
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>
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;
}
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.
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:
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 */
/***********************************************************/
/***********************************************************/
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>
Page 182
#define RATE2 0.40
#define MAX_GROSS_PAY 50000
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:
#include <stdio.h>
#include <conio.h>
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;
/******************************************************
* 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;
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.
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.
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:
You should already know how this statement works. Suppose it had been written like this:
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.
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
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
Exercise 10-7
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
Exercise 10-9
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
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 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).
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
• Use the do-while statement in C code programs to solve a repeat loop problem
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.
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 -
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
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;
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.
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
#include <stdio.h>
#include <conio.h>
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);
}
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 */
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
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 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>
/* 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;
}
/************************************************************/
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;
}
/************************************************************/
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.
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.
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.
Page 208
CHAPTER 12 -
ITERATION: THE FOR LOOP
• Use the for statement in C code programs to solve a problem using a fixed looping structure
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.
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.
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;
}
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");
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.
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;
Page 214
Answer = Row * Column;
printf("%i", Answer);
} /* end for loop for each column */
} /* end for loop for each row */
}
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
(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
Exercise 12-2
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
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
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?
7. Which loop is used when the processing must be done at least once?
Page 218
CHAPTER 13 -
STRINGS
• Use the strcmp function in C to compare if one string is equal to, greater than or less
than another string
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];
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.
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.
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");
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>
strcpy(Country,"Japan");
Length = strlen("Australia");
Would set Length to 9. The terminating null character is not included in the length of the string.
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 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".
#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];
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;
}
#define MAX_LEN 20
char Country[MAX_LEN];
int Counter = 0;
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:
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:
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.
*/
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 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.
*/
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
(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
/* 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);
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
Page 233
Page 234
CHAPTER 14 -
ONE-DIMENSIONAL ARRAYS
• 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
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 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:
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:
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.
Index
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.
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:
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
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:
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:
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:
Page 242
This forces every number to take up two characters on the display. They will look like this:
40
2
86
24
7
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.
2. We could prompt separately for each element of the array, as shown here:
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.
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:
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.
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
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.
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.
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:
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:
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 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:
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.
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 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;
/******************************************************
* 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;
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.
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.
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.
/*****************************************************
Program to demonstrate passing an array to a function
******************************************************/
#include <stdio.h>
int main(void)
{
int Repeat = 0;
char Name[11] = {0};
/*
* 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.
2. Write a function called Output Array that will output the elements of the above array.
3. Write a function to input the number of elements of the array and validate this is between 1-20.
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.
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?
Page 260
CHAPTER 15 -
COMBINING TECHNIQUES
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.
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
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 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.
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.
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.
Page 267
Note if writing to an existing file, the original contents of the file will be removed and replaced with the new
contents.
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.
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;
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;
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;
or often :
int main(void)
{
FILE* InFile;
int i;
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
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;
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
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.
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.
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:
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).
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).
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:
If you can’t remember these keys ALT E exposes the EDIT Menu.
File Management
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
• 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.
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
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
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
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.
For example:
PROGRAM Mainline
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
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.
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.
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
Page 293
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
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.
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[])
{
. . …
}
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;
For example:
For example:
typedef enum
{
Start,
Idle,
Active,
}TStates;
typedef struct
{
int x,
int y,
Page 303
}TPoint;
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:
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 :
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 */
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 :
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.
Standard • Commas, whether used as operators or separators, should be placed hard against
the previous symbol and followed by a space.
Standard • Expressions that are too large to fit on a single line should be reformatted over
several lines.
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();
}
for (;;)
{
…
}
c = getchar();
Page 307
while (c != EOF)
{
putchar(c);
c = getchar();
}
do
{
This();
} while (!Finished);
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:
One of the most important aspects of comments is their semantic content. They should therefore contain
either:
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 |
* +----------------+
*/
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
#include <stdio.h>
#include <conio.h>
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;
}
#include <stdio.h>
#include <conio.h>
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;
}
#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;
}
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;
}
#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;
}
#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
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
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
Page 320
Exercise – Sequence Documentation Solutions
Exercise 3-15 POST1
DATA DICTIONARY
INPUTS OUTPUTS
Weight Charge
5 $7.50
10 $15.00
DESK CHECK
DESK CHECK
Page 321
KNOWN RESULTS
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
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
Page 323
Chapter 4 Solutions
(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)?
Page 324
Chapter 5 Solutions
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
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
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
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;
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
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
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>
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);
Page 333
printf("\n\nThe charge is $%0.2f", Charge);
printf("\n\n\nPress any key...");
getch();
return 0;
}
#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;
#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
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
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);
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;
Page 338
printf("\n\n\nPress any key...");
getch();
return 0;
}
#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
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
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
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
/* 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 */
/***********************************************************************/
Page 344
Charge = Charge + Surcharge;
return Charge;
}
/* end function CalcCharge */
/***********************************************************************/
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>
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>
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");
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
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 */
/***********************************************************************/
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>
/* 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 */
/***********************************************************************/
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
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>
/* 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 */
/***********************************************************************/
Page 354
return Charge;
}
/* end function CalcCharge */
/***********************************************************************/
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 ***/
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;
}
#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");
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
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
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>
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 ***/
/***********************************************************************/
Page 363
break;
case 'I': Rate = I_RATE;
break;
case 'S': Rate = S_RATE;
break;
} /* end of switch */
return Rate;
}
/*** end of function CalcRate ***/
/***********************************************************************/
/*
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>
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 ***/
/***********************************************************************/
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>
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 */
/***********************************************************************/
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 */
/***********************************************************************/
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 ***/
/***********************************************************************/
Page 373
}
/*** end of function UpdateArrays ***/
/***********************************************************************/
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;
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>
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>
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>
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;
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>
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);
}
/*Calculations*/
NCost = NDays * NCHARGE;
OCost = ODays * OCHARGE;
PCost = PDays * PCHARGE;
/*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>
/* 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);
/*Calculations*/
NCost = NDays * NCHARGE;
OCost = ODays * OCHARGE;
PCost = PDays * PCHARGE;
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>
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);
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;
}
/***********************************************************/
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;
}
PfeeCal7 - Solution
(Header missing to save space)
/* PfeeCal7 */
Page 390
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
/* 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);
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;
}
/***********************************************************/
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;
}
Page 394
PfeeCal8 - Solution
(Header missing to save space)
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
/*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);
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();
/*Running totals*/
AllTotalCost += ThisTotalCost;
/*Output*/
ShowThisCust(CustID, CustType, NCost, OCost, PCost, ThisTotalCost);
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;
}
/**************************************************************/
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